blob: 8e47acac8cd46ffb54229e1038f56ec0a9d783dd [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 Vishniakouae6229e2019-12-30 16:23:19 -080059using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100060using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080061using android::os::InputEventInjectionResult;
62using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063
Garfield Tane84e6f92019-08-29 17:28:41 -070064namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Prabir Pradhancef936d2021-07-21 16:17:52 +000066namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000067// Temporarily releases a held mutex for the lifetime of the instance.
68// Named to match std::scoped_lock
69class scoped_unlock {
70public:
71 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
72 ~scoped_unlock() { mMutex.lock(); }
73
74private:
75 std::mutex& mMutex;
76};
77
Michael Wrightd02c5b62014-02-10 15:10:22 -080078// Default input dispatching timeout if there is no focused application or paused window
79// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080080const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
81 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
82 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for all pending events to be processed when an app switch
85// key is on the way. This is used to preempt input dispatch and drop input events
86// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080089const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// 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 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070097// Additional key latency in case a connection is still processing some motion events.
98// This will help with the case when a user touched a button that opens a new window,
99// and gives us the chance to dispatch the key to this new window.
100constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000103constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
104
Antonio Kantekea47acb2021-12-23 12:41:25 -0800105// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000106constexpr int LOGTAG_INPUT_INTERACTION = 62000;
107constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000108constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000109
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000110inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111 return systemTime(SYSTEM_TIME_MONOTONIC);
112}
113
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000114inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115 return value ? "true" : "false";
116}
117
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000118inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000119 if (binder == nullptr) {
120 return "<null>";
121 }
122 return StringPrintf("%p", binder.get());
123}
124
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000125inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700126 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
127 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128}
129
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000130bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700132 case AKEY_EVENT_ACTION_DOWN:
133 case AKEY_EVENT_ACTION_UP:
134 return true;
135 default:
136 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 }
138}
139
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000140bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700141 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 ALOGE("Key event has invalid action code 0x%x", action);
143 return false;
144 }
145 return true;
146}
147
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000148bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700150 case AMOTION_EVENT_ACTION_DOWN:
151 case AMOTION_EVENT_ACTION_UP:
152 case AMOTION_EVENT_ACTION_CANCEL:
153 case AMOTION_EVENT_ACTION_MOVE:
154 case AMOTION_EVENT_ACTION_OUTSIDE:
155 case AMOTION_EVENT_ACTION_HOVER_ENTER:
156 case AMOTION_EVENT_ACTION_HOVER_MOVE:
157 case AMOTION_EVENT_ACTION_HOVER_EXIT:
158 case AMOTION_EVENT_ACTION_SCROLL:
159 return true;
160 case AMOTION_EVENT_ACTION_POINTER_DOWN:
161 case AMOTION_EVENT_ACTION_POINTER_UP: {
162 int32_t index = getMotionEventActionPointerIndex(action);
163 return index >= 0 && index < pointerCount;
164 }
165 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
166 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
167 return actionButton != 0;
168 default:
169 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170 }
171}
172
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000173int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500174 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
175}
176
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000177bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
178 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700179 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 ALOGE("Motion event has invalid action code 0x%x", action);
181 return false;
182 }
183 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800184 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 return false;
187 }
188 BitSet32 pointerIdBits;
189 for (size_t i = 0; i < pointerCount; i++) {
190 int32_t id = pointerProperties[i].id;
191 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700192 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
193 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return false;
195 }
196 if (pointerIdBits.hasBit(id)) {
197 ALOGE("Motion event has duplicate pointer id %d", id);
198 return false;
199 }
200 pointerIdBits.markBit(id);
201 }
202 return true;
203}
204
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000205std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000207 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 }
209
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 bool first = true;
212 Region::const_iterator cur = region.begin();
213 Region::const_iterator const tail = region.end();
214 while (cur != tail) {
215 if (first) {
216 first = false;
217 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 cur++;
222 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000223 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224}
225
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000226std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500227 constexpr size_t maxEntries = 50; // max events to print
228 constexpr size_t skipBegin = maxEntries / 2;
229 const size_t skipEnd = queue.size() - maxEntries / 2;
230 // skip from maxEntries / 2 ... size() - maxEntries/2
231 // only print from 0 .. skipBegin and then from skipEnd .. size()
232
233 std::string dump;
234 for (size_t i = 0; i < queue.size(); i++) {
235 const DispatchEntry& entry = *queue[i];
236 if (i >= skipBegin && i < skipEnd) {
237 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
238 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
239 continue;
240 }
241 dump.append(INDENT4);
242 dump += entry.eventEntry->getDescription();
243 dump += StringPrintf(", seq=%" PRIu32
244 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
245 entry.seq, entry.targetFlags, entry.resolvedAction,
246 ns2ms(currentTime - entry.eventEntry->eventTime));
247 if (entry.deliveryTime != 0) {
248 // This entry was delivered, so add information on how long we've been waiting
249 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
250 }
251 dump.append("\n");
252 }
253 return dump;
254}
255
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700256/**
257 * Find the entry in std::unordered_map by key, and return it.
258 * If the entry is not found, return a default constructed entry.
259 *
260 * Useful when the entries are vectors, since an empty vector will be returned
261 * if the entry is not found.
262 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
263 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700264template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000265V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700266 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700267 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800268}
269
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000270bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700271 if (first == second) {
272 return true;
273 }
274
275 if (first == nullptr || second == nullptr) {
276 return false;
277 }
278
279 return first->getToken() == second->getToken();
280}
281
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000282bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000283 if (first == nullptr || second == nullptr) {
284 return false;
285 }
286 return first->applicationInfo.token != nullptr &&
287 first->applicationInfo.token == second->applicationInfo.token;
288}
289
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000290std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
291 std::shared_ptr<EventEntry> eventEntry,
292 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700293 if (inputTarget.useDefaultPointerTransform()) {
294 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700295 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700296 inputTarget.displayTransform,
297 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000298 }
299
300 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
301 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700303 std::vector<PointerCoords> pointerCoords;
304 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000305
306 // Use the first pointer information to normalize all other pointers. This could be any pointer
307 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700308 // uses the transform for the normalized pointer.
309 const ui::Transform& firstPointerTransform =
310 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
311 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000312
313 // Iterate through all pointers in the event to normalize against the first.
314 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
315 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
316 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700317 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000318
319 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700320 // First, apply the current pointer's transform to update the coordinates into
321 // window space.
322 pointerCoords[pointerIndex].transform(currTransform);
323 // Next, apply the inverse transform of the normalized coordinates so the
324 // current coordinates are transformed into the normalized coordinate space.
325 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000326 }
327
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700328 std::unique_ptr<MotionEntry> combinedMotionEntry =
329 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
330 motionEntry.deviceId, motionEntry.source,
331 motionEntry.displayId, motionEntry.policyFlags,
332 motionEntry.action, motionEntry.actionButton,
333 motionEntry.flags, motionEntry.metaState,
334 motionEntry.buttonState, motionEntry.classification,
335 motionEntry.edgeFlags, motionEntry.xPrecision,
336 motionEntry.yPrecision, motionEntry.xCursorPosition,
337 motionEntry.yCursorPosition, motionEntry.downTime,
338 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000339 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000340
341 if (motionEntry.injectionState) {
342 combinedMotionEntry->injectionState = motionEntry.injectionState;
343 combinedMotionEntry->injectionState->refCount += 1;
344 }
345
346 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700347 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700348 firstPointerTransform, inputTarget.displayTransform,
349 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350 return dispatchEntry;
351}
352
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000353status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
354 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700355 std::unique_ptr<InputChannel> uniqueServerChannel;
356 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
357
358 serverChannel = std::move(uniqueServerChannel);
359 return result;
360}
361
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500362template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000363bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500364 if (lhs == nullptr && rhs == nullptr) {
365 return true;
366 }
367 if (lhs == nullptr || rhs == nullptr) {
368 return false;
369 }
370 return *lhs == *rhs;
371}
372
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000373KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000374 KeyEvent event;
375 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
376 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
377 entry.repeatCount, entry.downTime, entry.eventTime);
378 return event;
379}
380
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000381bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000382 // Do not keep track of gesture monitors. They receive every event and would disproportionately
383 // affect the statistics.
384 if (connection.monitor) {
385 return false;
386 }
387 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
388 if (!connection.responsive) {
389 return false;
390 }
391 return true;
392}
393
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000394bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000395 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
396 const int32_t& inputEventId = eventEntry.id;
397 if (inputEventId != dispatchEntry.resolvedEventId) {
398 // Event was transmuted
399 return false;
400 }
401 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
402 return false;
403 }
404 // Only track latency for events that originated from hardware
405 if (eventEntry.isSynthesized()) {
406 return false;
407 }
408 const EventEntry::Type& inputEventEntryType = eventEntry.type;
409 if (inputEventEntryType == EventEntry::Type::KEY) {
410 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
411 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
412 return false;
413 }
414 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
415 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
416 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
417 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
418 return false;
419 }
420 } else {
421 // Not a key or a motion
422 return false;
423 }
424 if (!shouldReportMetricsForConnection(connection)) {
425 return false;
426 }
427 return true;
428}
429
Prabir Pradhancef936d2021-07-21 16:17:52 +0000430/**
431 * Connection is responsive if it has no events in the waitQueue that are older than the
432 * current time.
433 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000434bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000435 const nsecs_t currentTime = now();
436 for (const DispatchEntry* entry : connection.waitQueue) {
437 if (entry->timeoutTime < currentTime) {
438 return false;
439 }
440 }
441 return true;
442}
443
Antonio Kantekf16f2832021-09-28 04:39:20 +0000444// Returns true if the event type passed as argument represents a user activity.
445bool isUserActivityEvent(const EventEntry& eventEntry) {
446 switch (eventEntry.type) {
447 case EventEntry::Type::FOCUS:
448 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
449 case EventEntry::Type::DRAG:
450 case EventEntry::Type::TOUCH_MODE_CHANGED:
451 case EventEntry::Type::SENSOR:
452 case EventEntry::Type::CONFIGURATION_CHANGED:
453 return false;
454 case EventEntry::Type::DEVICE_RESET:
455 case EventEntry::Type::KEY:
456 case EventEntry::Type::MOTION:
457 return true;
458 }
459}
460
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800461// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhandb326da2023-03-09 04:51:55 +0000462bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhand65552b2021-10-07 11:23:50 -0700463 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800464 const auto inputConfig = windowInfo.inputConfig;
465 if (windowInfo.displayId != displayId ||
466 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800467 return false;
468 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700469 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800470 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800471 return false;
472 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800473 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800474 return false;
475 }
476 return true;
477}
478
Prabir Pradhand65552b2021-10-07 11:23:50 -0700479bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
480 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
481 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
482 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
483}
484
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000485// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
486// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
487// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
488// be sent to such a window, but it is not a foreground event and doesn't use
489// InputTarget::FLAG_FOREGROUND.
490bool canReceiveForegroundTouches(const WindowInfo& info) {
491 // A non-touchable window can still receive touch events (e.g. in the case of
492 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
493 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
494}
495
Antonio Kantek48710e42022-03-24 14:19:30 -0700496bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
497 if (windowHandle == nullptr) {
498 return false;
499 }
500 const WindowInfo* windowInfo = windowHandle->getInfo();
501 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
502 return true;
503 }
504 return false;
505}
506
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000507// Checks targeted injection using the window's owner's uid.
508// Returns an empty string if an entry can be sent to the given window, or an error message if the
509// entry is a targeted injection whose uid target doesn't match the window owner.
510std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
511 const EventEntry& entry) {
512 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
513 // The event was not injected, or the injected event does not target a window.
514 return {};
515 }
516 const int32_t uid = *entry.injectionState->targetUid;
517 if (window == nullptr) {
518 return StringPrintf("No valid window target for injection into uid %d.", uid);
519 }
520 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
521 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
522 "owned by uid %d.",
523 uid, window->getName().c_str(), window->getInfo()->ownerUid);
524 }
525 return {};
526}
527
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000528} // namespace
529
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530// --- InputDispatcher ---
531
Garfield Tan00f511d2019-06-12 16:55:40 -0700532InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800533 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
534
535InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
536 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700537 : mPolicy(policy),
538 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700539 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800540 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700541 mAppSwitchSawKeyDown(false),
542 mAppSwitchDueTime(LONG_LONG_MAX),
543 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800544 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700545 mDispatchEnabled(false),
546 mDispatchFrozen(false),
547 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800548 // mInTouchMode will be initialized by the WindowManager to the default device config.
549 // To avoid leaking stack in case that call never comes, and for tests,
550 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000551 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100552 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000553 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800554 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800555 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000556 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800557 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800559 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700561 mWindowInfoListener = new DispatcherWindowListener(*this);
562 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
563
Yi Kong9b14ac62018-07-17 13:48:38 -0700564 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565
566 policy->getDispatcherConfiguration(&mConfig);
567}
568
569InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000570 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571
Prabir Pradhancef936d2021-07-21 16:17:52 +0000572 resetKeyRepeatLocked();
573 releasePendingEventLocked();
574 drainInboundQueueLocked();
575 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000577 while (!mConnectionsByToken.empty()) {
578 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000579 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
580 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 }
582}
583
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700584status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700585 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700586 return ALREADY_EXISTS;
587 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700588 mThread = std::make_unique<InputThread>(
589 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
590 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591}
592
593status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700594 if (mThread && mThread->isCallingThread()) {
595 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596 return INVALID_OPERATION;
597 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700598 mThread.reset();
599 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600}
601
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602void InputDispatcher::dispatchOnce() {
603 nsecs_t nextWakeupTime = LONG_LONG_MAX;
604 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800605 std::scoped_lock _l(mLock);
606 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607
608 // Run a dispatch loop if there are no pending commands.
609 // The dispatch loop might enqueue commands to run afterwards.
610 if (!haveCommandsLocked()) {
611 dispatchOnceInnerLocked(&nextWakeupTime);
612 }
613
614 // Run all pending commands if there are any.
615 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000616 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 nextWakeupTime = LONG_LONG_MIN;
618 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800619
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700620 // If we are still waiting for ack on some events,
621 // we might have to wake up earlier to check if an app is anr'ing.
622 const nsecs_t nextAnrCheck = processAnrsLocked();
623 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
624
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800625 // We are about to enter an infinitely long sleep, because we have no commands or
626 // pending or queued events
627 if (nextWakeupTime == LONG_LONG_MAX) {
628 mDispatcherEnteredIdle.notify_all();
629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 } // release lock
631
632 // Wait for callback or timeout or wake. (make sure we round up, not down)
633 nsecs_t currentTime = now();
634 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
635 mLooper->pollOnce(timeoutMillis);
636}
637
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500639 * Raise ANR if there is no focused window.
640 * Before the ANR is raised, do a final state check:
641 * 1. The currently focused application must be the same one we are waiting for.
642 * 2. Ensure we still don't have a focused window.
643 */
644void InputDispatcher::processNoFocusedWindowAnrLocked() {
645 // Check if the application that we are waiting for is still focused.
646 std::shared_ptr<InputApplicationHandle> focusedApplication =
647 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
648 if (focusedApplication == nullptr ||
649 focusedApplication->getApplicationToken() !=
650 mAwaitedFocusedApplication->getApplicationToken()) {
651 // Unexpected because we should have reset the ANR timer when focused application changed
652 ALOGE("Waited for a focused window, but focused application has already changed to %s",
653 focusedApplication->getName().c_str());
654 return; // The focused application has changed.
655 }
656
chaviw98318de2021-05-19 16:45:23 -0500657 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500658 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
659 if (focusedWindowHandle != nullptr) {
660 return; // We now have a focused window. No need for ANR.
661 }
662 onAnrLocked(mAwaitedFocusedApplication);
663}
664
665/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700666 * Check if any of the connections' wait queues have events that are too old.
667 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
668 * Return the time at which we should wake up next.
669 */
670nsecs_t InputDispatcher::processAnrsLocked() {
671 const nsecs_t currentTime = now();
672 nsecs_t nextAnrCheck = LONG_LONG_MAX;
673 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
674 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
675 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500676 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700677 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500678 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700679 return LONG_LONG_MIN;
680 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500681 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700682 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
683 }
684 }
685
686 // Check if any connection ANRs are due
687 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
688 if (currentTime < nextAnrCheck) { // most likely scenario
689 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
690 }
691
692 // If we reached here, we have an unresponsive connection.
693 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
694 if (connection == nullptr) {
695 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
696 return nextAnrCheck;
697 }
698 connection->responsive = false;
699 // Stop waking up for this unresponsive connection
700 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000701 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700702 return LONG_LONG_MIN;
703}
704
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800705std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
706 const sp<Connection>& connection) {
707 if (connection->monitor) {
708 return mMonitorDispatchingTimeout;
709 }
710 const sp<WindowInfoHandle> window =
711 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500713 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500715 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716}
717
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
719 nsecs_t currentTime = now();
720
Jeff Browndc5992e2014-04-11 01:27:26 -0700721 // Reset the key repeat timer whenever normal dispatch is suspended while the
722 // device is in a non-interactive state. This is to ensure that we abort a key
723 // repeat if the device is just coming out of sleep.
724 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 resetKeyRepeatLocked();
726 }
727
728 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
729 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100730 if (DEBUG_FOCUS) {
731 ALOGD("Dispatch frozen. Waiting some more.");
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 return;
734 }
735
736 // Optimize latency of app switches.
737 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
738 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
739 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
740 if (mAppSwitchDueTime < *nextWakeupTime) {
741 *nextWakeupTime = mAppSwitchDueTime;
742 }
743
744 // Ready to start a new event.
745 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700747 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 if (isAppSwitchDue) {
749 // The inbound queue is empty so the app switch key we were waiting
750 // for will never arrive. Stop waiting for it.
751 resetPendingAppSwitchLocked(false);
752 isAppSwitchDue = false;
753 }
754
755 // Synthesize a key repeat if appropriate.
756 if (mKeyRepeatState.lastKeyEntry) {
757 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
758 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
759 } else {
760 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
761 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
762 }
763 }
764 }
765
766 // Nothing to do if there is no pending event.
767 if (!mPendingEvent) {
768 return;
769 }
770 } else {
771 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 mPendingEvent = mInboundQueue.front();
773 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 traceInboundQueueLengthLocked();
775 }
776
777 // Poke user activity for this event.
778 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700779 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
782
783 // Now we have an event to dispatch.
784 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700787 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700791 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700795 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700799 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700800 const ConfigurationChangedEntry& typedEntry =
801 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700807 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 const DeviceResetEntry& typedEntry =
809 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700810 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 break;
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100815 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 std::shared_ptr<FocusEntry> typedEntry =
817 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100818 dispatchFocusLocked(currentTime, typedEntry);
819 done = true;
820 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
821 break;
822 }
823
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700824 case EventEntry::Type::TOUCH_MODE_CHANGED: {
825 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
826 dispatchTouchModeChangeLocked(currentTime, typedEntry);
827 done = true;
828 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
829 break;
830 }
831
Prabir Pradhan99987712020-11-10 18:43:05 -0800832 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
833 const auto typedEntry =
834 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
835 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
836 done = true;
837 break;
838 }
839
arthurhungb89ccb02020-12-30 16:19:01 +0800840 case EventEntry::Type::DRAG: {
841 std::shared_ptr<DragEntry> typedEntry =
842 std::static_pointer_cast<DragEntry>(mPendingEvent);
843 dispatchDragLocked(currentTime, typedEntry);
844 done = true;
845 break;
846 }
847
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700848 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700851 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 resetPendingAppSwitchLocked(true);
853 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700854 } else if (dropReason == DropReason::NOT_DROPPED) {
855 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 }
857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
862 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700864 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 break;
866 }
867
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700868 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 std::shared_ptr<MotionEntry> motionEntry =
870 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
872 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
878 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 }
Chris Yef59a2f42020-10-16 12:55:26 -0700883
884 case EventEntry::Type::SENSOR: {
885 std::shared_ptr<SensorEntry> sensorEntry =
886 std::static_pointer_cast<SensorEntry>(mPendingEvent);
887 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
888 dropReason = DropReason::APP_SWITCH;
889 }
890 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
891 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
892 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
893 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
894 dropReason = DropReason::STALE;
895 }
896 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
897 done = true;
898 break;
899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901
902 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Michael Wright3a981722015-06-10 15:26:13 +0100906 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
908 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
911}
912
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800913bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
914 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
915}
916
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700917/**
918 * Return true if the events preceding this incoming motion event should be dropped
919 * Return false otherwise (the default behaviour)
920 */
921bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700922 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700923 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700924
925 // Optimize case where the current application is unresponsive and the user
926 // decides to touch a window in a different application.
927 // If the application takes too long to catch up then we drop all events preceding
928 // the touch into the other window.
929 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 int32_t displayId = motionEntry.displayId;
Prabir Pradhandb326da2023-03-09 04:51:55 +0000931 const float x = motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X);
932 const float y = motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700933
934 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500935 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700936 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 touchedWindowHandle->getApplicationToken() !=
939 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700940 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700941 ALOGI("Pruning input queue because user touched a different application while waiting "
942 "for %s",
943 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700944 return true;
945 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800947 // Alternatively, maybe there's a spy window that could handle this event.
948 const std::vector<sp<WindowInfoHandle>> touchedSpies =
949 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
950 for (const auto& windowHandle : touchedSpies) {
951 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000952 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800953 // This spy window could take more input. Drop all events preceding this
954 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700955 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800956 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700957 mAwaitedFocusedApplication->getName().c_str());
958 return true;
959 }
960 }
961 }
962
963 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
964 // yet been processed by some connections, the dispatcher will wait for these motion
965 // events to be processed before dispatching the key event. This is because these motion events
966 // may cause a new window to be launched, which the user might expect to receive focus.
967 // To prevent waiting forever for such events, just send the key to the currently focused window
968 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
969 ALOGD("Received a new pointer down event, stop waiting for events to process and "
970 "just send the pending key event to the focused window.");
971 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700972 }
973 return false;
974}
975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700977 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 mInboundQueue.push_back(std::move(newEntry));
979 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 traceInboundQueueLengthLocked();
981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700983 case EventEntry::Type::KEY: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000984 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
985 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 // Optimize app switch latency.
987 // If the application takes too long to catch up then we drop all events preceding
988 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700989 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700991 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700993 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000995 if (DEBUG_APP_SWITCH) {
996 ALOGD("App switch is pending!");
997 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700998 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 mAppSwitchSawKeyDown = false;
1000 needWake = true;
1001 }
1002 }
1003 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001004
1005 // If a new up event comes in, and the pending event with same key code has been asked
1006 // to try again later because of the policy. We have to reset the intercept key wake up
1007 // time for it may have been handled in the policy and could be dropped.
1008 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1009 mPendingEvent->type == EventEntry::Type::KEY) {
1010 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1011 if (pendingKey.keyCode == keyEntry.keyCode &&
1012 pendingKey.interceptKeyResult ==
1013 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1014 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1015 pendingKey.interceptKeyWakeupTime = 0;
1016 needWake = true;
1017 }
1018 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 break;
1020 }
1021
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001022 case EventEntry::Type::MOTION: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001023 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1024 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1026 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001027 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001031 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001032 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1033 break;
1034 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001035 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001036 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001037 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001038 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001039 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1040 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001041 // nothing to do
1042 break;
1043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045
1046 return needWake;
1047}
1048
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001050 // Do not store sensor event in recent queue to avoid flooding the queue.
1051 if (entry->type != EventEntry::Type::SENSOR) {
1052 mRecentQueue.push_back(entry);
1053 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001054 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001055 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057}
1058
Prabir Pradhandb326da2023-03-09 04:51:55 +00001059sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1060 TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001061 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001062 bool addOutsideTargets,
1063 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001064 if (addOutsideTargets && touchState == nullptr) {
1065 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001068 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001069 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001070 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001071 continue;
1072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001074 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001075 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001076 return windowHandle;
1077 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001078
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001079 if (addOutsideTargets &&
1080 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001081 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1082 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 }
1084 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001085 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086}
1087
Prabir Pradhand65552b2021-10-07 11:23:50 -07001088std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhandb326da2023-03-09 04:51:55 +00001089 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001090 // Traverse windows from front to back and gather the touched spy windows.
1091 std::vector<sp<WindowInfoHandle>> spyWindows;
1092 const auto& windowHandles = getWindowHandlesLocked(displayId);
1093 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1094 const WindowInfo& info = *windowHandle->getInfo();
1095
Prabir Pradhand65552b2021-10-07 11:23:50 -07001096 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001097 continue;
1098 }
1099 if (!info.isSpy()) {
1100 // The first touched non-spy window was found, so return the spy windows touched so far.
1101 return spyWindows;
1102 }
1103 spyWindows.push_back(windowHandle);
1104 }
1105 return spyWindows;
1106}
1107
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001108void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 const char* reason;
1110 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001111 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001112 if (DEBUG_INBOUND_EVENT_DETAILS) {
1113 ALOGD("Dropped event because policy consumed it.");
1114 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 reason = "inbound event was dropped because the policy consumed it";
1116 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001117 case DropReason::DISABLED:
1118 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 ALOGI("Dropped event because input dispatch is disabled.");
1120 }
1121 reason = "inbound event was dropped because input dispatch is disabled";
1122 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 ALOGI("Dropped event because of pending overdue app switch.");
1125 reason = "inbound event was dropped because of pending overdue app switch";
1126 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001127 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 ALOGI("Dropped event because the current application is not responding and the user "
1129 "has started interacting with a different application.");
1130 reason = "inbound event was dropped because the current application is not responding "
1131 "and the user has started interacting with a different application";
1132 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001133 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 ALOGI("Dropped event because it is stale.");
1135 reason = "inbound event was dropped because it is stale";
1136 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001137 case DropReason::NO_POINTER_CAPTURE:
1138 ALOGI("Dropped event because there is no window with Pointer Capture.");
1139 reason = "inbound event was dropped because there is no window with Pointer Capture";
1140 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001141 case DropReason::NOT_DROPPED: {
1142 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 }
1146
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001147 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001148 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1150 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001151 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001153 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001154 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1155 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001156 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1157 synthesizeCancelationEventsForAllConnectionsLocked(options);
1158 } else {
1159 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1160 synthesizeCancelationEventsForAllConnectionsLocked(options);
1161 }
1162 break;
1163 }
Chris Yef59a2f42020-10-16 12:55:26 -07001164 case EventEntry::Type::SENSOR: {
1165 break;
1166 }
arthurhungb89ccb02020-12-30 16:19:01 +08001167 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1168 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001169 break;
1170 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001171 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001172 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001173 case EventEntry::Type::CONFIGURATION_CHANGED:
1174 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001175 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001176 break;
1177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 }
1179}
1180
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001181static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001182 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1183 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184}
1185
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001186bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1187 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1188 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1189 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190}
1191
1192bool InputDispatcher::isAppSwitchPendingLocked() {
1193 return mAppSwitchDueTime != LONG_LONG_MAX;
1194}
1195
1196void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1197 mAppSwitchDueTime = LONG_LONG_MAX;
1198
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001199 if (DEBUG_APP_SWITCH) {
1200 if (handled) {
1201 ALOGD("App switch has arrived.");
1202 } else {
1203 ALOGD("App switch was abandoned.");
1204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206}
1207
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001209 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210}
1211
Prabir Pradhancef936d2021-07-21 16:17:52 +00001212bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001213 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 return false;
1215 }
1216
1217 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001218 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001219 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001220 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1221 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001222 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 return true;
1224}
1225
Prabir Pradhancef936d2021-07-21 16:17:52 +00001226void InputDispatcher::postCommandLocked(Command&& command) {
1227 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228}
1229
1230void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001231 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 releaseInboundEventLocked(entry);
1235 }
1236 traceInboundQueueLengthLocked();
1237}
1238
1239void InputDispatcher::releasePendingEventLocked() {
1240 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001242 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244}
1245
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001248 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001249 if (DEBUG_DISPATCH_CYCLE) {
1250 ALOGD("Injected inbound event was dropped.");
1251 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001255 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
1257 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258}
1259
1260void InputDispatcher::resetKeyRepeatLocked() {
1261 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001262 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
1264}
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1267 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268
Michael Wright2e732952014-09-24 13:26:59 -07001269 uint32_t policyFlags = entry->policyFlags &
1270 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272 std::shared_ptr<KeyEntry> newEntry =
1273 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1274 entry->source, entry->displayId, policyFlags, entry->action,
1275 entry->flags, entry->keyCode, entry->scanCode,
1276 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278 newEntry->syntheticRepeat = true;
1279 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282}
1283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001286 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1287 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
1290 // Reset key repeating in case a keyboard device was added or removed or something.
1291 resetKeyRepeatLocked();
1292
1293 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001294 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1295 scoped_unlock unlock(mLock);
1296 mPolicy->notifyConfigurationChanged(eventTime);
1297 };
1298 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 return true;
1300}
1301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1303 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001304 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1305 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1306 entry.deviceId);
1307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308
liushenxiang42232912021-05-21 20:24:09 +08001309 // Reset key repeating in case a keyboard device was disabled or enabled.
1310 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1311 resetKeyRepeatLocked();
1312 }
1313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001314 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 synthesizeCancelationEventsForAllConnectionsLocked(options);
1317 return true;
1318}
1319
Vishnu Nairad321cd2020-08-20 16:40:21 -07001320void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001321 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001322 if (mPendingEvent != nullptr) {
1323 // Move the pending event to the front of the queue. This will give the chance
1324 // for the pending event to get dispatched to the newly focused window
1325 mInboundQueue.push_front(mPendingEvent);
1326 mPendingEvent = nullptr;
1327 }
1328
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001329 std::unique_ptr<FocusEntry> focusEntry =
1330 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1331 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001332
1333 // This event should go to the front of the queue, but behind all other focus events
1334 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001335 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001336 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001337 [](const std::shared_ptr<EventEntry>& event) {
1338 return event->type == EventEntry::Type::FOCUS;
1339 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001340
1341 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001342 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001343}
1344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001345void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001346 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001347 if (channel == nullptr) {
1348 return; // Window has gone away
1349 }
1350 InputTarget target;
1351 target.inputChannel = channel;
1352 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1353 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001354 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1355 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001356 std::string reason = std::string("reason=").append(entry->reason);
1357 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001358 dispatchEventLocked(currentTime, entry, {target});
1359}
1360
Prabir Pradhan99987712020-11-10 18:43:05 -08001361void InputDispatcher::dispatchPointerCaptureChangedLocked(
1362 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1363 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001364 dropReason = DropReason::NOT_DROPPED;
1365
Prabir Pradhan99987712020-11-10 18:43:05 -08001366 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001367 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001368
1369 if (entry->pointerCaptureRequest.enable) {
1370 // Enable Pointer Capture.
1371 if (haveWindowWithPointerCapture &&
1372 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001373 // This can happen if pointer capture is disabled and re-enabled before we notify the
1374 // app of the state change, so there is no need to notify the app.
1375 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1376 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377 }
1378 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001379 // This can happen if a window requests capture and immediately releases capture.
1380 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001381 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001382 return;
1383 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001384 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1385 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1386 return;
1387 }
1388
Vishnu Nairc519ff72021-01-21 08:23:08 -08001389 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1391 mWindowTokenWithPointerCapture = token;
1392 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 // Disable Pointer Capture.
1394 // We do not check if the sequence number matches for requests to disable Pointer Capture
1395 // for two reasons:
1396 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1397 // to disable capture with the same sequence number: one generated by
1398 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1399 // Capture being disabled in InputReader.
1400 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1401 // actual Pointer Capture state that affects events being generated by input devices is
1402 // in InputReader.
1403 if (!haveWindowWithPointerCapture) {
1404 // Pointer capture was already forcefully disabled because of focus change.
1405 dropReason = DropReason::NOT_DROPPED;
1406 return;
1407 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001408 token = mWindowTokenWithPointerCapture;
1409 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001410 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001411 setPointerCaptureLocked(false);
1412 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001413 }
1414
1415 auto channel = getInputChannelLocked(token);
1416 if (channel == nullptr) {
1417 // Window has gone away, clean up Pointer Capture state.
1418 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001419 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001420 setPointerCaptureLocked(false);
1421 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001422 return;
1423 }
1424 InputTarget target;
1425 target.inputChannel = channel;
1426 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1427 entry->dispatchInProgress = true;
1428 dispatchEventLocked(currentTime, entry, {target});
1429
1430 dropReason = DropReason::NOT_DROPPED;
1431}
1432
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001433void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1434 const std::shared_ptr<TouchModeEntry>& entry) {
1435 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1436 getWindowHandlesLocked(mFocusedDisplayId);
1437 if (windowHandles.empty()) {
1438 return;
1439 }
1440 const std::vector<InputTarget> inputTargets =
1441 getInputTargetsFromWindowHandlesLocked(windowHandles);
1442 if (inputTargets.empty()) {
1443 return;
1444 }
1445 entry->dispatchInProgress = true;
1446 dispatchEventLocked(currentTime, entry, inputTargets);
1447}
1448
1449std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1450 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1451 std::vector<InputTarget> inputTargets;
1452 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1453 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1454 const sp<IBinder>& token = handle->getToken();
1455 if (token == nullptr) {
1456 continue;
1457 }
1458 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1459 if (channel == nullptr) {
1460 continue; // Window has gone away
1461 }
1462 InputTarget target;
1463 target.inputChannel = channel;
1464 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1465 inputTargets.push_back(target);
1466 }
1467 return inputTargets;
1468}
1469
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001470bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 if (!entry->dispatchInProgress) {
1474 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1475 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1476 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1477 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001478 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 // We have seen two identical key downs in a row which indicates that the device
1480 // driver is automatically generating key repeats itself. We take note of the
1481 // repeat here, but we disable our own next key repeat timer since it is clear that
1482 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001483 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1484 // Make sure we don't get key down from a different device. If a different
1485 // device Id has same key pressed down, the new device Id will replace the
1486 // current one to hold the key repeat with repeat count reset.
1487 // In the future when got a KEY_UP on the device id, drop it and do not
1488 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1490 resetKeyRepeatLocked();
1491 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1492 } else {
1493 // Not a repeat. Save key down state in case we do see a repeat later.
1494 resetKeyRepeatLocked();
1495 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1496 }
1497 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001498 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1499 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001500 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001501 if (DEBUG_INBOUND_EVENT_DETAILS) {
1502 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1503 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001504 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 resetKeyRepeatLocked();
1506 }
1507
1508 if (entry->repeatCount == 1) {
1509 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1510 } else {
1511 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1512 }
1513
1514 entry->dispatchInProgress = true;
1515
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001516 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
1518
1519 // Handle case where the policy asked us to try again later last time.
1520 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1521 if (currentTime < entry->interceptKeyWakeupTime) {
1522 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1523 *nextWakeupTime = entry->interceptKeyWakeupTime;
1524 }
1525 return false; // wait until next wakeup
1526 }
1527 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1528 entry->interceptKeyWakeupTime = 0;
1529 }
1530
1531 // Give the policy a chance to intercept the key.
1532 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1533 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001534 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001535 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001536
1537 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1538 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1539 };
1540 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 return false; // wait for the command to run
1542 } else {
1543 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1544 }
1545 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001546 if (*dropReason == DropReason::NOT_DROPPED) {
1547 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 }
1549 }
1550
1551 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001552 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001553 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001554 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1555 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001556 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return true;
1558 }
1559
1560 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001561 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001562 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001563 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return false;
1566 }
1567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001568 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return true;
1571 }
1572
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001573 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001574 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575
1576 // Dispatch the key.
1577 dispatchEventLocked(currentTime, entry, inputTargets);
1578 return true;
1579}
1580
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1583 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1584 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1585 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1586 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1587 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1588 entry.metaState, entry.repeatCount, entry.downTime);
1589 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590}
1591
Prabir Pradhancef936d2021-07-21 16:17:52 +00001592void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1593 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001594 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001595 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1596 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1597 "source=0x%x, sensorType=%s",
1598 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001599 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001601 auto command = [this, entry]() REQUIRES(mLock) {
1602 scoped_unlock unlock(mLock);
1603
1604 if (entry->accuracyChanged) {
1605 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1606 }
1607 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1608 entry->hwTimestamp, entry->values);
1609 };
1610 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001611}
1612
1613bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001614 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1615 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001616 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001617 }
Chris Yef59a2f42020-10-16 12:55:26 -07001618 { // acquire lock
1619 std::scoped_lock _l(mLock);
1620
1621 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1622 std::shared_ptr<EventEntry> entry = *it;
1623 if (entry->type == EventEntry::Type::SENSOR) {
1624 it = mInboundQueue.erase(it);
1625 releaseInboundEventLocked(entry);
1626 }
1627 }
1628 }
1629 return true;
1630}
1631
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001632bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001633 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001634 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001636 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 entry->dispatchInProgress = true;
1638
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001639 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
1641
1642 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001643 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001644 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1646 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 return true;
1648 }
1649
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001650 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001653 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654
1655 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001656 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 if (isPointerEvent) {
1658 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001660 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 } else {
1663 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001665 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001667 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 return false;
1669 }
1670
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001671 setInjectionResult(*entry, injectionResult);
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001672 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001673 return true;
1674 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001675 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001676 CancelationOptions::Mode mode(isPointerEvent
1677 ? CancelationOptions::CANCEL_POINTER_EVENTS
1678 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1679 CancelationOptions options(mode, "input event injection failed");
1680 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 return true;
1682 }
1683
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001684 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001685 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686
1687 // Dispatch the motion.
1688 if (conflictingPointerActions) {
1689 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001690 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 synthesizeCancelationEventsForAllConnectionsLocked(options);
1692 }
1693 dispatchEventLocked(currentTime, entry, inputTargets);
1694 return true;
1695}
1696
chaviw98318de2021-05-19 16:45:23 -05001697void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001698 bool isExiting, const int32_t rawX,
1699 const int32_t rawY) {
1700 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001701 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001702 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1703 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001704
1705 enqueueInboundEventLocked(std::move(dragEntry));
1706}
1707
1708void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1709 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1710 if (channel == nullptr) {
1711 return; // Window has gone away
1712 }
1713 InputTarget target;
1714 target.inputChannel = channel;
1715 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1716 entry->dispatchInProgress = true;
1717 dispatchEventLocked(currentTime, entry, {target});
1718}
1719
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001720void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001721 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1722 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1723 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001724 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001725 "metaState=0x%x, buttonState=0x%x,"
1726 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1727 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001728 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1729 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1730 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001732 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1733 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1734 "x=%f, y=%f, pressure=%f, size=%f, "
1735 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1736 "orientation=%f",
1737 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1738 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1739 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1740 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1741 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1742 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1743 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1744 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1745 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1746 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749}
1750
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001751void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1752 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001753 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001754 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001755 if (DEBUG_DISPATCH_CYCLE) {
1756 ALOGD("dispatchEventToCurrentInputTargets");
1757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001759 updateInteractionTokensLocked(*eventEntry, inputTargets);
1760
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1762
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001765 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001766 sp<Connection> connection =
1767 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001768 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001769 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001771 if (DEBUG_FOCUS) {
1772 ALOGD("Dropping event delivery to target with channel '%s' because it "
1773 "is no longer registered with the input dispatcher.",
1774 inputTarget.inputChannel->getName().c_str());
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 }
1777 }
1778}
1779
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001780void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1781 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1782 // If the policy decides to close the app, we will get a channel removal event via
1783 // unregisterInputChannel, and will clean up the connection that way. We are already not
1784 // sending new pointers to the connection when it blocked, but focused events will continue to
1785 // pile up.
1786 ALOGW("Canceling events for %s because it is unresponsive",
1787 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001788 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001789 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1790 "application not responding");
1791 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793}
1794
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001795void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001796 if (DEBUG_FOCUS) {
1797 ALOGD("Resetting ANR timeouts.");
1798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799
1800 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001801 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001802 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803}
1804
Tiger Huang721e26f2018-07-24 22:26:19 +08001805/**
1806 * Get the display id that the given event should go to. If this event specifies a valid display id,
1807 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1808 * Focused display is the display that the user most recently interacted with.
1809 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001810int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001811 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001813 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1815 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001816 break;
1817 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001818 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1820 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 break;
1822 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001823 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001824 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001825 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001826 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001827 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001828 case EventEntry::Type::SENSOR:
1829 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001830 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001831 return ADISPLAY_ID_NONE;
1832 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001833 }
1834 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1835}
1836
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001837bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1838 const char* focusedWindowName) {
1839 if (mAnrTracker.empty()) {
1840 // already processed all events that we waited for
1841 mKeyIsWaitingForEventsTimeout = std::nullopt;
1842 return false;
1843 }
1844
1845 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1846 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001847 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001848 mKeyIsWaitingForEventsTimeout = currentTime +
1849 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1850 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001851 return true;
1852 }
1853
1854 // We still have pending events, and already started the timer
1855 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1856 return true; // Still waiting
1857 }
1858
1859 // Waited too long, and some connection still hasn't processed all motions
1860 // Just send the key to the focused window
1861 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1862 focusedWindowName);
1863 mKeyIsWaitingForEventsTimeout = std::nullopt;
1864 return false;
1865}
1866
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001867InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1868 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1869 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001870 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871
Tiger Huang721e26f2018-07-24 22:26:19 +08001872 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001873 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001874 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001875 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1876
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 // If there is no currently focused window and no focused application
1878 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1880 ALOGI("Dropping %s event because there is no focused window or focused application in "
1881 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001882 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001883 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 }
1885
Vishnu Nair062a8672021-09-03 16:07:44 -07001886 // Drop key events if requested by input feature
1887 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1888 return InputEventInjectionResult::FAILED;
1889 }
1890
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001891 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1892 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1893 // start interacting with another application via touch (app switch). This code can be removed
1894 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1895 // an app is expected to have a focused window.
1896 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1897 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1898 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001899 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1900 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1901 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001903 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 ALOGW("Waiting because no window has focus but %s may eventually add a "
1905 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001906 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001909 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1910 // Already raised ANR. Drop the event
1911 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001912 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001914 } else {
1915 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001917 }
1918 }
1919
1920 // we have a valid, non-null focused window
1921 resetNoFocusedWindowTimeoutLocked();
1922
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001923 // Verify targeted injection.
1924 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1925 ALOGW("Dropping injected event: %s", (*err).c_str());
1926 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
1928
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001929 if (focusedWindowHandle->getInfo()->inputConfig.test(
1930 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 }
1934
1935 // If the event is a key event, then we must wait for all previous events to
1936 // complete before delivering it because previous events may have the
1937 // side-effect of transferring focus to a different window and we want to
1938 // ensure that the following keys are sent to the new window.
1939 //
1940 // Suppose the user touches a button in a window then immediately presses "A".
1941 // If the button causes a pop-up window to appear then we want to ensure that
1942 // the "A" key is delivered to the new pop-up window. This is because users
1943 // often anticipate pending UI changes when typing on a keyboard.
1944 // To obtain this behavior, we must serialize key events with respect to all
1945 // prior input events.
1946 if (entry.type == EventEntry::Type::KEY) {
1947 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1948 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001949 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 }
1952
1953 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001954 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001955 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1956 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957
1958 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960}
1961
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962/**
1963 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1964 * that are currently unresponsive.
1965 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001966std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1967 const std::vector<Monitor>& monitors) const {
1968 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001970 [this](const Monitor& monitor) REQUIRES(mLock) {
1971 sp<Connection> connection =
1972 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001973 if (connection == nullptr) {
1974 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001975 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001976 return false;
1977 }
1978 if (!connection->responsive) {
1979 ALOGW("Unresponsive monitor %s will not get the new gesture",
1980 connection->inputChannel->getName().c_str());
1981 return false;
1982 }
1983 return true;
1984 });
1985 return responsiveMonitors;
1986}
1987
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001988InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1989 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1990 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001991 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 // For security reasons, we defer updating the touch state until we are sure that
1994 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001995 const int32_t displayId = entry.displayId;
1996 const int32_t action = entry.action;
1997 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
1999 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002000 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002001 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2002 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002004 // Copy current touch state into tempTouchState.
2005 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2006 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002007 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002009 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2010 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002011 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002012 }
2013
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002014 bool isSplit = tempTouchState.split;
2015 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2016 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2017 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002018
2019 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2020 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2021 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2022 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2023 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002024 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 bool wrongDevice = false;
2026 if (newGesture) {
2027 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002028 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002029 ALOGI("Dropping event because a pointer for a different device is already down "
2030 "in display %" PRId32,
2031 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002032 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002033 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 switchedDevice = false;
2035 wrongDevice = true;
2036 goto Failed;
2037 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002038 tempTouchState.reset();
2039 tempTouchState.down = down;
2040 tempTouchState.deviceId = entry.deviceId;
2041 tempTouchState.source = entry.source;
2042 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002044 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002045 ALOGI("Dropping move event because a pointer for a different device is already active "
2046 "in display %" PRId32,
2047 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002048 // TODO: test multiple simultaneous input streams.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002049 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002050 switchedDevice = false;
2051 wrongDevice = true;
2052 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054
2055 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2056 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2057
Prabir Pradhandb326da2023-03-09 04:51:55 +00002058 float x;
2059 float y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002060 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002061 // Always dispatch mouse events to cursor position.
2062 if (isFromMouse) {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002063 x = entry.xCursorPosition;
2064 y = entry.yCursorPosition;
Garfield Tan00f511d2019-06-12 16:55:40 -07002065 } else {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002066 x = entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X);
2067 y = entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y);
Garfield Tan00f511d2019-06-12 16:55:40 -07002068 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002069 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002070 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002071 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002072 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002073
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002075 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002076 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002078 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002079 }
2080
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002081 // Verify targeted injection.
2082 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2083 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2084 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2085 newTouchedWindowHandle = nullptr;
2086 goto Failed;
2087 }
2088
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002089 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002091 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2092 // New window supports splitting, but we should never split mouse events.
2093 isSplit = !isFromMouse;
2094 } else if (isSplit) {
2095 // New window does not support splitting but we have already split events.
2096 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002097 newTouchedWindowHandle = nullptr;
2098 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002099 } else {
2100 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002101 // be delivered to a new window which supports split touch. Pointers from a mouse device
2102 // should never be split.
2103 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 }
2105
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002106 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002107 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002108 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2109 newHoverWindowHandle = nullptr;
2110 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002111 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002112 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002113 }
2114
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002115 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002116 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002117 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002118 // Process the foreground window first so that it is the first to receive the event.
2119 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002120 }
2121
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002122 if (newTouchedWindows.empty()) {
2123 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2124 x, y, displayId);
2125 injectionResult = InputEventInjectionResult::FAILED;
2126 goto Failed;
2127 }
2128
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002129 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2130 const WindowInfo& info = *windowHandle->getInfo();
2131
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002132 // Skip spy window targets that are not valid for targeted injection.
2133 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2134 continue;
2135 }
2136
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002137 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002138 ALOGI("Not sending touch event to %s because it is paused",
2139 windowHandle->getName().c_str());
2140 continue;
2141 }
2142
2143 // Ensure the window has a connection and the connection is responsive
2144 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2145 if (!isResponsive) {
2146 ALOGW("Not sending touch gesture to %s because it is not responsive",
2147 windowHandle->getName().c_str());
2148 continue;
2149 }
2150
2151 // Drop events that can't be trusted due to occlusion
2152 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2153 TouchOcclusionInfo occlusionInfo =
2154 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());
2160 }
2161 }
2162 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2163 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2164 ALOGW("Dropping untrusted touch event due to %s/%d",
2165 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2166 continue;
2167 }
2168 }
2169 }
2170
2171 // Drop touch events if requested by input feature
2172 if (shouldDropInput(entry, windowHandle)) {
2173 continue;
2174 }
2175
2176 // Set target flags.
2177 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2178
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002179 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2180 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002181 targetFlags |= InputTarget::FLAG_FOREGROUND;
2182 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183
2184 if (isSplit) {
2185 targetFlags |= InputTarget::FLAG_SPLIT;
2186 }
2187 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2188 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2189 } else if (isWindowObscuredLocked(windowHandle)) {
2190 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2191 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002192
2193 // Update the temporary touch state.
2194 BitSet32 pointerIds;
2195 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002196 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002197 pointerIds.markBit(pointerId);
2198 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002199
2200 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 } else {
2203 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2204
2205 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002206 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002207 if (DEBUG_FOCUS) {
2208 ALOGD("Dropping event because the pointer is not down or we previously "
2209 "dropped the pointer down event in display %" PRId32,
2210 displayId);
2211 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002212 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 goto Failed;
2214 }
2215
arthurhung6d4bed92021-03-17 11:59:33 +08002216 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002217
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002219 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002220 tempTouchState.isSlippery()) {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002221 const float x = entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X);
2222 const float y = entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223
Prabir Pradhand65552b2021-10-07 11:23:50 -07002224 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002225 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002226 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002227 newTouchedWindowHandle =
2228 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002229
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002230 // Verify targeted injection.
2231 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2232 ALOGW("Dropping injected event: %s", (*err).c_str());
2233 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2234 newTouchedWindowHandle = nullptr;
2235 goto Failed;
2236 }
2237
Vishnu Nair062a8672021-09-03 16:07:44 -07002238 // Drop touch events if requested by input feature
2239 if (newTouchedWindowHandle != nullptr &&
2240 shouldDropInput(entry, newTouchedWindowHandle)) {
2241 newTouchedWindowHandle = nullptr;
2242 }
2243
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002244 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2245 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002246 if (DEBUG_FOCUS) {
2247 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2248 oldTouchedWindowHandle->getName().c_str(),
2249 newTouchedWindowHandle->getName().c_str(), displayId);
2250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2253 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2254 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255
2256 // Make a slippery entrance into the new window.
2257 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002258 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 }
2260
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002261 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2262 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2263 targetFlags |= InputTarget::FLAG_FOREGROUND;
2264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (isSplit) {
2266 targetFlags |= InputTarget::FLAG_SPLIT;
2267 }
2268 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2269 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002270 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2271 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273
2274 BitSet32 pointerIds;
2275 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002276 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
2280 }
2281 }
2282
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285 // Let the previous window know that the hover sequence is over, unless we already did
2286 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002287 if (mLastHoverWindowHandle != nullptr &&
2288 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2289 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002290 if (DEBUG_HOVER) {
2291 ALOGD("Sending hover exit event to window %s.",
2292 mLastHoverWindowHandle->getName().c_str());
2293 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002294 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2295 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
Garfield Tandf26e862020-07-01 20:18:19 -07002298 // Let the new window know that the hover sequence is starting, unless we already did it
2299 // when dispatching it as is to newTouchedWindowHandle.
2300 if (newHoverWindowHandle != nullptr &&
2301 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2302 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002303 if (DEBUG_HOVER) {
2304 ALOGD("Sending hover enter event to window %s.",
2305 newHoverWindowHandle->getName().c_str());
2306 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2308 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2309 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311 }
2312
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002313 // Ensure that we have at least one foreground window or at least one window that cannot be a
2314 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2315 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2316 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002317 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2318 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002319 return !canReceiveForegroundTouches(
2320 *touchedWindow.windowHandle->getInfo()) ||
2321 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002322 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002323 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2324 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002325 injectionResult = InputEventInjectionResult::FAILED;
2326 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002329 // Ensure that all touched windows are valid for injection.
2330 if (entry.injectionState != nullptr) {
2331 std::string errs;
2332 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2333 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2334 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2335 // dispatched to any uid, since the coords will be zeroed out later.
2336 continue;
2337 }
2338 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2339 if (err) errs += "\n - " + *err;
2340 }
2341 if (!errs.empty()) {
2342 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2343 "%d:%s",
2344 *entry.injectionState->targetUid, errs.c_str());
2345 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2346 goto Failed;
2347 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002348 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002349
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 // Check whether windows listening for outside touches are owned by the same UID. If it is
2351 // set the policy flag that we will not reveal coordinate information to this window.
2352 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002353 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002354 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002355 if (foregroundWindowHandle) {
2356 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002357 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002358 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002359 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2360 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2361 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002362 InputTarget::FLAG_ZERO_COORDS,
2363 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
2366 }
2367 }
2368 }
2369
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 // If this is the first pointer going down and the touched window has a wallpaper
2371 // then also add the touched wallpaper windows so they are locked in for the duration
2372 // of the touch gesture.
2373 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2374 // engine only supports touch events. We would need to add a mechanism similar
2375 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2376 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002377 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002378 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002379 if (foregroundWindowHandle &&
2380 foregroundWindowHandle->getInfo()->inputConfig.test(
2381 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002382 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002383 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002384 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2385 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002386 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002387 windowHandle->getInfo()->inputConfig.test(
2388 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002389 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 .addOrUpdateWindow(windowHandle,
2391 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2392 InputTarget::
2393 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2394 InputTarget::FLAG_DISPATCH_AS_IS,
2395 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 }
2397 }
2398 }
2399 }
2400
2401 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002402 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002404 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002406 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
2408
2409 // Drop the outside or hover touch windows since we will not care about them
2410 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002411 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412
2413Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002415 if (!wrongDevice) {
2416 if (switchedDevice) {
2417 if (DEBUG_FOCUS) {
2418 ALOGD("Conflicting pointer actions: Switched to a different device.");
2419 }
2420 *outConflictingPointerActions = true;
2421 }
2422
2423 if (isHoverAction) {
2424 // Started hovering, therefore no longer down.
2425 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002426 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002427 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2428 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 *outConflictingPointerActions = true;
2431 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002432 tempTouchState.reset();
2433 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2434 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2435 tempTouchState.deviceId = entry.deviceId;
2436 tempTouchState.source = entry.source;
2437 tempTouchState.displayId = displayId;
2438 }
2439 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2440 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2441 // All pointers up or canceled.
2442 tempTouchState.reset();
2443 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2444 // First pointer went down.
2445 if (oldState && oldState->down) {
2446 if (DEBUG_FOCUS) {
2447 ALOGD("Conflicting pointer actions: Down received while already down.");
2448 }
2449 *outConflictingPointerActions = true;
2450 }
2451 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2452 // One pointer went up.
2453 if (isSplit) {
2454 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2455 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002457 for (size_t i = 0; i < tempTouchState.windows.size();) {
2458 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2459 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2460 touchedWindow.pointerIds.clearBit(pointerId);
2461 if (touchedWindow.pointerIds.isEmpty()) {
2462 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2463 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002466 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002468 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002469 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002470
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002471 // Save changes unless the action was scroll in which case the temporary touch
2472 // state was only valid for this one action.
2473 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2474 if (tempTouchState.displayId >= 0) {
2475 mTouchStatesByDisplay[displayId] = tempTouchState;
2476 } else {
2477 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002481 // Update hover state.
2482 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 return injectionResult;
2486}
2487
arthurhung6d4bed92021-03-17 11:59:33 +08002488void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002489 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2490 // have an explicit reason to support it.
2491 constexpr bool isStylus = false;
2492
chaviw98318de2021-05-19 16:45:23 -05002493 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002494 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002495 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002496 if (dropWindow) {
2497 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002498 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002499 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002500 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002501 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002502 }
2503 mDragState.reset();
2504}
2505
2506void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002507 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002508 return;
2509 }
2510
arthurhung6d4bed92021-03-17 11:59:33 +08002511 if (!mDragState->isStartDrag) {
2512 mDragState->isStartDrag = true;
2513 mDragState->isStylusButtonDownAtStart =
2514 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2515 }
2516
Arthur Hung54745652022-04-20 07:17:41 +00002517 // Find the pointer index by id.
2518 int32_t pointerIndex = 0;
2519 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2520 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2521 if (pointerProperties.id == mDragState->pointerId) {
2522 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002523 }
Arthur Hung54745652022-04-20 07:17:41 +00002524 }
arthurhung6d4bed92021-03-17 11:59:33 +08002525
Arthur Hung54745652022-04-20 07:17:41 +00002526 if (uint32_t(pointerIndex) == entry.pointerCount) {
2527 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002528 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002529 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002530 return;
2531 }
2532
2533 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
Prabir Pradhandb326da2023-03-09 04:51:55 +00002534 const float x = entry.pointerCoords[pointerIndex].getX();
2535 const float y = entry.pointerCoords[pointerIndex].getY();
Arthur Hung54745652022-04-20 07:17:41 +00002536
2537 switch (maskedAction) {
2538 case AMOTION_EVENT_ACTION_MOVE: {
2539 // Handle the special case : stylus button no longer pressed.
2540 bool isStylusButtonDown =
2541 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2542 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2543 finishDragAndDrop(entry.displayId, x, y);
2544 return;
2545 }
2546
2547 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2548 // until we have an explicit reason to support it.
2549 constexpr bool isStylus = false;
2550
2551 const sp<WindowInfoHandle> hoverWindowHandle =
2552 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2553 isStylus, false /*addOutsideTargets*/,
2554 true /*ignoreDragWindow*/);
2555 // enqueue drag exit if needed.
2556 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2557 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2558 if (mDragState->dragHoverWindowHandle != nullptr) {
2559 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2560 y);
2561 }
2562 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2563 }
2564 // enqueue drag location if needed.
2565 if (hoverWindowHandle != nullptr) {
2566 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2567 }
2568 break;
2569 }
2570
2571 case AMOTION_EVENT_ACTION_POINTER_UP:
2572 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2573 break;
2574 }
2575 // The drag pointer is up.
2576 [[fallthrough]];
2577 case AMOTION_EVENT_ACTION_UP:
2578 finishDragAndDrop(entry.displayId, x, y);
2579 break;
2580 case AMOTION_EVENT_ACTION_CANCEL: {
2581 ALOGD("Receiving cancel when drag and drop.");
2582 sendDropWindowCommandLocked(nullptr, 0, 0);
2583 mDragState.reset();
2584 break;
2585 }
arthurhungb89ccb02020-12-30 16:19:01 +08002586 }
2587}
2588
chaviw98318de2021-05-19 16:45:23 -05002589void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002590 int32_t targetFlags, BitSet32 pointerIds,
2591 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002592 std::vector<InputTarget>::iterator it =
2593 std::find_if(inputTargets.begin(), inputTargets.end(),
2594 [&windowHandle](const InputTarget& inputTarget) {
2595 return inputTarget.inputChannel->getConnectionToken() ==
2596 windowHandle->getToken();
2597 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002598
chaviw98318de2021-05-19 16:45:23 -05002599 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002600
2601 if (it == inputTargets.end()) {
2602 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002603 std::shared_ptr<InputChannel> inputChannel =
2604 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002605 if (inputChannel == nullptr) {
2606 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2607 return;
2608 }
2609 inputTarget.inputChannel = inputChannel;
2610 inputTarget.flags = targetFlags;
2611 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002612 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2613 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002614 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002615 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002616 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002617 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002618 inputTargets.push_back(inputTarget);
2619 it = inputTargets.end() - 1;
2620 }
2621
2622 ALOG_ASSERT(it->flags == targetFlags);
2623 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2624
chaviw1ff3d1e2020-07-01 15:53:47 -07002625 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626}
2627
Michael Wright3dd60e22019-03-27 22:06:44 +00002628void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002629 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002630 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2631 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002632
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2634 InputTarget target;
2635 target.inputChannel = monitor.inputChannel;
2636 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2637 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2638 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002639 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002640 target.setDefaultPointerTransform(target.displayTransform);
2641 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
2643}
2644
Robert Carrc9bf1d32020-04-13 17:21:08 -07002645/**
2646 * Indicate whether one window handle should be considered as obscuring
2647 * another window handle. We only check a few preconditions. Actually
2648 * checking the bounds is left to the caller.
2649 */
chaviw98318de2021-05-19 16:45:23 -05002650static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2651 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002652 // Compare by token so cloned layers aren't counted
2653 if (haveSameToken(windowHandle, otherHandle)) {
2654 return false;
2655 }
2656 auto info = windowHandle->getInfo();
2657 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002658 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002659 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002660 } else if (otherInfo->alpha == 0 &&
2661 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002662 // Those act as if they were invisible, so we don't need to flag them.
2663 // We do want to potentially flag touchable windows even if they have 0
2664 // opacity, since they can consume touches and alter the effects of the
2665 // user interaction (eg. apps that rely on
2666 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2667 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2668 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002669 } else if (info->ownerUid == otherInfo->ownerUid) {
2670 // If ownerUid is the same we don't generate occlusion events as there
2671 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002672 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002673 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002674 return false;
2675 } else if (otherInfo->displayId != info->displayId) {
2676 return false;
2677 }
2678 return true;
2679}
2680
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002681/**
2682 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2683 * untrusted, one should check:
2684 *
2685 * 1. If result.hasBlockingOcclusion is true.
2686 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2687 * BLOCK_UNTRUSTED.
2688 *
2689 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2690 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2691 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2692 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2693 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2694 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2695 *
2696 * If neither of those is true, then it means the touch can be allowed.
2697 */
2698InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002699 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2700 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002701 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002702 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002703 TouchOcclusionInfo info;
2704 info.hasBlockingOcclusion = false;
2705 info.obscuringOpacity = 0;
2706 info.obscuringUid = -1;
2707 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002708 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002709 if (windowHandle == otherHandle) {
2710 break; // All future windows are below us. Exit early.
2711 }
chaviw98318de2021-05-19 16:45:23 -05002712 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002713 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2714 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002715 if (DEBUG_TOUCH_OCCLUSION) {
2716 info.debugInfo.push_back(
2717 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2718 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002719 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2720 // we perform the checks below to see if the touch can be propagated or not based on the
2721 // window's touch occlusion mode
2722 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2723 info.hasBlockingOcclusion = true;
2724 info.obscuringUid = otherInfo->ownerUid;
2725 info.obscuringPackage = otherInfo->packageName;
2726 break;
2727 }
2728 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2729 uint32_t uid = otherInfo->ownerUid;
2730 float opacity =
2731 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2732 // Given windows A and B:
2733 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2734 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2735 opacityByUid[uid] = opacity;
2736 if (opacity > info.obscuringOpacity) {
2737 info.obscuringOpacity = opacity;
2738 info.obscuringUid = uid;
2739 info.obscuringPackage = otherInfo->packageName;
2740 }
2741 }
2742 }
2743 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002744 if (DEBUG_TOUCH_OCCLUSION) {
2745 info.debugInfo.push_back(
2746 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2747 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002748 return info;
2749}
2750
chaviw98318de2021-05-19 16:45:23 -05002751std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002752 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002753 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2754 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2755 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2756 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002757 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2758 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2759 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2760 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2761 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002762 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002763 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002764}
2765
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002766bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2767 if (occlusionInfo.hasBlockingOcclusion) {
2768 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2769 occlusionInfo.obscuringUid);
2770 return false;
2771 }
2772 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2773 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2774 "%.2f, maximum allowed = %.2f)",
2775 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2776 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2777 return false;
2778 }
2779 return true;
2780}
2781
chaviw98318de2021-05-19 16:45:23 -05002782bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002785 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2786 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002787 if (windowHandle == otherHandle) {
2788 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 }
chaviw98318de2021-05-19 16:45:23 -05002790 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002792 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 return true;
2794 }
2795 }
2796 return false;
2797}
2798
chaviw98318de2021-05-19 16:45:23 -05002799bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002800 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002801 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2802 const WindowInfo* windowInfo = windowHandle->getInfo();
2803 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002804 if (windowHandle == otherHandle) {
2805 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002806 }
chaviw98318de2021-05-19 16:45:23 -05002807 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002808 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002809 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002810 return true;
2811 }
2812 }
2813 return false;
2814}
2815
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002816std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002817 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002818 if (applicationHandle != nullptr) {
2819 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002820 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 } else {
2822 return applicationHandle->getName();
2823 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002824 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002825 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002827 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 }
2829}
2830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002831void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002832 if (!isUserActivityEvent(eventEntry)) {
2833 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002834 return;
2835 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002836 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002837 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002838 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002839 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002840 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002841 if (DEBUG_DISPATCH_CYCLE) {
2842 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 return;
2845 }
2846 }
2847
2848 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002849 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002850 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002851 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2852 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002853 return;
2854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002856 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 eventType = USER_ACTIVITY_EVENT_TOUCH;
2858 }
2859 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002861 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002862 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2863 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 return;
2865 }
2866 eventType = USER_ACTIVITY_EVENT_BUTTON;
2867 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002869 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002870 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002871 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002872 break;
2873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 }
2875
Prabir Pradhancef936d2021-07-21 16:17:52 +00002876 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2877 REQUIRES(mLock) {
2878 scoped_unlock unlock(mLock);
2879 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2880 };
2881 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882}
2883
2884void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002886 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002887 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002888 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002890 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002891 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002892 ATRACE_NAME(message.c_str());
2893 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002894 if (DEBUG_DISPATCH_CYCLE) {
2895 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2896 "globalScaleFactor=%f, pointerIds=0x%x %s",
2897 connection->getInputChannelName().c_str(), inputTarget.flags,
2898 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2899 inputTarget.getPointerInfoString().c_str());
2900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
2902 // Skip this event if the connection status is not normal.
2903 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002904 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002905 if (DEBUG_DISPATCH_CYCLE) {
2906 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002907 connection->getInputChannelName().c_str(),
2908 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 return;
2911 }
2912
2913 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002914 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2915 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2916 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002917 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002919 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002920 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002921 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002922 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 if (!splitMotionEntry) {
2924 return; // split event was dropped
2925 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002926 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2927 std::string reason = std::string("reason=pointer cancel on split window");
2928 android_log_event_list(LOGTAG_INPUT_CANCEL)
2929 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2930 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002931 if (DEBUG_FOCUS) {
2932 ALOGD("channel '%s' ~ Split motion event.",
2933 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002934 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002935 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002936 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2937 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 return;
2939 }
2940 }
2941
2942 // Not splitting. Enqueue dispatch entries for the event as is.
2943 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2944}
2945
2946void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002948 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002949 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002950 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002952 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002953 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002954 ATRACE_NAME(message.c_str());
2955 }
2956
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002957 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
2959 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002960 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002962 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002968 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002970 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972
2973 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002974 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 startDispatchCycleLocked(currentTime, connection);
2976 }
2977}
2978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002981 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002983 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2985 connection->getInputChannelName().c_str(),
2986 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002987 ATRACE_NAME(message.c_str());
2988 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002989 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 if (!(inputTargetFlags & dispatchMode)) {
2991 return;
2992 }
2993 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2994
2995 // This is a new event.
2996 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002997 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002998 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003000 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3001 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003002 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003004 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003005 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003007 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003008 dispatchEntry->resolvedAction = keyEntry.action;
3009 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3012 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003013 if (DEBUG_DISPATCH_CYCLE) {
3014 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3015 "event",
3016 connection->getInputChannelName().c_str());
3017 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003018 return; // skip the inconsistent event
3019 }
3020 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003023 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003024 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003025 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3026 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3027 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3028 static_cast<int32_t>(IdGenerator::Source::OTHER);
3029 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3032 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3034 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3036 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3038 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3039 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3040 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003041 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003042 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003043 }
3044 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003045 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3046 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003047 if (DEBUG_DISPATCH_CYCLE) {
3048 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3049 "enter event",
3050 connection->getInputChannelName().c_str());
3051 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003052 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3053 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003057 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3059 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3060 }
3061 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3062 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3066 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003067 if (DEBUG_DISPATCH_CYCLE) {
3068 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3069 "event",
3070 connection->getInputChannelName().c_str());
3071 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 return; // skip the inconsistent event
3073 }
3074
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003075 dispatchEntry->resolvedEventId =
3076 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3077 ? mIdGenerator.nextId()
3078 : motionEntry.id;
3079 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3080 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3081 ") to MotionEvent(id=0x%" PRIx32 ").",
3082 motionEntry.id, dispatchEntry->resolvedEventId);
3083 ATRACE_NAME(message.c_str());
3084 }
3085
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003086 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3087 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3088 // Skip reporting pointer down outside focus to the policy.
3089 break;
3090 }
3091
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003092 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003093 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094
3095 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003097 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003098 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003099 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3100 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003101 break;
3102 }
Chris Yef59a2f42020-10-16 12:55:26 -07003103 case EventEntry::Type::SENSOR: {
3104 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3105 break;
3106 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003107 case EventEntry::Type::CONFIGURATION_CHANGED:
3108 case EventEntry::Type::DEVICE_RESET: {
3109 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003110 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003111 break;
3112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
3114
3115 // Remember that we are waiting for this dispatch to complete.
3116 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003117 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
3119
3120 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003121 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003122 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003123}
3124
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003125/**
3126 * This function is purely for debugging. It helps us understand where the user interaction
3127 * was taking place. For example, if user is touching launcher, we will see a log that user
3128 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3129 * We will see both launcher and wallpaper in that list.
3130 * Once the interaction with a particular set of connections starts, no new logs will be printed
3131 * until the set of interacted connections changes.
3132 *
3133 * The following items are skipped, to reduce the logspam:
3134 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3135 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3136 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3137 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3138 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003139 */
3140void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3141 const std::vector<InputTarget>& targets) {
3142 // Skip ACTION_UP events, and all events other than keys and motions
3143 if (entry.type == EventEntry::Type::KEY) {
3144 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3145 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3146 return;
3147 }
3148 } else if (entry.type == EventEntry::Type::MOTION) {
3149 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3150 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3151 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3152 return;
3153 }
3154 } else {
3155 return; // Not a key or a motion
3156 }
3157
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003158 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003159 std::vector<sp<Connection>> newConnections;
3160 for (const InputTarget& target : targets) {
3161 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3162 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3163 continue; // Skip windows that receive ACTION_OUTSIDE
3164 }
3165
3166 sp<IBinder> token = target.inputChannel->getConnectionToken();
3167 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003168 if (connection == nullptr) {
3169 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003170 }
3171 newConnectionTokens.insert(std::move(token));
3172 newConnections.emplace_back(connection);
3173 }
3174 if (newConnectionTokens == mInteractionConnectionTokens) {
3175 return; // no change
3176 }
3177 mInteractionConnectionTokens = newConnectionTokens;
3178
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003179 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003180 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003181 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003182 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003183 std::string message = "Interaction with: " + targetList;
3184 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003185 message += "<none>";
3186 }
3187 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3188}
3189
chaviwfd6d3512019-03-25 13:23:49 -07003190void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003191 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003192 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003193 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3194 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003195 return;
3196 }
3197
Vishnu Nairc519ff72021-01-21 08:23:08 -08003198 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003199 if (focusedToken == token) {
3200 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003201 return;
3202 }
3203
Prabir Pradhancef936d2021-07-21 16:17:52 +00003204 auto command = [this, token]() REQUIRES(mLock) {
3205 scoped_unlock unlock(mLock);
3206 mPolicy->onPointerDownOutsideFocus(token);
3207 };
3208 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209}
3210
3211void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003213 if (ATRACE_ENABLED()) {
3214 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003216 ATRACE_NAME(message.c_str());
3217 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003218 if (DEBUG_DISPATCH_CYCLE) {
3219 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003222 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003223 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003225 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003226 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227
3228 // Publish the event.
3229 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003230 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3231 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003232 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003233 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3234 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 status = connection->inputPublisher
3238 .publishKeyEvent(dispatchEntry->seq,
3239 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3240 keyEntry.source, keyEntry.displayId,
3241 std::move(hmac), dispatchEntry->resolvedAction,
3242 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3243 keyEntry.scanCode, keyEntry.metaState,
3244 keyEntry.repeatCount, keyEntry.downTime,
3245 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 }
3248
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003249 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003253 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254
chaviw82357092020-01-28 13:13:06 -08003255 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3258 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003259 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3261 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003262 // Don't apply window scale here since we don't want scale to affect raw
3263 // coordinates. The scale will be sent back to the client and applied
3264 // later when requesting relative coordinates.
3265 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3266 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 }
3268 usingCoords = scaledCoords;
3269 }
3270 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 // We don't want the dispatch target to know.
3272 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003273 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 scaledCoords[i].clear();
3275 }
3276 usingCoords = scaledCoords;
3277 }
3278 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003280 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003281
3282 // Publish the motion event.
3283 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003284 .publishMotionEvent(dispatchEntry->seq,
3285 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003286 motionEntry.deviceId, motionEntry.source,
3287 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003288 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003289 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 motionEntry.edgeFlags, motionEntry.metaState,
3292 motionEntry.buttonState,
3293 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003294 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 motionEntry.xPrecision, motionEntry.yPrecision,
3296 motionEntry.xCursorPosition,
3297 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003298 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 motionEntry.downTime, motionEntry.eventTime,
3300 motionEntry.pointerCount,
3301 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 break;
3303 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003304
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003305 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003306 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003307 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003309 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003310 break;
3311 }
3312
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003313 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3314 const TouchModeEntry& touchModeEntry =
3315 static_cast<const TouchModeEntry&>(eventEntry);
3316 status = connection->inputPublisher
3317 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3318 touchModeEntry.inTouchMode);
3319
3320 break;
3321 }
3322
Prabir Pradhan99987712020-11-10 18:43:05 -08003323 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3324 const auto& captureEntry =
3325 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3326 status = connection->inputPublisher
3327 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003328 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003329 break;
3330 }
3331
arthurhungb89ccb02020-12-30 16:19:01 +08003332 case EventEntry::Type::DRAG: {
3333 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3334 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3335 dragEntry.id, dragEntry.x,
3336 dragEntry.y,
3337 dragEntry.isExiting);
3338 break;
3339 }
3340
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003341 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003342 case EventEntry::Type::DEVICE_RESET:
3343 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003344 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003345 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349
3350 // Check the result.
3351 if (status) {
3352 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003353 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 "This is unexpected because the wait queue is empty, so the pipe "
3356 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003357 "event to it, status=%s(%d)",
3358 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3359 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3361 } else {
3362 // Pipe is full and we are waiting for the app to finish process some events
3363 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003364 if (DEBUG_DISPATCH_CYCLE) {
3365 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3366 "waiting for the application to catch up",
3367 connection->getInputChannelName().c_str());
3368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 }
3370 } else {
3371 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003372 "status=%s(%d)",
3373 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3374 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3376 }
3377 return;
3378 }
3379
3380 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003381 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3382 connection->outboundQueue.end(),
3383 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003384 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003385 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003386 if (connection->responsive) {
3387 mAnrTracker.insert(dispatchEntry->timeoutTime,
3388 connection->inputChannel->getConnectionToken());
3389 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003390 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
3392}
3393
chaviw09c8d2d2020-08-24 15:48:26 -07003394std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3395 size_t size;
3396 switch (event.type) {
3397 case VerifiedInputEvent::Type::KEY: {
3398 size = sizeof(VerifiedKeyEvent);
3399 break;
3400 }
3401 case VerifiedInputEvent::Type::MOTION: {
3402 size = sizeof(VerifiedMotionEvent);
3403 break;
3404 }
3405 }
3406 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3407 return mHmacKeyManager.sign(start, size);
3408}
3409
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003410const std::array<uint8_t, 32> InputDispatcher::getSignature(
3411 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003412 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3413 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003414 // Only sign events up and down events as the purely move events
3415 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003416 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003417 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003418
3419 VerifiedMotionEvent verifiedEvent =
3420 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3421 verifiedEvent.actionMasked = actionMasked;
3422 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3423 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003424}
3425
3426const std::array<uint8_t, 32> InputDispatcher::getSignature(
3427 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3428 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3429 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3430 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003431 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003432}
3433
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003436 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003437 if (DEBUG_DISPATCH_CYCLE) {
3438 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3439 connection->getInputChannelName().c_str(), seq, toString(handled));
3440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003442 if (connection->status == Connection::Status::BROKEN ||
3443 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 return;
3445 }
3446
3447 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003448 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3449 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3450 };
3451 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452}
3453
3454void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003455 const sp<Connection>& connection,
3456 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003457 if (DEBUG_DISPATCH_CYCLE) {
3458 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3459 connection->getInputChannelName().c_str(), toString(notify));
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
3462 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003463 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003464 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003465 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003466 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
3468 // The connection appears to be unrecoverably broken.
3469 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003470 if (connection->status == Connection::Status::NORMAL) {
3471 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472
3473 if (notify) {
3474 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003475 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3476 connection->getInputChannelName().c_str());
3477
3478 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003479 scoped_unlock unlock(mLock);
3480 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3481 };
3482 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484 }
3485}
3486
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003487void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3488 while (!queue.empty()) {
3489 DispatchEntry* dispatchEntry = queue.front();
3490 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003491 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 }
3493}
3494
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003495void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003497 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 }
3499 delete dispatchEntry;
3500}
3501
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003502int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3503 std::scoped_lock _l(mLock);
3504 sp<Connection> connection = getConnectionLocked(connectionToken);
3505 if (connection == nullptr) {
3506 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3507 connectionToken.get(), events);
3508 return 0; // remove the callback
3509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003511 bool notify;
3512 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3513 if (!(events & ALOOPER_EVENT_INPUT)) {
3514 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3515 "events=0x%x",
3516 connection->getInputChannelName().c_str(), events);
3517 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003520 nsecs_t currentTime = now();
3521 bool gotOne = false;
3522 status_t status = OK;
3523 for (;;) {
3524 Result<InputPublisher::ConsumerResponse> result =
3525 connection->inputPublisher.receiveConsumerResponse();
3526 if (!result.ok()) {
3527 status = result.error().code();
3528 break;
3529 }
3530
3531 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3532 const InputPublisher::Finished& finish =
3533 std::get<InputPublisher::Finished>(*result);
3534 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3535 finish.consumeTime);
3536 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003537 if (shouldReportMetricsForConnection(*connection)) {
3538 const InputPublisher::Timeline& timeline =
3539 std::get<InputPublisher::Timeline>(*result);
3540 mLatencyTracker
3541 .trackGraphicsLatency(timeline.inputEventId,
3542 connection->inputChannel->getConnectionToken(),
3543 std::move(timeline.graphicsTimeline));
3544 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003545 }
3546 gotOne = true;
3547 }
3548 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003549 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003550 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 return 1;
3552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003555 notify = status != DEAD_OBJECT || !connection->monitor;
3556 if (notify) {
3557 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3558 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3559 status);
3560 }
3561 } else {
3562 // Monitor channels are never explicitly unregistered.
3563 // We do it automatically when the remote endpoint is closed so don't warn about them.
3564 const bool stillHaveWindowHandle =
3565 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3566 notify = !connection->monitor && stillHaveWindowHandle;
3567 if (notify) {
3568 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3569 connection->getInputChannelName().c_str(), events);
3570 }
3571 }
3572
3573 // Remove the channel.
3574 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3575 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576}
3577
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003580 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003581 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 }
3583}
3584
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003585void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003586 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003587 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003588 for (const Monitor& monitor : monitors) {
3589 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003591 }
3592}
3593
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003595 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003596 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003597 if (connection == nullptr) {
3598 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003600
3601 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602}
3603
3604void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3605 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003606 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 return;
3608 }
3609
3610 nsecs_t currentTime = now();
3611
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003612 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003613 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003615 if (cancelationEvents.empty()) {
3616 return;
3617 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003618 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3619 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3620 "with reality: %s, mode=%d.",
3621 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3622 options.mode);
3623 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003624
Arthur Hungb3307ee2021-10-14 10:57:37 +00003625 std::string reason = std::string("reason=").append(options.reason);
3626 android_log_event_list(LOGTAG_INPUT_CANCEL)
3627 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3628
Svet Ganov5d3bc372020-01-26 23:11:07 -08003629 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003630 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3632 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003633 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003634 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003635 target.globalScaleFactor = windowInfo->globalScaleFactor;
3636 }
3637 target.inputChannel = connection->inputChannel;
3638 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3639
hongzuo liu474c1672022-09-06 02:51:35 +00003640 const bool wasEmpty = connection->outboundQueue.empty();
3641
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003642 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003643 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003644 switch (cancelationEventEntry->type) {
3645 case EventEntry::Type::KEY: {
3646 logOutboundKeyDetails("cancel - ",
3647 static_cast<const KeyEntry&>(*cancelationEventEntry));
3648 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003650 case EventEntry::Type::MOTION: {
3651 logOutboundMotionDetails("cancel - ",
3652 static_cast<const MotionEntry&>(*cancelationEventEntry));
3653 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003655 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003656 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003657 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3658 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003659 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003660 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003661 break;
3662 }
3663 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003664 case EventEntry::Type::DEVICE_RESET:
3665 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003666 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003667 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003668 break;
3669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 }
3671
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003672 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3673 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003675
hongzuo liu474c1672022-09-06 02:51:35 +00003676 // If the outbound queue was previously empty, start the dispatch cycle going.
3677 if (wasEmpty && !connection->outboundQueue.empty()) {
3678 startDispatchCycleLocked(currentTime, connection);
3679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680}
3681
Svet Ganov5d3bc372020-01-26 23:11:07 -08003682void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3683 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003684 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003685 return;
3686 }
3687
3688 nsecs_t currentTime = now();
3689
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003690 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003691 connection->inputState.synthesizePointerDownEvents(currentTime);
3692
3693 if (downEvents.empty()) {
3694 return;
3695 }
3696
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003697 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003698 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3699 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003700 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003701
3702 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003703 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003704 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3705 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003706 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003707 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003708 target.globalScaleFactor = windowInfo->globalScaleFactor;
3709 }
3710 target.inputChannel = connection->inputChannel;
3711 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3712
hongzuo liu474c1672022-09-06 02:51:35 +00003713 const bool wasEmpty = connection->outboundQueue.empty();
3714
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 switch (downEventEntry->type) {
3717 case EventEntry::Type::MOTION: {
3718 logOutboundMotionDetails("down - ",
3719 static_cast<const MotionEntry&>(*downEventEntry));
3720 break;
3721 }
3722
3723 case EventEntry::Type::KEY:
3724 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003725 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003727 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003728 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003729 case EventEntry::Type::SENSOR:
3730 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003732 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003733 break;
3734 }
3735 }
3736
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003737 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3738 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003739 }
hongzuo liu474c1672022-09-06 02:51:35 +00003740 // If the outbound queue was previously empty, start the dispatch cycle going.
3741 if (wasEmpty && !connection->outboundQueue.empty()) {
3742 startDispatchCycleLocked(currentTime, connection);
3743 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003744}
3745
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003746std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3747 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 ALOG_ASSERT(pointerIds.value != 0);
3749
3750 uint32_t splitPointerIndexMap[MAX_POINTERS];
3751 PointerProperties splitPointerProperties[MAX_POINTERS];
3752 PointerCoords splitPointerCoords[MAX_POINTERS];
3753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003754 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 uint32_t splitPointerCount = 0;
3756
3757 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003758 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003760 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 uint32_t pointerId = uint32_t(pointerProperties.id);
3762 if (pointerIds.hasBit(pointerId)) {
3763 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3764 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3765 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003766 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 splitPointerCount += 1;
3768 }
3769 }
3770
3771 if (splitPointerCount != pointerIds.count()) {
3772 // This is bad. We are missing some of the pointers that we expected to deliver.
3773 // Most likely this indicates that we received an ACTION_MOVE events that has
3774 // different pointer ids than we expected based on the previous ACTION_DOWN
3775 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3776 // in this way.
3777 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003778 "we expected there to be %d pointers. This probably means we received "
3779 "a broken sequence of pointer ids from the input device.",
3780 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003781 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003784 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3787 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3789 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003790 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 uint32_t pointerId = uint32_t(pointerProperties.id);
3792 if (pointerIds.hasBit(pointerId)) {
3793 if (pointerIds.count() == 1) {
3794 // The first/last pointer went down/up.
3795 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003796 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003797 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3798 ? AMOTION_EVENT_ACTION_CANCEL
3799 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 } else {
3801 // A secondary pointer went down/up.
3802 uint32_t splitPointerIndex = 0;
3803 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3804 splitPointerIndex += 1;
3805 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806 action = maskedAction |
3807 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
3809 } else {
3810 // An unrelated pointer changed.
3811 action = AMOTION_EVENT_ACTION_MOVE;
3812 }
3813 }
3814
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003815 int32_t newId = mIdGenerator.nextId();
3816 if (ATRACE_ENABLED()) {
3817 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3818 ") to MotionEvent(id=0x%" PRIx32 ").",
3819 originalMotionEntry.id, newId);
3820 ATRACE_NAME(message.c_str());
3821 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003822 std::unique_ptr<MotionEntry> splitMotionEntry =
3823 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3824 originalMotionEntry.deviceId, originalMotionEntry.source,
3825 originalMotionEntry.displayId,
3826 originalMotionEntry.policyFlags, action,
3827 originalMotionEntry.actionButton,
3828 originalMotionEntry.flags, originalMotionEntry.metaState,
3829 originalMotionEntry.buttonState,
3830 originalMotionEntry.classification,
3831 originalMotionEntry.edgeFlags,
3832 originalMotionEntry.xPrecision,
3833 originalMotionEntry.yPrecision,
3834 originalMotionEntry.xCursorPosition,
3835 originalMotionEntry.yCursorPosition,
3836 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003837 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003839 if (originalMotionEntry.injectionState) {
3840 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 splitMotionEntry->injectionState->refCount += 1;
3842 }
3843
3844 return splitMotionEntry;
3845}
3846
3847void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003848 if (DEBUG_INBOUND_EVENT_DETAILS) {
3849 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851
Antonio Kantekf16f2832021-09-28 04:39:20 +00003852 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003854 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003856 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3857 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3858 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 } // release lock
3860
3861 if (needWake) {
3862 mLooper->wake();
3863 }
3864}
3865
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003866/**
3867 * If one of the meta shortcuts is detected, process them here:
3868 * Meta + Backspace -> generate BACK
3869 * Meta + Enter -> generate HOME
3870 * This will potentially overwrite keyCode and metaState.
3871 */
3872void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003873 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003874 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3875 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3876 if (keyCode == AKEYCODE_DEL) {
3877 newKeyCode = AKEYCODE_BACK;
3878 } else if (keyCode == AKEYCODE_ENTER) {
3879 newKeyCode = AKEYCODE_HOME;
3880 }
3881 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003882 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003883 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003884 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003885 keyCode = newKeyCode;
3886 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3887 }
3888 } else if (action == AKEY_EVENT_ACTION_UP) {
3889 // In order to maintain a consistent stream of up and down events, check to see if the key
3890 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3891 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003892 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003893 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003894 auto replacementIt = mReplacedKeys.find(replacement);
3895 if (replacementIt != mReplacedKeys.end()) {
3896 keyCode = replacementIt->second;
3897 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003898 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3899 }
3900 }
3901}
3902
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003904 if (DEBUG_INBOUND_EVENT_DETAILS) {
3905 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3906 "policyFlags=0x%x, action=0x%x, "
3907 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3908 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3909 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3910 args->downTime);
3911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 if (!validateKeyEvent(args->action)) {
3913 return;
3914 }
3915
3916 uint32_t policyFlags = args->policyFlags;
3917 int32_t flags = args->flags;
3918 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003919 // InputDispatcher tracks and generates key repeats on behalf of
3920 // whatever notifies it, so repeatCount should always be set to 0
3921 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3923 policyFlags |= POLICY_FLAG_VIRTUAL;
3924 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 if (policyFlags & POLICY_FLAG_FUNCTION) {
3927 metaState |= AMETA_FUNCTION_ON;
3928 }
3929
3930 policyFlags |= POLICY_FLAG_TRUSTED;
3931
Michael Wright78f24442014-08-06 15:55:28 -07003932 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003933 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003934
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003936 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003937 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3938 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939
Michael Wright2b3c3302018-03-02 17:19:13 +00003940 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003942 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3943 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003944 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946
Antonio Kantekf16f2832021-09-28 04:39:20 +00003947 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 { // acquire lock
3949 mLock.lock();
3950
3951 if (shouldSendKeyToInputFilterLocked(args)) {
3952 mLock.unlock();
3953
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003954 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3956 return; // event was consumed by the filter
3957 }
3958
3959 mLock.lock();
3960 }
3961
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003962 std::unique_ptr<KeyEntry> newEntry =
3963 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3964 args->displayId, policyFlags, args->action, flags,
3965 keyCode, args->scanCode, metaState, repeatCount,
3966 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 mLock.unlock();
3970 } // release lock
3971
3972 if (needWake) {
3973 mLooper->wake();
3974 }
3975}
3976
3977bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3978 return mInputFilterEnabled;
3979}
3980
3981void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003982 if (DEBUG_INBOUND_EVENT_DETAILS) {
3983 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3984 "displayId=%" PRId32 ", policyFlags=0x%x, "
3985 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3986 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3987 "yCursorPosition=%f, downTime=%" PRId64,
3988 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3989 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3990 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3991 args->xCursorPosition, args->yCursorPosition, args->downTime);
3992 for (uint32_t i = 0; i < args->pointerCount; i++) {
3993 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3994 "x=%f, y=%f, pressure=%f, size=%f, "
3995 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3996 "orientation=%f",
3997 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3998 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3999 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4000 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4001 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4002 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4003 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4004 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4005 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4006 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004009 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4010 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 return;
4012 }
4013
4014 uint32_t policyFlags = args->policyFlags;
4015 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004016
4017 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004018 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004019 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4020 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004021 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023
Antonio Kantekf16f2832021-09-28 04:39:20 +00004024 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 { // acquire lock
4026 mLock.lock();
4027
4028 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004029 ui::Transform displayTransform;
4030 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4031 displayTransform = it->second.transform;
4032 }
4033
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 mLock.unlock();
4035
4036 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004037 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4038 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004039 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004040 displayTransform, args->xPrecision, args->yPrecision,
4041 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004042 args->downTime, args->eventTime, args->pointerCount,
4043 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
4045 policyFlags |= POLICY_FLAG_FILTERED;
4046 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4047 return; // event was consumed by the filter
4048 }
4049
4050 mLock.lock();
4051 }
4052
4053 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004054 std::unique_ptr<MotionEntry> newEntry =
4055 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4056 args->source, args->displayId, policyFlags,
4057 args->action, args->actionButton, args->flags,
4058 args->metaState, args->buttonState,
4059 args->classification, args->edgeFlags,
4060 args->xPrecision, args->yPrecision,
4061 args->xCursorPosition, args->yCursorPosition,
4062 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004063 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004065 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4066 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4067 !mInputFilterEnabled) {
4068 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4069 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4070 }
4071
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004072 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 mLock.unlock();
4074 } // release lock
4075
4076 if (needWake) {
4077 mLooper->wake();
4078 }
4079}
4080
Chris Yef59a2f42020-10-16 12:55:26 -07004081void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004082 if (DEBUG_INBOUND_EVENT_DETAILS) {
4083 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4084 " sensorType=%s",
4085 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004086 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004087 }
Chris Yef59a2f42020-10-16 12:55:26 -07004088
Antonio Kantekf16f2832021-09-28 04:39:20 +00004089 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004090 { // acquire lock
4091 mLock.lock();
4092
4093 // Just enqueue a new sensor event.
4094 std::unique_ptr<SensorEntry> newEntry =
4095 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4096 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4097 args->sensorType, args->accuracy,
4098 args->accuracyChanged, args->values);
4099
4100 needWake = enqueueInboundEventLocked(std::move(newEntry));
4101 mLock.unlock();
4102 } // release lock
4103
4104 if (needWake) {
4105 mLooper->wake();
4106 }
4107}
4108
Chris Yefb552902021-02-03 17:18:37 -08004109void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004110 if (DEBUG_INBOUND_EVENT_DETAILS) {
4111 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4112 args->deviceId, args->isOn);
4113 }
Chris Yefb552902021-02-03 17:18:37 -08004114 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4115}
4116
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004118 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119}
4120
4121void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004122 if (DEBUG_INBOUND_EVENT_DETAILS) {
4123 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4124 "switchMask=0x%08x",
4125 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127
4128 uint32_t policyFlags = args->policyFlags;
4129 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131}
4132
4133void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004134 if (DEBUG_INBOUND_EVENT_DETAILS) {
4135 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4136 args->deviceId);
4137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
Antonio Kantekf16f2832021-09-28 04:39:20 +00004139 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004141 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004143 std::unique_ptr<DeviceResetEntry> newEntry =
4144 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4145 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 } // release lock
4147
4148 if (needWake) {
4149 mLooper->wake();
4150 }
4151}
4152
Prabir Pradhan7e186182020-11-10 13:56:45 -08004153void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004154 if (DEBUG_INBOUND_EVENT_DETAILS) {
4155 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004156 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004158
Antonio Kantekf16f2832021-09-28 04:39:20 +00004159 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004160 { // acquire lock
4161 std::scoped_lock _l(mLock);
4162 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004163 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004164 needWake = enqueueInboundEventLocked(std::move(entry));
4165 } // release lock
4166
4167 if (needWake) {
4168 mLooper->wake();
4169 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004170}
4171
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004172InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4173 std::optional<int32_t> targetUid,
4174 InputEventInjectionSync syncMode,
4175 std::chrono::milliseconds timeout,
4176 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004177 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004178 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4179 "policyFlags=0x%08x",
4180 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4181 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004182 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004183 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004185 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004187 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004188 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4189 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4190 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4191 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4192 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004193 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004194 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004195 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004196 }
4197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004198 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004201 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4202 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004203 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004204 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004207 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004208 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4209 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4210 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004211 int32_t keyCode = incomingKey.getKeyCode();
4212 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004213 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004214 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004215 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004216 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004217 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4218 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4219 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004221 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4222 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004223 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224
4225 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4226 android::base::Timer t;
4227 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4228 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4229 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4230 std::to_string(t.duration().count()).c_str());
4231 }
4232 }
4233
4234 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004235 std::unique_ptr<KeyEntry> injectedEntry =
4236 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 incomingKey.getDisplayId(), policyFlags, action,
4239 flags, keyCode, incomingKey.getScanCode(), metaState,
4240 incomingKey.getRepeatCount(),
4241 incomingKey.getDownTime());
4242 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 }
4245
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004248 const int32_t action = motionEvent.getAction();
4249 const bool isPointerEvent =
4250 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4251 // If a pointer event has no displayId specified, inject it to the default display.
4252 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4253 ? ADISPLAY_ID_DEFAULT
4254 : event->getDisplayId();
4255 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004256 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004257 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004258 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004260 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 }
4262
4263 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004264 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 android::base::Timer t;
4266 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4267 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4268 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4269 std::to_string(t.duration().count()).c_str());
4270 }
4271 }
4272
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004273 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4274 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4275 }
4276
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004277 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004278 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4279 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004280 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004281 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4282 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004283 displayId, policyFlags, action, actionButton,
4284 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004285 motionEvent.getButtonState(),
4286 motionEvent.getClassification(),
4287 motionEvent.getEdgeFlags(),
4288 motionEvent.getXPrecision(),
4289 motionEvent.getYPrecision(),
4290 motionEvent.getRawXCursorPosition(),
4291 motionEvent.getRawYCursorPosition(),
4292 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004293 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004294 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004296 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 sampleEventTimes += 1;
4298 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004300 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4301 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004302 displayId, policyFlags, action, actionButton,
4303 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004304 motionEvent.getButtonState(),
4305 motionEvent.getClassification(),
4306 motionEvent.getEdgeFlags(),
4307 motionEvent.getXPrecision(),
4308 motionEvent.getYPrecision(),
4309 motionEvent.getRawXCursorPosition(),
4310 motionEvent.getRawYCursorPosition(),
4311 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004312 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004313 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004314 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4315 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004316 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 }
4318 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004322 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004326 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004327 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 injectionState->injectionIsAsync = true;
4329 }
4330
4331 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004332 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
4334 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004335 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004336 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004337 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339
4340 mLock.unlock();
4341
4342 if (needWake) {
4343 mLooper->wake();
4344 }
4345
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004346 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004348 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004350 if (syncMode == InputEventInjectionSync::NONE) {
4351 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 } else {
4353 for (;;) {
4354 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 break;
4357 }
4358
4359 nsecs_t remainingTimeout = endTime - now();
4360 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004361 if (DEBUG_INJECTION) {
4362 ALOGD("injectInputEvent - Timed out waiting for injection result "
4363 "to become available.");
4364 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 break;
4367 }
4368
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004369 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 }
4371
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4373 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004375 if (DEBUG_INJECTION) {
4376 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4377 injectionState->pendingForegroundDispatches);
4378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 nsecs_t remainingTimeout = endTime - now();
4380 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004381 if (DEBUG_INJECTION) {
4382 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4383 "dispatches to finish.");
4384 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 break;
4387 }
4388
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004389 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 }
4391 }
4392 }
4393
4394 injectionState->release();
4395 } // release lock
4396
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004397 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004398 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400
4401 return injectionResult;
4402}
4403
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004404std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004405 std::array<uint8_t, 32> calculatedHmac;
4406 std::unique_ptr<VerifiedInputEvent> result;
4407 switch (event.getType()) {
4408 case AINPUT_EVENT_TYPE_KEY: {
4409 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4410 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4411 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004412 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004413 break;
4414 }
4415 case AINPUT_EVENT_TYPE_MOTION: {
4416 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4417 VerifiedMotionEvent verifiedMotionEvent =
4418 verifiedMotionEventFromMotionEvent(motionEvent);
4419 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004420 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004421 break;
4422 }
4423 default: {
4424 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4425 return nullptr;
4426 }
4427 }
4428 if (calculatedHmac == INVALID_HMAC) {
4429 return nullptr;
4430 }
4431 if (calculatedHmac != event.getHmac()) {
4432 return nullptr;
4433 }
4434 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004435}
4436
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004437void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004438 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004439 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004442 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004445 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446 // Log the outcome since the injector did not wait for the injection result.
4447 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 ALOGV("Asynchronous input event injection succeeded.");
4450 break;
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004451 case InputEventInjectionResult::TARGET_MISMATCH:
4452 ALOGV("Asynchronous input event injection target mismatch.");
4453 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 ALOGW("Asynchronous input event injection failed.");
4456 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004457 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 ALOGW("Asynchronous input event injection timed out.");
4459 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004460 case InputEventInjectionResult::PENDING:
4461 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4462 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 }
4464 }
4465
4466 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004467 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 }
4469}
4470
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004471void InputDispatcher::transformMotionEntryForInjectionLocked(
4472 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004473 // Input injection works in the logical display coordinate space, but the input pipeline works
4474 // display space, so we need to transform the injected events accordingly.
4475 const auto it = mDisplayInfos.find(entry.displayId);
4476 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004477 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004478
4479 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004480 entry.pointerCoords[i] =
4481 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4482 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004483 }
4484}
4485
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4487 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 if (injectionState) {
4489 injectionState->pendingForegroundDispatches += 1;
4490 }
4491}
4492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4494 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 if (injectionState) {
4496 injectionState->pendingForegroundDispatches -= 1;
4497
4498 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004499 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
4501 }
4502}
4503
chaviw98318de2021-05-19 16:45:23 -05004504const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004505 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004506 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004507 auto it = mWindowHandlesByDisplay.find(displayId);
4508 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004509}
4510
chaviw98318de2021-05-19 16:45:23 -05004511sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004512 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004513 if (windowHandleToken == nullptr) {
4514 return nullptr;
4515 }
4516
Arthur Hungb92218b2018-08-14 12:00:21 +08004517 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004518 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4519 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004520 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004521 return windowHandle;
4522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004525 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526}
4527
chaviw98318de2021-05-19 16:45:23 -05004528sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4529 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004530 if (windowHandleToken == nullptr) {
4531 return nullptr;
4532 }
4533
chaviw98318de2021-05-19 16:45:23 -05004534 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004535 if (windowHandle->getToken() == windowHandleToken) {
4536 return windowHandle;
4537 }
4538 }
4539 return nullptr;
4540}
4541
chaviw98318de2021-05-19 16:45:23 -05004542sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4543 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004544 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004545 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4546 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004547 if (handle->getId() == windowHandle->getId() &&
4548 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004549 if (windowHandle->getInfo()->displayId != it.first) {
4550 ALOGE("Found window %s in display %" PRId32
4551 ", but it should belong to display %" PRId32,
4552 windowHandle->getName().c_str(), it.first,
4553 windowHandle->getInfo()->displayId);
4554 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004555 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004559 return nullptr;
4560}
4561
chaviw98318de2021-05-19 16:45:23 -05004562sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004563 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4564 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565}
4566
chaviw98318de2021-05-19 16:45:23 -05004567bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004568 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4569 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004570 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004571 if (connection != nullptr && noInputChannel) {
4572 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4573 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4574 return false;
4575 }
4576
4577 if (connection == nullptr) {
4578 if (!noInputChannel) {
4579 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4580 }
4581 return false;
4582 }
4583 if (!connection->responsive) {
4584 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4585 return false;
4586 }
4587 return true;
4588}
4589
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004590std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4591 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004592 auto connectionIt = mConnectionsByToken.find(token);
4593 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004594 return nullptr;
4595 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004596 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004597}
4598
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004599void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004600 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4601 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004602 // Remove all handles on a display if there are no windows left.
4603 mWindowHandlesByDisplay.erase(displayId);
4604 return;
4605 }
4606
4607 // Since we compare the pointer of input window handles across window updates, we need
4608 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004609 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4610 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4611 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004612 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004613 }
4614
chaviw98318de2021-05-19 16:45:23 -05004615 std::vector<sp<WindowInfoHandle>> newHandles;
4616 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004617 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004618 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004619 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004620 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004621 const bool canReceiveInput =
4622 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4623 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004624 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004625 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004626 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004627 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004628 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004629 }
4630
4631 if (info->displayId != displayId) {
4632 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4633 handle->getName().c_str(), displayId, info->displayId);
4634 continue;
4635 }
4636
Robert Carredd13602020-04-13 17:24:34 -07004637 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4638 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004639 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004640 oldHandle->updateFrom(handle);
4641 newHandles.push_back(oldHandle);
4642 } else {
4643 newHandles.push_back(handle);
4644 }
4645 }
4646
4647 // Insert or replace
4648 mWindowHandlesByDisplay[displayId] = newHandles;
4649}
4650
Arthur Hung72d8dc32020-03-28 00:48:39 +00004651void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004652 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004653 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004654 { // acquire lock
4655 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004656 for (const auto& [displayId, handles] : handlesPerDisplay) {
4657 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004658 }
4659 }
4660 // Wake up poll loop since it may need to make new input dispatching choices.
4661 mLooper->wake();
4662}
4663
Arthur Hungb92218b2018-08-14 12:00:21 +08004664/**
4665 * Called from InputManagerService, update window handle list by displayId that can receive input.
4666 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4667 * If set an empty list, remove all handles from the specific display.
4668 * For focused handle, check if need to change and send a cancel event to previous one.
4669 * For removed handle, check if need to send a cancel event if already in touch.
4670 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004671void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004672 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004673 if (DEBUG_FOCUS) {
4674 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004675 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004676 windowList += iwh->getName() + " ";
4677 }
4678 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680
Prabir Pradhand65552b2021-10-07 11:23:50 -07004681 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004682 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004683 const WindowInfo& info = *window->getInfo();
4684
4685 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004686 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004687 if (noInputWindow && window->getToken() != nullptr) {
4688 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4689 window->getName().c_str());
4690 window->releaseChannel();
4691 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004692
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004693 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004694 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4695 !info.inputConfig.test(
4696 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004697 "%s has feature SPY, but is not a trusted overlay.",
4698 window->getName().c_str());
4699
Prabir Pradhand65552b2021-10-07 11:23:50 -07004700 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004701 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4702 !info.inputConfig.test(
4703 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004704 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4705 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004706 }
4707
Arthur Hung72d8dc32020-03-28 00:48:39 +00004708 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004709 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004711 // Save the old windows' orientation by ID before it gets updated.
4712 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004713 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004714 oldWindowOrientations.emplace(handle->getId(),
4715 handle->getInfo()->transform.getOrientation());
4716 }
4717
chaviw98318de2021-05-19 16:45:23 -05004718 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004719
chaviw98318de2021-05-19 16:45:23 -05004720 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Tommy Nordgrenab0cedb2022-10-13 11:25:57 +02004721 if (mLastHoverWindowHandle) {
4722 const WindowInfo* lastHoverWindowInfo = mLastHoverWindowHandle->getInfo();
4723 if (lastHoverWindowInfo->displayId == displayId &&
4724 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4725 windowHandles.end()) {
4726 mLastHoverWindowHandle = nullptr;
4727 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728 }
4729
Vishnu Nairc519ff72021-01-21 08:23:08 -08004730 std::optional<FocusResolver::FocusChanges> changes =
4731 mFocusResolver.setInputWindows(displayId, windowHandles);
4732 if (changes) {
4733 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004736 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4737 mTouchStatesByDisplay.find(displayId);
4738 if (stateIt != mTouchStatesByDisplay.end()) {
4739 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004740 for (size_t i = 0; i < state.windows.size();) {
4741 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004742 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004743 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004744 ALOGD("Touched window was removed: %s in display %" PRId32,
4745 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004746 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004747 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004748 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4749 if (touchedInputChannel != nullptr) {
4750 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4751 "touched window was removed");
4752 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004753 // Since we are about to drop the touch, cancel the events for the wallpaper as
4754 // well.
4755 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004756 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4757 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004758 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4759 if (wallpaper != nullptr) {
4760 sp<Connection> wallpaperConnection =
4761 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004762 if (wallpaperConnection != nullptr) {
4763 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4764 options);
4765 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004766 }
4767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004769 state.windows.erase(state.windows.begin() + i);
4770 } else {
4771 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773 }
arthurhungb89ccb02020-12-30 16:19:01 +08004774
arthurhung6d4bed92021-03-17 11:59:33 +08004775 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004776 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004777 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004778 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004779 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004780 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4781 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004782 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004783 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004785
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004786 // Determine if the orientation of any of the input windows have changed, and cancel all
4787 // pointer events if necessary.
4788 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4789 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4790 if (newWindowHandle != nullptr &&
4791 newWindowHandle->getInfo()->transform.getOrientation() !=
4792 oldWindowOrientations[oldWindowHandle->getId()]) {
4793 std::shared_ptr<InputChannel> inputChannel =
4794 getInputChannelLocked(newWindowHandle->getToken());
4795 if (inputChannel != nullptr) {
4796 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4797 "touched window's orientation changed");
4798 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004799 }
4800 }
4801 }
4802
Arthur Hung72d8dc32020-03-28 00:48:39 +00004803 // Release information for windows that are no longer present.
4804 // This ensures that unused input channels are released promptly.
4805 // Otherwise, they might stick around until the window handle is destroyed
4806 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004807 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004808 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 if (DEBUG_FOCUS) {
4810 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004811 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004812 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004813 }
chaviw291d88a2019-02-14 10:33:58 -08004814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815}
4816
4817void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004818 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004819 if (DEBUG_FOCUS) {
4820 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4821 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4822 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004823 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004824 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004825 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 } // release lock
4827
4828 // Wake up poll loop since it may need to make new input dispatching choices.
4829 mLooper->wake();
4830}
4831
Vishnu Nair599f1412021-06-21 10:39:58 -07004832void InputDispatcher::setFocusedApplicationLocked(
4833 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4834 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4835 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4836
4837 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4838 return; // This application is already focused. No need to wake up or change anything.
4839 }
4840
4841 // Set the new application handle.
4842 if (inputApplicationHandle != nullptr) {
4843 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4844 } else {
4845 mFocusedApplicationHandlesByDisplay.erase(displayId);
4846 }
4847
4848 // No matter what the old focused application was, stop waiting on it because it is
4849 // no longer focused.
4850 resetNoFocusedWindowTimeoutLocked();
4851}
4852
Tiger Huang721e26f2018-07-24 22:26:19 +08004853/**
4854 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4855 * the display not specified.
4856 *
4857 * We track any unreleased events for each window. If a window loses the ability to receive the
4858 * released event, we will send a cancel event to it. So when the focused display is changed, we
4859 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4860 * display. The display-specified events won't be affected.
4861 */
4862void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004863 if (DEBUG_FOCUS) {
4864 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4865 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004866 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004867 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004868
4869 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004870 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004871 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004872 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004873 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004874 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004875 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876 CancelationOptions
4877 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4878 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004879 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004880 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4881 }
4882 }
4883 mFocusedDisplayId = displayId;
4884
Chris Ye3c2d6f52020-08-09 10:39:48 -07004885 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004886 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004887 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004888
Vishnu Nairad321cd2020-08-20 16:40:21 -07004889 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004890 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004891 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004892 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004893 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004894 }
4895 }
4896 }
4897
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004898 if (DEBUG_FOCUS) {
4899 logDispatchStateLocked();
4900 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004901 } // release lock
4902
4903 // Wake up poll loop since it may need to make new input dispatching choices.
4904 mLooper->wake();
4905}
4906
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004908 if (DEBUG_FOCUS) {
4909 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911
4912 bool changed;
4913 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004914 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4917 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 }
4920
4921 if (mDispatchEnabled && !enabled) {
4922 resetAndDropEverythingLocked("dispatcher is being disabled");
4923 }
4924
4925 mDispatchEnabled = enabled;
4926 mDispatchFrozen = frozen;
4927 changed = true;
4928 } else {
4929 changed = false;
4930 }
4931
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004932 if (DEBUG_FOCUS) {
4933 logDispatchStateLocked();
4934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 } // release lock
4936
4937 if (changed) {
4938 // Wake up poll loop since it may need to make new input dispatching choices.
4939 mLooper->wake();
4940 }
4941}
4942
4943void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004944 if (DEBUG_FOCUS) {
4945 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
4948 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004949 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950
4951 if (mInputFilterEnabled == enabled) {
4952 return;
4953 }
4954
4955 mInputFilterEnabled = enabled;
4956 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4957 } // release lock
4958
4959 // Wake up poll loop since there might be work to do to drop everything.
4960 mLooper->wake();
4961}
4962
Antonio Kantekea47acb2021-12-23 12:41:25 -08004963bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4964 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004965 bool needWake = false;
4966 {
4967 std::scoped_lock lock(mLock);
4968 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004969 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004970 }
4971 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004972 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4973 "hasPermission=%s)",
4974 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4975 }
4976 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07004977 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
4978 !recentWindowsAreOwnedByLocked(pid, uid)) {
4979 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
4980 "window nor none of the previously interacted window",
4981 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004982 return false;
4983 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004984 }
4985
4986 // TODO(b/198499018): Store touch mode per display.
4987 mInTouchMode = inTouchMode;
4988
Antonio Kantekf16f2832021-09-28 04:39:20 +00004989 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4990 needWake = enqueueInboundEventLocked(std::move(entry));
4991 } // release lock
4992
4993 if (needWake) {
4994 mLooper->wake();
4995 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004996 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004997}
4998
Antonio Kantek48710e42022-03-24 14:19:30 -07004999bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5000 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5001 if (focusedToken == nullptr) {
5002 return false;
5003 }
5004 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5005 return isWindowOwnedBy(windowHandle, pid, uid);
5006}
5007
5008bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5009 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5010 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5011 const sp<WindowInfoHandle> windowHandle =
5012 getWindowHandleLocked(connectionToken);
5013 return isWindowOwnedBy(windowHandle, pid, uid);
5014 }) != mInteractionConnectionTokens.end();
5015}
5016
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005017void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5018 if (opacity < 0 || opacity > 1) {
5019 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5020 return;
5021 }
5022
5023 std::scoped_lock lock(mLock);
5024 mMaximumObscuringOpacityForTouch = opacity;
5025}
5026
5027void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5028 std::scoped_lock lock(mLock);
5029 mBlockUntrustedTouchesMode = mode;
5030}
5031
Arthur Hungabbb9d82021-09-01 14:52:30 +00005032std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5033 const sp<IBinder>& token) {
5034 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5035 for (TouchedWindow& w : state.windows) {
5036 if (w.windowHandle->getToken() == token) {
5037 return std::make_pair(&state, &w);
5038 }
5039 }
5040 }
5041 return std::make_pair(nullptr, nullptr);
5042}
5043
arthurhungb89ccb02020-12-30 16:19:01 +08005044bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5045 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005046 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005047 if (DEBUG_FOCUS) {
5048 ALOGD("Trivial transfer to same window.");
5049 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005050 return true;
5051 }
5052
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005054 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055
Arthur Hungabbb9d82021-09-01 14:52:30 +00005056 // Find the target touch state and touched window by fromToken.
5057 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5058 if (state == nullptr || touchedWindow == nullptr) {
5059 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 return false;
5061 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005062
5063 const int32_t displayId = state->displayId;
5064 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5065 if (toWindowHandle == nullptr) {
5066 ALOGW("Cannot transfer focus because to window not found.");
5067 return false;
5068 }
5069
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005070 if (DEBUG_FOCUS) {
5071 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005072 touchedWindow->windowHandle->getName().c_str(),
5073 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 }
5075
Arthur Hungabbb9d82021-09-01 14:52:30 +00005076 // Erase old window.
5077 int32_t oldTargetFlags = touchedWindow->targetFlags;
5078 BitSet32 pointerIds = touchedWindow->pointerIds;
5079 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080
Arthur Hungabbb9d82021-09-01 14:52:30 +00005081 // Add new window.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005082 int32_t newTargetFlags =
5083 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5084 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5085 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5086 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005087 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088
Arthur Hungabbb9d82021-09-01 14:52:30 +00005089 // Store the dragging window.
5090 if (isDragDrop) {
Arthur Hung54745652022-04-20 07:17:41 +00005091 if (pointerIds.count() > 1) {
5092 ALOGW("The drag and drop cannot be started when there is more than 1 pointer on the"
5093 " window.");
5094 return false;
5095 }
5096 // If the window didn't not support split or the source is mouse, the pointerIds count
5097 // would be 0, so we have to track the pointer 0.
5098 const int32_t id = pointerIds.count() == 0 ? 0 : pointerIds.firstMarkedBit();
5099 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101
Arthur Hungabbb9d82021-09-01 14:52:30 +00005102 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005103 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5104 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005105 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005106 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005107 CancelationOptions
5108 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5109 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005111 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005114 if (DEBUG_FOCUS) {
5115 logDispatchStateLocked();
5116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 } // release lock
5118
5119 // Wake up poll loop since it may need to make new input dispatching choices.
5120 mLooper->wake();
5121 return true;
5122}
5123
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005124/**
5125 * Get the touched foreground window on the given display.
5126 * Return null if there are no windows touched on that display, or if more than one foreground
5127 * window is being touched.
5128 */
5129sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5130 auto stateIt = mTouchStatesByDisplay.find(displayId);
5131 if (stateIt == mTouchStatesByDisplay.end()) {
5132 ALOGI("No touch state on display %" PRId32, displayId);
5133 return nullptr;
5134 }
5135
5136 const TouchState& state = stateIt->second;
5137 sp<WindowInfoHandle> touchedForegroundWindow;
5138 // If multiple foreground windows are touched, return nullptr
5139 for (const TouchedWindow& window : state.windows) {
5140 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5141 if (touchedForegroundWindow != nullptr) {
5142 ALOGI("Two or more foreground windows: %s and %s",
5143 touchedForegroundWindow->getName().c_str(),
5144 window.windowHandle->getName().c_str());
5145 return nullptr;
5146 }
5147 touchedForegroundWindow = window.windowHandle;
5148 }
5149 }
5150 return touchedForegroundWindow;
5151}
5152
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005153// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005154bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005155 sp<IBinder> fromToken;
5156 { // acquire lock
5157 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005158 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005159 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005160 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5161 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005162 return false;
5163 }
5164
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005165 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5166 if (from == nullptr) {
5167 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5168 return false;
5169 }
5170
5171 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005172 } // release lock
5173
5174 return transferTouchFocus(fromToken, destChannelToken);
5175}
5176
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005178 if (DEBUG_FOCUS) {
5179 ALOGD("Resetting and dropping all events (%s).", reason);
5180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181
5182 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5183 synthesizeCancelationEventsForAllConnectionsLocked(options);
5184
5185 resetKeyRepeatLocked();
5186 releasePendingEventLocked();
5187 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005188 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005190 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005191 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005193 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194}
5195
5196void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005197 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 dumpDispatchStateLocked(dump);
5199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005200 std::istringstream stream(dump);
5201 std::string line;
5202
5203 while (std::getline(stream, line, '\n')) {
5204 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 }
5206}
5207
Prabir Pradhan99987712020-11-10 18:43:05 -08005208std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5209 std::string dump;
5210
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005211 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5212 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005213
5214 std::string windowName = "None";
5215 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005216 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005217 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5218 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5219 : "token has capture without window";
5220 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005221 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005222
5223 return dump;
5224}
5225
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005226void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005227 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5228 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5229 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005230 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231
Tiger Huang721e26f2018-07-24 22:26:19 +08005232 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5233 dump += StringPrintf(INDENT "FocusedApplications:\n");
5234 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5235 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005236 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005237 const std::chrono::duration timeout =
5238 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005239 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005240 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005241 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005244 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005246
Vishnu Nairc519ff72021-01-21 08:23:08 -08005247 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005248 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005250 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005251 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005252 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5253 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005254 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005255 state.displayId, toString(state.down), toString(state.split),
5256 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005257 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005258 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005259 for (size_t i = 0; i < state.windows.size(); i++) {
5260 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005261 dump += StringPrintf(INDENT4
5262 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5263 i, touchedWindow.windowHandle->getName().c_str(),
5264 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005265 }
5266 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005267 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 }
5270 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005271 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 }
5273
arthurhung6d4bed92021-03-17 11:59:33 +08005274 if (mDragState) {
5275 dump += StringPrintf(INDENT "DragState:\n");
5276 mDragState->dump(dump, INDENT2);
5277 }
5278
Arthur Hungb92218b2018-08-14 12:00:21 +08005279 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005280 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5281 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5282 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5283 const auto& displayInfo = it->second;
5284 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5285 displayInfo.logicalHeight);
5286 displayInfo.transform.dump(dump, "transform", INDENT4);
5287 } else {
5288 dump += INDENT2 "No DisplayInfo found!\n";
5289 }
5290
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005291 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005292 dump += INDENT2 "Windows:\n";
5293 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005294 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5295 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005297 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005298 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005299 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005300 "applicationInfo.name=%s, "
5301 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005302 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005303 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005304 windowInfo->displayId,
5305 windowInfo->inputConfig.string().c_str(),
5306 windowInfo->alpha, windowInfo->frameLeft,
5307 windowInfo->frameTop, windowInfo->frameRight,
5308 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005309 windowInfo->applicationInfo.name.c_str(),
5310 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005311 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005312 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005313 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005314 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005315 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005316 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005317 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005318 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005319 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005320 }
5321 } else {
5322 dump += INDENT2 "Windows: <none>\n";
5323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005326 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005329 if (!mGlobalMonitorsByDisplay.empty()) {
5330 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5331 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005332 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005335 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 }
5337
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005338 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339
5340 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005341 if (!mRecentQueue.empty()) {
5342 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005343 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
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 "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 }
5351
5352 // Dump event currently being dispatched.
5353 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005354 dump += INDENT "PendingEvent:\n";
5355 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005356 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005357 dump += StringPrintf(", age=%" PRId64 "ms\n",
5358 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005360 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 }
5362
5363 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005364 if (!mInboundQueue.empty()) {
5365 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005366 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005367 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005368 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005369 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 }
5371 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005372 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 }
5374
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005375 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005376 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005377 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5378 const KeyReplacement& replacement = pair.first;
5379 int32_t newKeyCode = pair.second;
5380 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005381 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005382 }
5383 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005384 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005385 }
5386
Prabir Pradhancef936d2021-07-21 16:17:52 +00005387 if (!mCommandQueue.empty()) {
5388 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5389 } else {
5390 dump += INDENT "CommandQueue: <empty>\n";
5391 }
5392
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005393 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005394 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005395 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005396 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005397 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005398 connection->inputChannel->getFd().get(),
5399 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005400 connection->getWindowName().c_str(),
5401 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005402 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005404 if (!connection->outboundQueue.empty()) {
5405 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5406 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005407 dump += dumpQueue(connection->outboundQueue, currentTime);
5408
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005410 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005413 if (!connection->waitQueue.empty()) {
5414 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5415 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005416 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005418 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 }
5420 }
5421 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005422 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005423 }
5424
5425 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005426 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5427 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005432 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005433 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5434 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5435 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005436 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005437 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438}
5439
Michael Wright3dd60e22019-03-27 22:06:44 +00005440void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5441 const size_t numMonitors = monitors.size();
5442 for (size_t i = 0; i < numMonitors; i++) {
5443 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005444 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005445 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5446 dump += "\n";
5447 }
5448}
5449
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005450class LooperEventCallback : public LooperCallback {
5451public:
5452 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5453 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5454
5455private:
5456 std::function<int(int events)> mCallback;
5457};
5458
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005459Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005460 if (DEBUG_CHANNEL_CREATION) {
5461 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005464 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005465 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005466 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005467
5468 if (result) {
5469 return base::Error(result) << "Failed to open input channel pair with name " << name;
5470 }
5471
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005473 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005474 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005475 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005476 sp<Connection> connection =
5477 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005479 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5480 ALOGE("Created a new connection, but the token %p is already known", token.get());
5481 }
5482 mConnectionsByToken.emplace(token, connection);
5483
5484 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5485 this, std::placeholders::_1, token);
5486
5487 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 } // release lock
5489
5490 // Wake the looper because some connections have changed.
5491 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005492 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493}
5494
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005495Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005496 const std::string& name,
5497 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005498 std::shared_ptr<InputChannel> serverChannel;
5499 std::unique_ptr<InputChannel> clientChannel;
5500 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5501 if (result) {
5502 return base::Error(result) << "Failed to open input channel pair with name " << name;
5503 }
5504
Michael Wright3dd60e22019-03-27 22:06:44 +00005505 { // acquire lock
5506 std::scoped_lock _l(mLock);
5507
5508 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005509 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5510 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005511 }
5512
Garfield Tan15601662020-09-22 15:32:38 -07005513 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005514 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005515 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005516
5517 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5518 ALOGE("Created a new connection, but the token %p is already known", token.get());
5519 }
5520 mConnectionsByToken.emplace(token, connection);
5521 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5522 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005523
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005524 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005525
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005526 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005527 }
Garfield Tan15601662020-09-22 15:32:38 -07005528
Michael Wright3dd60e22019-03-27 22:06:44 +00005529 // Wake the looper because some connections have changed.
5530 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005531 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005532}
5533
Garfield Tan15601662020-09-22 15:32:38 -07005534status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005536 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537
Garfield Tan15601662020-09-22 15:32:38 -07005538 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 if (status) {
5540 return status;
5541 }
5542 } // release lock
5543
5544 // Wake the poll loop because removing the connection may have changed the current
5545 // synchronization state.
5546 mLooper->wake();
5547 return OK;
5548}
5549
Garfield Tan15601662020-09-22 15:32:38 -07005550status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5551 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005552 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005553 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005554 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 return BAD_VALUE;
5556 }
5557
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005558 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005559
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005561 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005564 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565
5566 nsecs_t currentTime = now();
5567 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5568
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005569 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 return OK;
5571}
5572
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005573void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005574 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5575 auto& [displayId, monitors] = *it;
5576 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5577 return monitor.inputChannel->getConnectionToken() == connectionToken;
5578 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005579
Michael Wright3dd60e22019-03-27 22:06:44 +00005580 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005581 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005582 } else {
5583 ++it;
5584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586}
5587
Michael Wright3dd60e22019-03-27 22:06:44 +00005588status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005589 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005590
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005591 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5592 if (!requestingChannel) {
5593 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5594 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005595 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005596
5597 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5598 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5599 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5600 " Ignoring.");
5601 return BAD_VALUE;
5602 }
5603
5604 TouchState& state = *statePtr;
5605
5606 // Send cancel events to all the input channels we're stealing from.
5607 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5608 "input channel stole pointer stream");
5609 options.deviceId = state.deviceId;
5610 options.displayId = state.displayId;
5611 std::string canceledWindows;
5612 for (const TouchedWindow& window : state.windows) {
5613 const std::shared_ptr<InputChannel> channel =
5614 getInputChannelLocked(window.windowHandle->getToken());
5615 if (channel != nullptr && channel->getConnectionToken() != token) {
5616 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5617 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5618 canceledWindows += channel->getName();
5619 }
5620 }
5621 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5622 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5623 canceledWindows.c_str());
5624
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005625 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005626 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005627 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005628 return OK;
5629}
5630
Prabir Pradhan99987712020-11-10 18:43:05 -08005631void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5632 { // acquire lock
5633 std::scoped_lock _l(mLock);
5634 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005635 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005636 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5637 windowHandle != nullptr ? windowHandle->getName().c_str()
5638 : "token without window");
5639 }
5640
Vishnu Nairc519ff72021-01-21 08:23:08 -08005641 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005642 if (focusedToken != windowToken) {
5643 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5644 enabled ? "enable" : "disable");
5645 return;
5646 }
5647
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005648 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005649 ALOGW("Ignoring request to %s Pointer Capture: "
5650 "window has %s requested pointer capture.",
5651 enabled ? "enable" : "disable", enabled ? "already" : "not");
5652 return;
5653 }
5654
Christine Franksb768bb42021-11-29 12:11:31 -08005655 if (enabled) {
5656 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5657 mIneligibleDisplaysForPointerCapture.end(),
5658 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5659 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5660 return;
5661 }
5662 }
5663
Prabir Pradhan99987712020-11-10 18:43:05 -08005664 setPointerCaptureLocked(enabled);
5665 } // release lock
5666
5667 // Wake the thread to process command entries.
5668 mLooper->wake();
5669}
5670
Christine Franksb768bb42021-11-29 12:11:31 -08005671void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5672 { // acquire lock
5673 std::scoped_lock _l(mLock);
5674 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5675 if (!isEligible) {
5676 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5677 }
5678 } // release lock
5679}
5680
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005681std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5682 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005683 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005684 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005685 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005686 }
5687 }
5688 }
5689 return std::nullopt;
5690}
5691
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005692sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005693 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005694 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005695 }
5696
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005697 for (const auto& [token, connection] : mConnectionsByToken) {
5698 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005699 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700 }
5701 }
Robert Carr4e670e52018-08-15 13:26:12 -07005702
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005703 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704}
5705
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005706std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5707 sp<Connection> connection = getConnectionLocked(connectionToken);
5708 if (connection == nullptr) {
5709 return "<nullptr>";
5710 }
5711 return connection->getInputChannelName();
5712}
5713
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005714void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005715 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005716 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005717}
5718
Prabir Pradhancef936d2021-07-21 16:17:52 +00005719void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5720 const sp<Connection>& connection, uint32_t seq,
5721 bool handled, nsecs_t consumeTime) {
5722 // Handle post-event policy actions.
5723 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5724 if (dispatchEntryIt == connection->waitQueue.end()) {
5725 return;
5726 }
5727 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5728 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5729 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5730 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5731 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5732 }
5733 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5734 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5735 connection->inputChannel->getConnectionToken(),
5736 dispatchEntry->deliveryTime, consumeTime, finishTime);
5737 }
5738
5739 bool restartEvent;
5740 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5741 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5742 restartEvent =
5743 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5744 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5745 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5746 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5747 handled);
5748 } else {
5749 restartEvent = false;
5750 }
5751
5752 // Dequeue the event and start the next cycle.
5753 // Because the lock might have been released, it is possible that the
5754 // contents of the wait queue to have been drained, so we need to double-check
5755 // a few things.
5756 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5757 if (dispatchEntryIt != connection->waitQueue.end()) {
5758 dispatchEntry = *dispatchEntryIt;
5759 connection->waitQueue.erase(dispatchEntryIt);
5760 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5761 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5762 if (!connection->responsive) {
5763 connection->responsive = isConnectionResponsive(*connection);
5764 if (connection->responsive) {
5765 // The connection was unresponsive, and now it's responsive.
5766 processConnectionResponsiveLocked(*connection);
5767 }
5768 }
5769 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005770 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005771 connection->outboundQueue.push_front(dispatchEntry);
5772 traceOutboundQueueLength(*connection);
5773 } else {
5774 releaseDispatchEntry(dispatchEntry);
5775 }
5776 }
5777
5778 // Start the next dispatch cycle for this connection.
5779 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780}
5781
Prabir Pradhancef936d2021-07-21 16:17:52 +00005782void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5783 const sp<IBinder>& newToken) {
5784 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5785 scoped_unlock unlock(mLock);
5786 mPolicy->notifyFocusChanged(oldToken, newToken);
5787 };
5788 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789}
5790
Prabir Pradhancef936d2021-07-21 16:17:52 +00005791void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5792 auto command = [this, token, x, y]() REQUIRES(mLock) {
5793 scoped_unlock unlock(mLock);
5794 mPolicy->notifyDropWindow(token, x, y);
5795 };
5796 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005797}
5798
Prabir Pradhancef936d2021-07-21 16:17:52 +00005799void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5800 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5801 scoped_unlock unlock(mLock);
5802 mPolicy->notifyUntrustedTouch(obscuringPackage);
5803 };
5804 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005805}
5806
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005807void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5808 if (connection == nullptr) {
5809 LOG_ALWAYS_FATAL("Caller must check for nullness");
5810 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005811 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5812 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005813 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005814 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005815 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005816 return;
5817 }
5818 /**
5819 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5820 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5821 * has changed. This could cause newer entries to time out before the already dispatched
5822 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5823 * processes the events linearly. So providing information about the oldest entry seems to be
5824 * most useful.
5825 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005826 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005827 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5828 std::string reason =
5829 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005830 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005831 ns2ms(currentWait),
5832 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005833 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005834 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005835
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005836 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5837
5838 // Stop waking up for events on this connection, it is already unresponsive
5839 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005840}
5841
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005842void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5843 std::string reason =
5844 StringPrintf("%s does not have a focused window", application->getName().c_str());
5845 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846
Prabir Pradhancef936d2021-07-21 16:17:52 +00005847 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5848 scoped_unlock unlock(mLock);
5849 mPolicy->notifyNoFocusedWindowAnr(application);
5850 };
5851 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005852}
5853
chaviw98318de2021-05-19 16:45:23 -05005854void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005855 const std::string& reason) {
5856 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5857 updateLastAnrStateLocked(windowLabel, reason);
5858}
5859
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005860void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5861 const std::string& reason) {
5862 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005863 updateLastAnrStateLocked(windowLabel, reason);
5864}
5865
5866void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5867 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005869 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 struct tm tm;
5871 localtime_r(&t, &tm);
5872 char timestr[64];
5873 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005874 mLastAnrState.clear();
5875 mLastAnrState += INDENT "ANR:\n";
5876 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005877 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5878 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005879 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880}
5881
Prabir Pradhancef936d2021-07-21 16:17:52 +00005882void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5883 KeyEntry& entry) {
5884 const KeyEvent event = createKeyEvent(entry);
5885 nsecs_t delay = 0;
5886 { // release lock
5887 scoped_unlock unlock(mLock);
5888 android::base::Timer t;
5889 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5890 entry.policyFlags);
5891 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5892 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5893 std::to_string(t.duration().count()).c_str());
5894 }
5895 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896
5897 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005898 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005899 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005900 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005902 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5903 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905}
5906
Prabir Pradhancef936d2021-07-21 16:17:52 +00005907void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005908 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005909 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005910 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005911 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005912 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005913 };
5914 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005915}
5916
Prabir Pradhanedd96402022-02-15 01:46:16 -08005917void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5918 std::optional<int32_t> pid) {
5919 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005920 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005921 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005922 };
5923 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005924}
5925
5926/**
5927 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5928 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5929 * command entry to the command queue.
5930 */
5931void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5932 std::string reason) {
5933 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005934 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005935 if (connection.monitor) {
5936 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5937 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005938 pid = findMonitorPidByTokenLocked(connectionToken);
5939 } else {
5940 // The connection is a window
5941 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5942 reason.c_str());
5943 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5944 if (handle != nullptr) {
5945 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005946 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005947 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005948 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005949}
5950
5951/**
5952 * Tell the policy that a connection has become responsive so that it can stop ANR.
5953 */
5954void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5955 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005956 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005957 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005958 pid = findMonitorPidByTokenLocked(connectionToken);
5959 } else {
5960 // The connection is a window
5961 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5962 if (handle != nullptr) {
5963 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005964 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005965 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005966 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005967}
5968
Prabir Pradhancef936d2021-07-21 16:17:52 +00005969bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005970 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 KeyEntry& keyEntry, bool handled) {
5972 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005973 if (!handled) {
5974 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005976 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005977 return false;
5978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005980 // Get the fallback key state.
5981 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005982 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005984 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985 connection->inputState.removeFallbackKey(originalKeyCode);
5986 }
5987
5988 if (handled || !dispatchEntry->hasForegroundTarget()) {
5989 // If the application handles the original key for which we previously
5990 // generated a fallback or if the window is not a foreground window,
5991 // then cancel the associated fallback key, if any.
5992 if (fallbackKeyCode != -1) {
5993 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005994 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5995 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5996 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5997 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5998 keyEntry.policyFlags);
5999 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006000 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006001 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002
6003 mLock.unlock();
6004
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006005 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006006 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007
6008 mLock.lock();
6009
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 // Cancel the fallback key.
6011 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006013 "application handled the original non-fallback key "
6014 "or is no longer a foreground target, "
6015 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 options.keyCode = fallbackKeyCode;
6017 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006019 connection->inputState.removeFallbackKey(originalKeyCode);
6020 }
6021 } else {
6022 // If the application did not handle a non-fallback key, first check
6023 // that we are in a good state to perform unhandled key event processing
6024 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006025 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006026 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006027 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6028 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6029 "since this is not an initial down. "
6030 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6031 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6032 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006033 return false;
6034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006036 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006037 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6038 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6039 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6040 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6041 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006042 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043
6044 mLock.unlock();
6045
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006046 bool fallback =
6047 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006048 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006049
6050 mLock.lock();
6051
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006052 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 connection->inputState.removeFallbackKey(originalKeyCode);
6054 return false;
6055 }
6056
6057 // Latch the fallback keycode for this key on an initial down.
6058 // The fallback keycode cannot change at any other point in the lifecycle.
6059 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061 fallbackKeyCode = event.getKeyCode();
6062 } else {
6063 fallbackKeyCode = AKEYCODE_UNKNOWN;
6064 }
6065 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6066 }
6067
6068 ALOG_ASSERT(fallbackKeyCode != -1);
6069
6070 // Cancel the fallback key if the policy decides not to send it anymore.
6071 // We will continue to dispatch the key to the policy but we will no
6072 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006073 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6074 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006075 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6076 if (fallback) {
6077 ALOGD("Unhandled key event: Policy requested to send key %d"
6078 "as a fallback for %d, but on the DOWN it had requested "
6079 "to send %d instead. Fallback canceled.",
6080 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6081 } else {
6082 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6083 "but on the DOWN it had requested to send %d. "
6084 "Fallback canceled.",
6085 originalKeyCode, fallbackKeyCode);
6086 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006087 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088
6089 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6090 "canceling fallback, policy no longer desires it");
6091 options.keyCode = fallbackKeyCode;
6092 synthesizeCancelationEventsForConnectionLocked(connection, options);
6093
6094 fallback = false;
6095 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006096 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006097 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006098 }
6099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006101 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6102 {
6103 std::string msg;
6104 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6105 connection->inputState.getFallbackKeys();
6106 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6107 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6108 }
6109 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6110 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006113
6114 if (fallback) {
6115 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 keyEntry.eventTime = event.getEventTime();
6117 keyEntry.deviceId = event.getDeviceId();
6118 keyEntry.source = event.getSource();
6119 keyEntry.displayId = event.getDisplayId();
6120 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6121 keyEntry.keyCode = fallbackKeyCode;
6122 keyEntry.scanCode = event.getScanCode();
6123 keyEntry.metaState = event.getMetaState();
6124 keyEntry.repeatCount = event.getRepeatCount();
6125 keyEntry.downTime = event.getDownTime();
6126 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006127
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006128 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6129 ALOGD("Unhandled key event: Dispatching fallback key. "
6130 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6131 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6132 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133 return true; // restart the event
6134 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006135 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6136 ALOGD("Unhandled key event: No fallback key.");
6137 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006138
6139 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006140 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 }
6142 }
6143 return false;
6144}
6145
Prabir Pradhancef936d2021-07-21 16:17:52 +00006146bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006147 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006148 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149 return false;
6150}
6151
Michael Wrightd02c5b62014-02-10 15:10:22 -08006152void InputDispatcher::traceInboundQueueLengthLocked() {
6153 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006154 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006155 }
6156}
6157
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006158void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159 if (ATRACE_ENABLED()) {
6160 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006161 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6162 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163 }
6164}
6165
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006166void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 if (ATRACE_ENABLED()) {
6168 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006169 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6170 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171 }
6172}
6173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006174void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006175 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006177 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178 dumpDispatchStateLocked(dump);
6179
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006180 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006181 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006182 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183 }
6184}
6185
6186void InputDispatcher::monitor() {
6187 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006188 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006190 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191}
6192
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006193/**
6194 * Wake up the dispatcher and wait until it processes all events and commands.
6195 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6196 * this method can be safely called from any thread, as long as you've ensured that
6197 * the work you are interested in completing has already been queued.
6198 */
6199bool InputDispatcher::waitForIdle() {
6200 /**
6201 * Timeout should represent the longest possible time that a device might spend processing
6202 * events and commands.
6203 */
6204 constexpr std::chrono::duration TIMEOUT = 100ms;
6205 std::unique_lock lock(mLock);
6206 mLooper->wake();
6207 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6208 return result == std::cv_status::no_timeout;
6209}
6210
Vishnu Naire798b472020-07-23 13:52:21 -07006211/**
6212 * Sets focus to the window identified by the token. This must be called
6213 * after updating any input window handles.
6214 *
6215 * Params:
6216 * request.token - input channel token used to identify the window that should gain focus.
6217 * request.focusedToken - the token that the caller expects currently to be focused. If the
6218 * specified token does not match the currently focused window, this request will be dropped.
6219 * If the specified focused token matches the currently focused window, the call will succeed.
6220 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6221 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6222 * when requesting the focus change. This determines which request gets
6223 * precedence if there is a focus change request from another source such as pointer down.
6224 */
Vishnu Nair958da932020-08-21 17:12:37 -07006225void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6226 { // acquire lock
6227 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006228 std::optional<FocusResolver::FocusChanges> changes =
6229 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6230 if (changes) {
6231 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006232 }
6233 } // release lock
6234 // Wake up poll loop since it may need to make new input dispatching choices.
6235 mLooper->wake();
6236}
6237
Vishnu Nairc519ff72021-01-21 08:23:08 -08006238void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6239 if (changes.oldFocus) {
6240 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006241 if (focusedInputChannel) {
6242 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6243 "focus left window");
6244 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006245 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006246 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006247 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006248 if (changes.newFocus) {
6249 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006250 }
6251
Prabir Pradhan99987712020-11-10 18:43:05 -08006252 // If a window has pointer capture, then it must have focus. We need to ensure that this
6253 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6254 // If the window loses focus before it loses pointer capture, then the window can be in a state
6255 // where it has pointer capture but not focus, violating the contract. Therefore we must
6256 // dispatch the pointer capture event before the focus event. Since focus events are added to
6257 // the front of the queue (above), we add the pointer capture event to the front of the queue
6258 // after the focus events are added. This ensures the pointer capture event ends up at the
6259 // front.
6260 disablePointerCaptureForcedLocked();
6261
Vishnu Nairc519ff72021-01-21 08:23:08 -08006262 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006263 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006264 }
6265}
Vishnu Nair958da932020-08-21 17:12:37 -07006266
Prabir Pradhan99987712020-11-10 18:43:05 -08006267void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006268 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006269 return;
6270 }
6271
6272 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6273
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006274 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006275 setPointerCaptureLocked(false);
6276 }
6277
6278 if (!mWindowTokenWithPointerCapture) {
6279 // No need to send capture changes because no window has capture.
6280 return;
6281 }
6282
6283 if (mPendingEvent != nullptr) {
6284 // Move the pending event to the front of the queue. This will give the chance
6285 // for the pending event to be dropped if it is a captured event.
6286 mInboundQueue.push_front(mPendingEvent);
6287 mPendingEvent = nullptr;
6288 }
6289
6290 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006291 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006292 mInboundQueue.push_front(std::move(entry));
6293}
6294
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006295void InputDispatcher::setPointerCaptureLocked(bool enable) {
6296 mCurrentPointerCaptureRequest.enable = enable;
6297 mCurrentPointerCaptureRequest.seq++;
6298 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006299 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006300 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301 };
6302 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006303}
6304
Vishnu Nair599f1412021-06-21 10:39:58 -07006305void InputDispatcher::displayRemoved(int32_t displayId) {
6306 { // acquire lock
6307 std::scoped_lock _l(mLock);
6308 // Set an empty list to remove all handles from the specific display.
6309 setInputWindowsLocked(/* window handles */ {}, displayId);
6310 setFocusedApplicationLocked(displayId, nullptr);
6311 // Call focus resolver to clean up stale requests. This must be called after input windows
6312 // have been removed for the removed display.
6313 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006314 // Reset pointer capture eligibility, regardless of previous state.
6315 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006316 } // release lock
6317
6318 // Wake up poll loop since it may need to make new input dispatching choices.
6319 mLooper->wake();
6320}
6321
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006322void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6323 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006324 // The listener sends the windows as a flattened array. Separate the windows by display for
6325 // more convenient parsing.
6326 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006327 for (const auto& info : windowInfos) {
6328 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6329 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6330 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006331
6332 { // acquire lock
6333 std::scoped_lock _l(mLock);
6334 mDisplayInfos.clear();
6335 for (const auto& displayInfo : displayInfos) {
6336 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6337 }
6338
6339 for (const auto& [displayId, handles] : handlesPerDisplay) {
6340 setInputWindowsLocked(handles, displayId);
6341 }
6342 }
6343 // Wake up poll loop since it may need to make new input dispatching choices.
6344 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006345}
6346
Vishnu Nair062a8672021-09-03 16:07:44 -07006347bool InputDispatcher::shouldDropInput(
6348 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006349 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6350 (windowHandle->getInfo()->inputConfig.test(
6351 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006352 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006353 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6354 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006355 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006356 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006357 windowHandle->getInfo()->displayId);
6358 return true;
6359 }
6360 return false;
6361}
6362
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006363void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6364 const std::vector<gui::WindowInfo>& windowInfos,
6365 const std::vector<DisplayInfo>& displayInfos) {
6366 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6367}
6368
Arthur Hungdfd528e2021-12-08 13:23:04 +00006369void InputDispatcher::cancelCurrentTouch() {
6370 {
6371 std::scoped_lock _l(mLock);
6372 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6373 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6374 "cancel current touch");
6375 synthesizeCancelationEventsForAllConnectionsLocked(options);
6376
6377 mTouchStatesByDisplay.clear();
6378 mLastHoverWindowHandle.clear();
6379 }
6380 // Wake up poll loop since there might be work to do.
6381 mLooper->wake();
6382}
6383
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006384void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6385 std::scoped_lock _l(mLock);
6386 mMonitorDispatchingTimeout = timeout;
6387}
6388
Garfield Tane84e6f92019-08-29 17:28:41 -07006389} // namespace android::inputdispatcher