blob: caf7101e2588336bcfeff405ba92955637ec0622 [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 Pradhand65552b2021-10-07 11:23:50 -0700462bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
463 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;
931 int32_t x = static_cast<int32_t>(
932 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
933 int32_t y = static_cast<int32_t>(
934 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700935
936 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500937 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700938 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700939 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700940 touchedWindowHandle->getApplicationToken() !=
941 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700942 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700943 ALOGI("Pruning input queue because user touched a different application while waiting "
944 "for %s",
945 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700946 return true;
947 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800949 // Alternatively, maybe there's a spy window that could handle this event.
950 const std::vector<sp<WindowInfoHandle>> touchedSpies =
951 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
952 for (const auto& windowHandle : touchedSpies) {
953 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000954 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800955 // This spy window could take more input. Drop all events preceding this
956 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700957 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800958 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 mAwaitedFocusedApplication->getName().c_str());
960 return true;
961 }
962 }
963 }
964
965 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
966 // yet been processed by some connections, the dispatcher will wait for these motion
967 // events to be processed before dispatching the key event. This is because these motion events
968 // may cause a new window to be launched, which the user might expect to receive focus.
969 // To prevent waiting forever for such events, just send the key to the currently focused window
970 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
971 ALOGD("Received a new pointer down event, stop waiting for events to process and "
972 "just send the pending key event to the focused window.");
973 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700974 }
975 return false;
976}
977
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700979 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700980 mInboundQueue.push_back(std::move(newEntry));
981 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 traceInboundQueueLengthLocked();
983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700985 case EventEntry::Type::KEY: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000986 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
987 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 // Optimize app switch latency.
989 // If the application takes too long to catch up then we drop all events preceding
990 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700993 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700995 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700996 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000997 if (DEBUG_APP_SWITCH) {
998 ALOGD("App switch is pending!");
999 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001000 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 mAppSwitchSawKeyDown = false;
1002 needWake = true;
1003 }
1004 }
1005 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001006
1007 // If a new up event comes in, and the pending event with same key code has been asked
1008 // to try again later because of the policy. We have to reset the intercept key wake up
1009 // time for it may have been handled in the policy and could be dropped.
1010 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1011 mPendingEvent->type == EventEntry::Type::KEY) {
1012 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1013 if (pendingKey.keyCode == keyEntry.keyCode &&
1014 pendingKey.interceptKeyResult ==
1015 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1016 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1017 pendingKey.interceptKeyWakeupTime = 0;
1018 needWake = true;
1019 }
1020 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 break;
1022 }
1023
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001024 case EventEntry::Type::MOTION: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001025 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1026 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001027 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1028 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001029 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001034 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1035 break;
1036 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001037 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001038 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001039 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001040 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001041 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1042 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001043 // nothing to do
1044 break;
1045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
1047
1048 return needWake;
1049}
1050
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001051void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001052 // Do not store sensor event in recent queue to avoid flooding the queue.
1053 if (entry->type != EventEntry::Type::SENSOR) {
1054 mRecentQueue.push_back(entry);
1055 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001056 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001057 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
1059}
1060
chaviw98318de2021-05-19 16:45:23 -05001061sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1062 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001063 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001064 bool addOutsideTargets,
1065 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001066 if (addOutsideTargets && touchState == nullptr) {
1067 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001070 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001071 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001072 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001073 continue;
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001076 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001077 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001078 return windowHandle;
1079 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001080
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001081 if (addOutsideTargets &&
1082 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001083 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1084 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001087 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088}
1089
Prabir Pradhand65552b2021-10-07 11:23:50 -07001090std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1091 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001092 // Traverse windows from front to back and gather the touched spy windows.
1093 std::vector<sp<WindowInfoHandle>> spyWindows;
1094 const auto& windowHandles = getWindowHandlesLocked(displayId);
1095 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1096 const WindowInfo& info = *windowHandle->getInfo();
1097
Prabir Pradhand65552b2021-10-07 11:23:50 -07001098 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001099 continue;
1100 }
1101 if (!info.isSpy()) {
1102 // The first touched non-spy window was found, so return the spy windows touched so far.
1103 return spyWindows;
1104 }
1105 spyWindows.push_back(windowHandle);
1106 }
1107 return spyWindows;
1108}
1109
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001110void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 const char* reason;
1112 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001114 if (DEBUG_INBOUND_EVENT_DETAILS) {
1115 ALOGD("Dropped event because policy consumed it.");
1116 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 reason = "inbound event was dropped because the policy consumed it";
1118 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001119 case DropReason::DISABLED:
1120 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 ALOGI("Dropped event because input dispatch is disabled.");
1122 }
1123 reason = "inbound event was dropped because input dispatch is disabled";
1124 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001125 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 ALOGI("Dropped event because of pending overdue app switch.");
1127 reason = "inbound event was dropped because of pending overdue app switch";
1128 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 ALOGI("Dropped event because the current application is not responding and the user "
1131 "has started interacting with a different application.");
1132 reason = "inbound event was dropped because the current application is not responding "
1133 "and the user has started interacting with a different application";
1134 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 ALOGI("Dropped event because it is stale.");
1137 reason = "inbound event was dropped because it is stale";
1138 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 case DropReason::NO_POINTER_CAPTURE:
1140 ALOGI("Dropped event because there is no window with Pointer Capture.");
1141 reason = "inbound event was dropped because there is no window with Pointer Capture";
1142 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001143 case DropReason::NOT_DROPPED: {
1144 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001149 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001150 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1152 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001155 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1157 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1159 synthesizeCancelationEventsForAllConnectionsLocked(options);
1160 } else {
1161 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1162 synthesizeCancelationEventsForAllConnectionsLocked(options);
1163 }
1164 break;
1165 }
Chris Yef59a2f42020-10-16 12:55:26 -07001166 case EventEntry::Type::SENSOR: {
1167 break;
1168 }
arthurhungb89ccb02020-12-30 16:19:01 +08001169 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1170 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001171 break;
1172 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001173 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001174 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001175 case EventEntry::Type::CONFIGURATION_CHANGED:
1176 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001177 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001178 break;
1179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 }
1181}
1182
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001183static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001184 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1185 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186}
1187
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1189 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1190 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1191 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
1194bool InputDispatcher::isAppSwitchPendingLocked() {
1195 return mAppSwitchDueTime != LONG_LONG_MAX;
1196}
1197
1198void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1199 mAppSwitchDueTime = LONG_LONG_MAX;
1200
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001201 if (DEBUG_APP_SWITCH) {
1202 if (handled) {
1203 ALOGD("App switch has arrived.");
1204 } else {
1205 ALOGD("App switch was abandoned.");
1206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001211 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212}
1213
Prabir Pradhancef936d2021-07-21 16:17:52 +00001214bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001215 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 return false;
1217 }
1218
1219 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001220 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001221 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001222 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1223 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001224 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 return true;
1226}
1227
Prabir Pradhancef936d2021-07-21 16:17:52 +00001228void InputDispatcher::postCommandLocked(Command&& command) {
1229 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230}
1231
1232void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001234 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001235 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 releaseInboundEventLocked(entry);
1237 }
1238 traceInboundQueueLengthLocked();
1239}
1240
1241void InputDispatcher::releasePendingEventLocked() {
1242 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001244 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246}
1247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001250 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001251 if (DEBUG_DISPATCH_CYCLE) {
1252 ALOGD("Injected inbound event was dropped.");
1253 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001257 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
1259 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260}
1261
1262void InputDispatcher::resetKeyRepeatLocked() {
1263 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001264 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266}
1267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1269 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270
Michael Wright2e732952014-09-24 13:26:59 -07001271 uint32_t policyFlags = entry->policyFlags &
1272 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 std::shared_ptr<KeyEntry> newEntry =
1275 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1276 entry->source, entry->displayId, policyFlags, entry->action,
1277 entry->flags, entry->keyCode, entry->scanCode,
1278 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 newEntry->syntheticRepeat = true;
1281 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001283 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284}
1285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001286bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001288 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1289 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
1292 // Reset key repeating in case a keyboard device was added or removed or something.
1293 resetKeyRepeatLocked();
1294
1295 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001296 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1297 scoped_unlock unlock(mLock);
1298 mPolicy->notifyConfigurationChanged(eventTime);
1299 };
1300 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 return true;
1302}
1303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1305 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001306 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1307 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1308 entry.deviceId);
1309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
liushenxiang42232912021-05-21 20:24:09 +08001311 // Reset key repeating in case a keyboard device was disabled or enabled.
1312 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1313 resetKeyRepeatLocked();
1314 }
1315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001317 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 synthesizeCancelationEventsForAllConnectionsLocked(options);
1319 return true;
1320}
1321
Vishnu Nairad321cd2020-08-20 16:40:21 -07001322void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001323 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001324 if (mPendingEvent != nullptr) {
1325 // Move the pending event to the front of the queue. This will give the chance
1326 // for the pending event to get dispatched to the newly focused window
1327 mInboundQueue.push_front(mPendingEvent);
1328 mPendingEvent = nullptr;
1329 }
1330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331 std::unique_ptr<FocusEntry> focusEntry =
1332 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1333 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001334
1335 // This event should go to the front of the queue, but behind all other focus events
1336 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001337 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001338 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001339 [](const std::shared_ptr<EventEntry>& event) {
1340 return event->type == EventEntry::Type::FOCUS;
1341 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001342
1343 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001344 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001345}
1346
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001347void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001348 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001349 if (channel == nullptr) {
1350 return; // Window has gone away
1351 }
1352 InputTarget target;
1353 target.inputChannel = channel;
1354 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1355 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001356 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1357 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001358 std::string reason = std::string("reason=").append(entry->reason);
1359 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001360 dispatchEventLocked(currentTime, entry, {target});
1361}
1362
Prabir Pradhan99987712020-11-10 18:43:05 -08001363void InputDispatcher::dispatchPointerCaptureChangedLocked(
1364 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1365 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001366 dropReason = DropReason::NOT_DROPPED;
1367
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001369 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001370
1371 if (entry->pointerCaptureRequest.enable) {
1372 // Enable Pointer Capture.
1373 if (haveWindowWithPointerCapture &&
1374 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001375 // This can happen if pointer capture is disabled and re-enabled before we notify the
1376 // app of the state change, so there is no need to notify the app.
1377 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1378 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001379 }
1380 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001381 // This can happen if a window requests capture and immediately releases capture.
1382 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001383 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001384 return;
1385 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001386 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1387 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1388 return;
1389 }
1390
Vishnu Nairc519ff72021-01-21 08:23:08 -08001391 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1393 mWindowTokenWithPointerCapture = token;
1394 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001395 // Disable Pointer Capture.
1396 // We do not check if the sequence number matches for requests to disable Pointer Capture
1397 // for two reasons:
1398 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1399 // to disable capture with the same sequence number: one generated by
1400 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1401 // Capture being disabled in InputReader.
1402 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1403 // actual Pointer Capture state that affects events being generated by input devices is
1404 // in InputReader.
1405 if (!haveWindowWithPointerCapture) {
1406 // Pointer capture was already forcefully disabled because of focus change.
1407 dropReason = DropReason::NOT_DROPPED;
1408 return;
1409 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001410 token = mWindowTokenWithPointerCapture;
1411 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001412 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001413 setPointerCaptureLocked(false);
1414 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001415 }
1416
1417 auto channel = getInputChannelLocked(token);
1418 if (channel == nullptr) {
1419 // Window has gone away, clean up Pointer Capture state.
1420 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001421 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001422 setPointerCaptureLocked(false);
1423 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001424 return;
1425 }
1426 InputTarget target;
1427 target.inputChannel = channel;
1428 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1429 entry->dispatchInProgress = true;
1430 dispatchEventLocked(currentTime, entry, {target});
1431
1432 dropReason = DropReason::NOT_DROPPED;
1433}
1434
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001435void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1436 const std::shared_ptr<TouchModeEntry>& entry) {
1437 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1438 getWindowHandlesLocked(mFocusedDisplayId);
1439 if (windowHandles.empty()) {
1440 return;
1441 }
1442 const std::vector<InputTarget> inputTargets =
1443 getInputTargetsFromWindowHandlesLocked(windowHandles);
1444 if (inputTargets.empty()) {
1445 return;
1446 }
1447 entry->dispatchInProgress = true;
1448 dispatchEventLocked(currentTime, entry, inputTargets);
1449}
1450
1451std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1452 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1453 std::vector<InputTarget> inputTargets;
1454 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1455 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1456 const sp<IBinder>& token = handle->getToken();
1457 if (token == nullptr) {
1458 continue;
1459 }
1460 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1461 if (channel == nullptr) {
1462 continue; // Window has gone away
1463 }
1464 InputTarget target;
1465 target.inputChannel = channel;
1466 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1467 inputTargets.push_back(target);
1468 }
1469 return inputTargets;
1470}
1471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001472bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475 if (!entry->dispatchInProgress) {
1476 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1477 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1478 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1479 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001480 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 // We have seen two identical key downs in a row which indicates that the device
1482 // driver is automatically generating key repeats itself. We take note of the
1483 // repeat here, but we disable our own next key repeat timer since it is clear that
1484 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001485 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1486 // Make sure we don't get key down from a different device. If a different
1487 // device Id has same key pressed down, the new device Id will replace the
1488 // current one to hold the key repeat with repeat count reset.
1489 // In the future when got a KEY_UP on the device id, drop it and do not
1490 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1492 resetKeyRepeatLocked();
1493 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1494 } else {
1495 // Not a repeat. Save key down state in case we do see a repeat later.
1496 resetKeyRepeatLocked();
1497 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1498 }
1499 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001500 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1501 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001502 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001503 if (DEBUG_INBOUND_EVENT_DETAILS) {
1504 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1505 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001506 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 resetKeyRepeatLocked();
1508 }
1509
1510 if (entry->repeatCount == 1) {
1511 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1512 } else {
1513 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1514 }
1515
1516 entry->dispatchInProgress = true;
1517
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001518 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 }
1520
1521 // Handle case where the policy asked us to try again later last time.
1522 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1523 if (currentTime < entry->interceptKeyWakeupTime) {
1524 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1525 *nextWakeupTime = entry->interceptKeyWakeupTime;
1526 }
1527 return false; // wait until next wakeup
1528 }
1529 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1530 entry->interceptKeyWakeupTime = 0;
1531 }
1532
1533 // Give the policy a chance to intercept the key.
1534 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1535 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001536 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001537 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001538
1539 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1540 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1541 };
1542 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 return false; // wait for the command to run
1544 } else {
1545 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1546 }
1547 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001548 if (*dropReason == DropReason::NOT_DROPPED) {
1549 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551 }
1552
1553 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001554 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1557 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001558 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 return true;
1560 }
1561
1562 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return false;
1568 }
1569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001570 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 return true;
1573 }
1574
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001575 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
1578 // Dispatch the key.
1579 dispatchEventLocked(currentTime, entry, inputTargets);
1580 return true;
1581}
1582
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001584 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1585 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1586 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1587 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1588 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1589 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1590 entry.metaState, entry.repeatCount, entry.downTime);
1591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592}
1593
Prabir Pradhancef936d2021-07-21 16:17:52 +00001594void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1595 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001596 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001597 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1598 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1599 "source=0x%x, sensorType=%s",
1600 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001601 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001602 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001603 auto command = [this, entry]() REQUIRES(mLock) {
1604 scoped_unlock unlock(mLock);
1605
1606 if (entry->accuracyChanged) {
1607 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1608 }
1609 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1610 entry->hwTimestamp, entry->values);
1611 };
1612 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001613}
1614
1615bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001616 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1617 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001618 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001619 }
Chris Yef59a2f42020-10-16 12:55:26 -07001620 { // acquire lock
1621 std::scoped_lock _l(mLock);
1622
1623 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1624 std::shared_ptr<EventEntry> entry = *it;
1625 if (entry->type == EventEntry::Type::SENSOR) {
1626 it = mInboundQueue.erase(it);
1627 releaseInboundEventLocked(entry);
1628 }
1629 }
1630 }
1631 return true;
1632}
1633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001634bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001635 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001636 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001638 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 entry->dispatchInProgress = true;
1640
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001641 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 }
1643
1644 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001645 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001646 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001647 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1648 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return true;
1650 }
1651
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001652 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653
1654 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001655 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656
1657 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 if (isPointerEvent) {
1660 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 } else {
1665 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001669 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 return false;
1671 }
1672
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001673 setInjectionResult(*entry, injectionResult);
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001674 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001675 return true;
1676 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001677 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001678 CancelationOptions::Mode mode(isPointerEvent
1679 ? CancelationOptions::CANCEL_POINTER_EVENTS
1680 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1681 CancelationOptions options(mode, "input event injection failed");
1682 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 return true;
1684 }
1685
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001686 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001687 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688
1689 // Dispatch the motion.
1690 if (conflictingPointerActions) {
1691 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001692 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 synthesizeCancelationEventsForAllConnectionsLocked(options);
1694 }
1695 dispatchEventLocked(currentTime, entry, inputTargets);
1696 return true;
1697}
1698
chaviw98318de2021-05-19 16:45:23 -05001699void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001700 bool isExiting, const int32_t rawX,
1701 const int32_t rawY) {
1702 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001703 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001704 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1705 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001706
1707 enqueueInboundEventLocked(std::move(dragEntry));
1708}
1709
1710void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1711 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1712 if (channel == nullptr) {
1713 return; // Window has gone away
1714 }
1715 InputTarget target;
1716 target.inputChannel = channel;
1717 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1718 entry->dispatchInProgress = true;
1719 dispatchEventLocked(currentTime, entry, {target});
1720}
1721
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001722void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001723 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1724 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1725 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001726 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001727 "metaState=0x%x, buttonState=0x%x,"
1728 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1729 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001730 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1731 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1732 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001734 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1735 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1736 "x=%f, y=%f, pressure=%f, size=%f, "
1737 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1738 "orientation=%f",
1739 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1740 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1741 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1742 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1743 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1744 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1745 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1746 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1747 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1748 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751}
1752
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001753void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1754 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001756 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001757 if (DEBUG_DISPATCH_CYCLE) {
1758 ALOGD("dispatchEventToCurrentInputTargets");
1759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001761 updateInteractionTokensLocked(*eventEntry, inputTargets);
1762
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001765 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001767 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001768 sp<Connection> connection =
1769 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001770 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001771 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001773 if (DEBUG_FOCUS) {
1774 ALOGD("Dropping event delivery to target with channel '%s' because it "
1775 "is no longer registered with the input dispatcher.",
1776 inputTarget.inputChannel->getName().c_str());
1777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 }
1779 }
1780}
1781
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001782void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1783 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1784 // If the policy decides to close the app, we will get a channel removal event via
1785 // unregisterInputChannel, and will clean up the connection that way. We are already not
1786 // sending new pointers to the connection when it blocked, but focused events will continue to
1787 // pile up.
1788 ALOGW("Canceling events for %s because it is unresponsive",
1789 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001790 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001791 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1792 "application not responding");
1793 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795}
1796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001798 if (DEBUG_FOCUS) {
1799 ALOGD("Resetting ANR timeouts.");
1800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801
1802 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001804 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805}
1806
Tiger Huang721e26f2018-07-24 22:26:19 +08001807/**
1808 * Get the display id that the given event should go to. If this event specifies a valid display id,
1809 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1810 * Focused display is the display that the user most recently interacted with.
1811 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001813 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001815 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1817 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001818 break;
1819 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001820 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001821 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1822 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 break;
1824 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001825 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001826 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001827 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001828 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001829 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001830 case EventEntry::Type::SENSOR:
1831 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001832 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001833 return ADISPLAY_ID_NONE;
1834 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001835 }
1836 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1837}
1838
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1840 const char* focusedWindowName) {
1841 if (mAnrTracker.empty()) {
1842 // already processed all events that we waited for
1843 mKeyIsWaitingForEventsTimeout = std::nullopt;
1844 return false;
1845 }
1846
1847 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1848 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001849 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001850 mKeyIsWaitingForEventsTimeout = currentTime +
1851 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1852 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853 return true;
1854 }
1855
1856 // We still have pending events, and already started the timer
1857 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1858 return true; // Still waiting
1859 }
1860
1861 // Waited too long, and some connection still hasn't processed all motions
1862 // Just send the key to the focused window
1863 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1864 focusedWindowName);
1865 mKeyIsWaitingForEventsTimeout = std::nullopt;
1866 return false;
1867}
1868
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001869InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1870 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1871 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001872 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873
Tiger Huang721e26f2018-07-24 22:26:19 +08001874 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001875 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001876 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001877 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1878
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 // If there is no currently focused window and no focused application
1880 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1882 ALOGI("Dropping %s event because there is no focused window or focused application in "
1883 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001884 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001885 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
1887
Vishnu Nair062a8672021-09-03 16:07:44 -07001888 // Drop key events if requested by input feature
1889 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1890 return InputEventInjectionResult::FAILED;
1891 }
1892
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1894 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1895 // start interacting with another application via touch (app switch). This code can be removed
1896 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1897 // an app is expected to have a focused window.
1898 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1899 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1900 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001901 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1902 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1903 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001905 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906 ALOGW("Waiting because no window has focus but %s may eventually add a "
1907 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001908 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001909 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001911 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1912 // Already raised ANR. Drop the event
1913 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001914 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001915 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001916 } else {
1917 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001919 }
1920 }
1921
1922 // we have a valid, non-null focused window
1923 resetNoFocusedWindowTimeoutLocked();
1924
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001925 // Verify targeted injection.
1926 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1927 ALOGW("Dropping injected event: %s", (*err).c_str());
1928 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
1930
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001931 if (focusedWindowHandle->getInfo()->inputConfig.test(
1932 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001934 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001935 }
1936
1937 // If the event is a key event, then we must wait for all previous events to
1938 // complete before delivering it because previous events may have the
1939 // side-effect of transferring focus to a different window and we want to
1940 // ensure that the following keys are sent to the new window.
1941 //
1942 // Suppose the user touches a button in a window then immediately presses "A".
1943 // If the button causes a pop-up window to appear then we want to ensure that
1944 // the "A" key is delivered to the new pop-up window. This is because users
1945 // often anticipate pending UI changes when typing on a keyboard.
1946 // To obtain this behavior, we must serialize key events with respect to all
1947 // prior input events.
1948 if (entry.type == EventEntry::Type::KEY) {
1949 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1950 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001951 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
1954
1955 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001956 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001957 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1958 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959
1960 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001961 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962}
1963
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964/**
1965 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1966 * that are currently unresponsive.
1967 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001968std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1969 const std::vector<Monitor>& monitors) const {
1970 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001971 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001972 [this](const Monitor& monitor) REQUIRES(mLock) {
1973 sp<Connection> connection =
1974 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001975 if (connection == nullptr) {
1976 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001977 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001978 return false;
1979 }
1980 if (!connection->responsive) {
1981 ALOGW("Unresponsive monitor %s will not get the new gesture",
1982 connection->inputChannel->getName().c_str());
1983 return false;
1984 }
1985 return true;
1986 });
1987 return responsiveMonitors;
1988}
1989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001990InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1991 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1992 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001993 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 // For security reasons, we defer updating the touch state until we are sure that
1996 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001997 const int32_t displayId = entry.displayId;
1998 const int32_t action = entry.action;
1999 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
2001 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002002 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002003 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2004 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002006 // Copy current touch state into tempTouchState.
2007 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2008 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002009 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002010 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002011 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2012 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002013 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002014 }
2015
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002016 bool isSplit = tempTouchState.split;
2017 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2018 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2019 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002020
2021 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2022 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2023 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2024 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2025 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002026 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 bool wrongDevice = false;
2028 if (newGesture) {
2029 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002030 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002031 ALOGI("Dropping event because a pointer for a different device is already down "
2032 "in display %" PRId32,
2033 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002034 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 switchedDevice = false;
2037 wrongDevice = true;
2038 goto Failed;
2039 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002040 tempTouchState.reset();
2041 tempTouchState.down = down;
2042 tempTouchState.deviceId = entry.deviceId;
2043 tempTouchState.source = entry.source;
2044 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002046 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002047 ALOGI("Dropping move event because a pointer for a different device is already active "
2048 "in display %" PRId32,
2049 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002050 // TODO: test multiple simultaneous input streams.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002051 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002052 switchedDevice = false;
2053 wrongDevice = true;
2054 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
2056
2057 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2058 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2059
Garfield Tan00f511d2019-06-12 16:55:40 -07002060 int32_t x;
2061 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002062 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002063 // Always dispatch mouse events to cursor position.
2064 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002065 x = int32_t(entry.xCursorPosition);
2066 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002067 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002068 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2069 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002070 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002071 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002072 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002073 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002074 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002075
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002077 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002078 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2079 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002081 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002082 }
2083
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002084 // Verify targeted injection.
2085 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2086 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2087 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2088 newTouchedWindowHandle = nullptr;
2089 goto Failed;
2090 }
2091
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002092 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002093 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002094 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2095 // New window supports splitting, but we should never split mouse events.
2096 isSplit = !isFromMouse;
2097 } else if (isSplit) {
2098 // New window does not support splitting but we have already split events.
2099 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002100 newTouchedWindowHandle = nullptr;
2101 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002102 } else {
2103 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002104 // be delivered to a new window which supports split touch. Pointers from a mouse device
2105 // should never be split.
2106 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 }
2108
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002109 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002110 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002111 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2112 newHoverWindowHandle = nullptr;
2113 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002114 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002115 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002116 }
2117
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002118 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002119 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002120 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002121 // Process the foreground window first so that it is the first to receive the event.
2122 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002123 }
2124
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002125 if (newTouchedWindows.empty()) {
2126 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2127 x, y, displayId);
2128 injectionResult = InputEventInjectionResult::FAILED;
2129 goto Failed;
2130 }
2131
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002132 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2133 const WindowInfo& info = *windowHandle->getInfo();
2134
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002135 // Skip spy window targets that are not valid for targeted injection.
2136 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2137 continue;
2138 }
2139
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002140 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002141 ALOGI("Not sending touch event to %s because it is paused",
2142 windowHandle->getName().c_str());
2143 continue;
2144 }
2145
2146 // Ensure the window has a connection and the connection is responsive
2147 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2148 if (!isResponsive) {
2149 ALOGW("Not sending touch gesture to %s because it is not responsive",
2150 windowHandle->getName().c_str());
2151 continue;
2152 }
2153
2154 // Drop events that can't be trusted due to occlusion
2155 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2156 TouchOcclusionInfo occlusionInfo =
2157 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2158 if (!isTouchTrustedLocked(occlusionInfo)) {
2159 if (DEBUG_TOUCH_OCCLUSION) {
2160 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2161 for (const auto& log : occlusionInfo.debugInfo) {
2162 ALOGD("%s", log.c_str());
2163 }
2164 }
2165 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2166 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2167 ALOGW("Dropping untrusted touch event due to %s/%d",
2168 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2169 continue;
2170 }
2171 }
2172 }
2173
2174 // Drop touch events if requested by input feature
2175 if (shouldDropInput(entry, windowHandle)) {
2176 continue;
2177 }
2178
2179 // Set target flags.
2180 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2181
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002182 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2183 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002184 targetFlags |= InputTarget::FLAG_FOREGROUND;
2185 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186
2187 if (isSplit) {
2188 targetFlags |= InputTarget::FLAG_SPLIT;
2189 }
2190 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2191 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2192 } else if (isWindowObscuredLocked(windowHandle)) {
2193 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2194 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002195
2196 // Update the temporary touch state.
2197 BitSet32 pointerIds;
Arthur Hung02701602022-07-15 09:35:36 +00002198 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002199 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Arthur Hungba703c32022-12-08 07:45:36 +00002200
2201 // If this is the pointer going down and the touched window has a wallpaper
2202 // then also add the touched wallpaper windows so they are locked in for the duration
2203 // of the touch gesture.
2204 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2205 // engine only supports touch events. We would need to add a mechanism similar
2206 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2207 if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2208 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2209 if ((targetFlags & InputTarget::FLAG_FOREGROUND) &&
2210 windowHandle->getInfo()->inputConfig.test(
2211 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2212 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2213 if (wallpaper != nullptr) {
2214 int32_t wallpaperFlags = InputTarget::FLAG_WINDOW_IS_OBSCURED |
2215 InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2216 InputTarget::FLAG_DISPATCH_AS_IS;
2217 if (isSplit) {
2218 wallpaperFlags |= InputTarget::FLAG_SPLIT;
2219 }
2220 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds);
2221 }
2222 }
2223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 } else {
2226 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2227
2228 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002230 if (DEBUG_FOCUS) {
2231 ALOGD("Dropping event because the pointer is not down or we previously "
2232 "dropped the pointer down event in display %" PRId32,
2233 displayId);
2234 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002235 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 goto Failed;
2237 }
2238
arthurhung6d4bed92021-03-17 11:59:33 +08002239 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002240
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002242 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002243 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2245 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
Prabir Pradhand65552b2021-10-07 11:23:50 -07002247 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002248 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002249 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002250 newTouchedWindowHandle =
2251 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002252
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002253 // Verify targeted injection.
2254 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2255 ALOGW("Dropping injected event: %s", (*err).c_str());
2256 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2257 newTouchedWindowHandle = nullptr;
2258 goto Failed;
2259 }
2260
Vishnu Nair062a8672021-09-03 16:07:44 -07002261 // Drop touch events if requested by input feature
2262 if (newTouchedWindowHandle != nullptr &&
2263 shouldDropInput(entry, newTouchedWindowHandle)) {
2264 newTouchedWindowHandle = nullptr;
2265 }
2266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2268 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002269 if (DEBUG_FOCUS) {
2270 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2271 oldTouchedWindowHandle->getName().c_str(),
2272 newTouchedWindowHandle->getName().c_str(), displayId);
2273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002275 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2276 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2277 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
2279 // Make a slippery entrance into the new window.
2280 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002281 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 }
2283
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002284 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2285 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2286 targetFlags |= InputTarget::FLAG_FOREGROUND;
2287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 if (isSplit) {
2289 targetFlags |= InputTarget::FLAG_SPLIT;
2290 }
2291 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2292 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002293 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2294 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296
2297 BitSet32 pointerIds;
Arthur Hung02701602022-07-15 09:35:36 +00002298 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002299 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Arthur Hungba703c32022-12-08 07:45:36 +00002300
2301 // Check if the wallpaper window should deliver the corresponding event.
2302 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
2303 tempTouchState, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305 }
Arthur Hung69d75572022-11-15 03:30:48 +00002306
2307 // Update the pointerIds for non-splittable when it received pointer down.
2308 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2309 // If no split, we suppose all touched windows should receive pointer down.
2310 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2311 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2312 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2313 // Ignore drag window for it should just track one pointer.
2314 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2315 continue;
2316 }
2317 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2318 }
2319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002324 // Let the previous window know that the hover sequence is over, unless we already did
2325 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002326 if (mLastHoverWindowHandle != nullptr &&
2327 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2328 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002329 if (DEBUG_HOVER) {
2330 ALOGD("Sending hover exit event to window %s.",
2331 mLastHoverWindowHandle->getName().c_str());
2332 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002333 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2334 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
2336
Garfield Tandf26e862020-07-01 20:18:19 -07002337 // Let the new window know that the hover sequence is starting, unless we already did it
2338 // when dispatching it as is to newTouchedWindowHandle.
2339 if (newHoverWindowHandle != nullptr &&
2340 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2341 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002342 if (DEBUG_HOVER) {
2343 ALOGD("Sending hover enter event to window %s.",
2344 newHoverWindowHandle->getName().c_str());
2345 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002346 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2347 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2348 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 }
2350 }
2351
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002352 // Ensure that we have at least one foreground window or at least one window that cannot be a
2353 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2354 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2355 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002356 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2357 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002358 return !canReceiveForegroundTouches(
2359 *touchedWindow.windowHandle->getInfo()) ||
2360 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002361 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002362 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2363 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002364 injectionResult = InputEventInjectionResult::FAILED;
2365 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
2367
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002368 // Ensure that all touched windows are valid for injection.
2369 if (entry.injectionState != nullptr) {
2370 std::string errs;
2371 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2372 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2373 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2374 // dispatched to any uid, since the coords will be zeroed out later.
2375 continue;
2376 }
2377 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2378 if (err) errs += "\n - " + *err;
2379 }
2380 if (!errs.empty()) {
2381 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2382 "%d:%s",
2383 *entry.injectionState->targetUid, errs.c_str());
2384 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2385 goto Failed;
2386 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002387 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002388
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 // Check whether windows listening for outside touches are owned by the same UID. If it is
2390 // set the policy flag that we will not reveal coordinate information to this window.
2391 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002392 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002393 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002394 if (foregroundWindowHandle) {
2395 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002396 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002397 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002398 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2399 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2400 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002401 InputTarget::FLAG_ZERO_COORDS,
2402 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405 }
2406 }
2407 }
2408
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002410 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002412 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
2416
2417 // Drop the outside or hover touch windows since we will not care about them
2418 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002419 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
2421Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002423 if (!wrongDevice) {
2424 if (switchedDevice) {
2425 if (DEBUG_FOCUS) {
2426 ALOGD("Conflicting pointer actions: Switched to a different device.");
2427 }
2428 *outConflictingPointerActions = true;
2429 }
2430
2431 if (isHoverAction) {
2432 // Started hovering, therefore no longer down.
2433 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002434 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002435 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2436 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 *outConflictingPointerActions = true;
2439 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002440 tempTouchState.reset();
2441 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2442 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2443 tempTouchState.deviceId = entry.deviceId;
2444 tempTouchState.source = entry.source;
2445 tempTouchState.displayId = displayId;
2446 }
2447 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2448 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2449 // All pointers up or canceled.
2450 tempTouchState.reset();
2451 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2452 // First pointer went down.
2453 if (oldState && oldState->down) {
2454 if (DEBUG_FOCUS) {
2455 ALOGD("Conflicting pointer actions: Down received while already down.");
2456 }
2457 *outConflictingPointerActions = true;
2458 }
2459 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2460 // One pointer went up.
Arthur Hung02701602022-07-15 09:35:36 +00002461 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2462 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463
Arthur Hung02701602022-07-15 09:35:36 +00002464 for (size_t i = 0; i < tempTouchState.windows.size();) {
2465 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2466 touchedWindow.pointerIds.clearBit(pointerId);
2467 if (touchedWindow.pointerIds.isEmpty()) {
2468 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2469 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
Arthur Hung02701602022-07-15 09:35:36 +00002471 i += 1;
2472 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002473 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002474
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002475 // Save changes unless the action was scroll in which case the temporary touch
2476 // state was only valid for this one action.
2477 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2478 if (tempTouchState.displayId >= 0) {
2479 mTouchStatesByDisplay[displayId] = tempTouchState;
2480 } else {
2481 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002485 // Update hover state.
2486 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 }
2488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 return injectionResult;
2490}
2491
arthurhung6d4bed92021-03-17 11:59:33 +08002492void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002493 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2494 // have an explicit reason to support it.
2495 constexpr bool isStylus = false;
2496
chaviw98318de2021-05-19 16:45:23 -05002497 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002498 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002499 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002500 if (dropWindow) {
2501 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002502 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002503 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002504 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002505 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002506 }
2507 mDragState.reset();
2508}
2509
2510void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002511 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002512 return;
2513 }
2514
arthurhung6d4bed92021-03-17 11:59:33 +08002515 if (!mDragState->isStartDrag) {
2516 mDragState->isStartDrag = true;
2517 mDragState->isStylusButtonDownAtStart =
2518 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2519 }
2520
Arthur Hung54745652022-04-20 07:17:41 +00002521 // Find the pointer index by id.
2522 int32_t pointerIndex = 0;
2523 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2524 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2525 if (pointerProperties.id == mDragState->pointerId) {
2526 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002527 }
Arthur Hung54745652022-04-20 07:17:41 +00002528 }
arthurhung6d4bed92021-03-17 11:59:33 +08002529
Arthur Hung54745652022-04-20 07:17:41 +00002530 if (uint32_t(pointerIndex) == entry.pointerCount) {
2531 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002532 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002533 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002534 return;
2535 }
2536
2537 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2538 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2539 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2540
2541 switch (maskedAction) {
2542 case AMOTION_EVENT_ACTION_MOVE: {
2543 // Handle the special case : stylus button no longer pressed.
2544 bool isStylusButtonDown =
2545 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2546 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2547 finishDragAndDrop(entry.displayId, x, y);
2548 return;
2549 }
2550
2551 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2552 // until we have an explicit reason to support it.
2553 constexpr bool isStylus = false;
2554
2555 const sp<WindowInfoHandle> hoverWindowHandle =
2556 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2557 isStylus, false /*addOutsideTargets*/,
2558 true /*ignoreDragWindow*/);
2559 // enqueue drag exit if needed.
2560 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2561 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2562 if (mDragState->dragHoverWindowHandle != nullptr) {
2563 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2564 y);
2565 }
2566 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2567 }
2568 // enqueue drag location if needed.
2569 if (hoverWindowHandle != nullptr) {
2570 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2571 }
2572 break;
2573 }
2574
2575 case AMOTION_EVENT_ACTION_POINTER_UP:
2576 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2577 break;
2578 }
2579 // The drag pointer is up.
2580 [[fallthrough]];
2581 case AMOTION_EVENT_ACTION_UP:
2582 finishDragAndDrop(entry.displayId, x, y);
2583 break;
2584 case AMOTION_EVENT_ACTION_CANCEL: {
2585 ALOGD("Receiving cancel when drag and drop.");
2586 sendDropWindowCommandLocked(nullptr, 0, 0);
2587 mDragState.reset();
2588 break;
2589 }
arthurhungb89ccb02020-12-30 16:19:01 +08002590 }
2591}
2592
chaviw98318de2021-05-19 16:45:23 -05002593void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 int32_t targetFlags, BitSet32 pointerIds,
2595 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002596 std::vector<InputTarget>::iterator it =
2597 std::find_if(inputTargets.begin(), inputTargets.end(),
2598 [&windowHandle](const InputTarget& inputTarget) {
2599 return inputTarget.inputChannel->getConnectionToken() ==
2600 windowHandle->getToken();
2601 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002602
chaviw98318de2021-05-19 16:45:23 -05002603 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002604
2605 if (it == inputTargets.end()) {
2606 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002607 std::shared_ptr<InputChannel> inputChannel =
2608 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002609 if (inputChannel == nullptr) {
2610 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2611 return;
2612 }
2613 inputTarget.inputChannel = inputChannel;
2614 inputTarget.flags = targetFlags;
2615 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002616 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2617 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002618 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002619 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002620 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002621 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002622 inputTargets.push_back(inputTarget);
2623 it = inputTargets.end() - 1;
2624 }
2625
2626 ALOG_ASSERT(it->flags == targetFlags);
2627 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2628
chaviw1ff3d1e2020-07-01 15:53:47 -07002629 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630}
2631
Michael Wright3dd60e22019-03-27 22:06:44 +00002632void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002633 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002634 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2635 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002636
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002637 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2638 InputTarget target;
2639 target.inputChannel = monitor.inputChannel;
2640 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2641 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2642 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002643 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002644 target.setDefaultPointerTransform(target.displayTransform);
2645 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 }
2647}
2648
Robert Carrc9bf1d32020-04-13 17:21:08 -07002649/**
2650 * Indicate whether one window handle should be considered as obscuring
2651 * another window handle. We only check a few preconditions. Actually
2652 * checking the bounds is left to the caller.
2653 */
chaviw98318de2021-05-19 16:45:23 -05002654static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2655 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002656 // Compare by token so cloned layers aren't counted
2657 if (haveSameToken(windowHandle, otherHandle)) {
2658 return false;
2659 }
2660 auto info = windowHandle->getInfo();
2661 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002662 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002663 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002664 } else if (otherInfo->alpha == 0 &&
2665 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002666 // Those act as if they were invisible, so we don't need to flag them.
2667 // We do want to potentially flag touchable windows even if they have 0
2668 // opacity, since they can consume touches and alter the effects of the
2669 // user interaction (eg. apps that rely on
2670 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2671 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2672 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002673 } else if (info->ownerUid == otherInfo->ownerUid) {
2674 // If ownerUid is the same we don't generate occlusion events as there
2675 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002676 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002677 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002678 return false;
2679 } else if (otherInfo->displayId != info->displayId) {
2680 return false;
2681 }
2682 return true;
2683}
2684
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002685/**
2686 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2687 * untrusted, one should check:
2688 *
2689 * 1. If result.hasBlockingOcclusion is true.
2690 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2691 * BLOCK_UNTRUSTED.
2692 *
2693 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2694 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2695 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2696 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2697 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2698 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2699 *
2700 * If neither of those is true, then it means the touch can be allowed.
2701 */
2702InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002703 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2704 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002705 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002706 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002707 TouchOcclusionInfo info;
2708 info.hasBlockingOcclusion = false;
2709 info.obscuringOpacity = 0;
2710 info.obscuringUid = -1;
2711 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002712 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002713 if (windowHandle == otherHandle) {
2714 break; // All future windows are below us. Exit early.
2715 }
chaviw98318de2021-05-19 16:45:23 -05002716 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002717 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2718 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002719 if (DEBUG_TOUCH_OCCLUSION) {
2720 info.debugInfo.push_back(
2721 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2722 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002723 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2724 // we perform the checks below to see if the touch can be propagated or not based on the
2725 // window's touch occlusion mode
2726 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2727 info.hasBlockingOcclusion = true;
2728 info.obscuringUid = otherInfo->ownerUid;
2729 info.obscuringPackage = otherInfo->packageName;
2730 break;
2731 }
2732 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2733 uint32_t uid = otherInfo->ownerUid;
2734 float opacity =
2735 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2736 // Given windows A and B:
2737 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2738 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2739 opacityByUid[uid] = opacity;
2740 if (opacity > info.obscuringOpacity) {
2741 info.obscuringOpacity = opacity;
2742 info.obscuringUid = uid;
2743 info.obscuringPackage = otherInfo->packageName;
2744 }
2745 }
2746 }
2747 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002748 if (DEBUG_TOUCH_OCCLUSION) {
2749 info.debugInfo.push_back(
2750 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2751 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002752 return info;
2753}
2754
chaviw98318de2021-05-19 16:45:23 -05002755std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002756 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002757 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2758 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2759 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2760 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002761 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2762 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2763 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2764 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2765 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002766 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002767 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002768}
2769
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002770bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2771 if (occlusionInfo.hasBlockingOcclusion) {
2772 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2773 occlusionInfo.obscuringUid);
2774 return false;
2775 }
2776 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2777 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2778 "%.2f, maximum allowed = %.2f)",
2779 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2780 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2781 return false;
2782 }
2783 return true;
2784}
2785
chaviw98318de2021-05-19 16:45:23 -05002786bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002789 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2790 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791 if (windowHandle == otherHandle) {
2792 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 }
chaviw98318de2021-05-19 16:45:23 -05002794 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002795 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002796 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 return true;
2798 }
2799 }
2800 return false;
2801}
2802
chaviw98318de2021-05-19 16:45:23 -05002803bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002804 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002805 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2806 const WindowInfo* windowInfo = windowHandle->getInfo();
2807 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002808 if (windowHandle == otherHandle) {
2809 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002810 }
chaviw98318de2021-05-19 16:45:23 -05002811 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002812 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002813 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002814 return true;
2815 }
2816 }
2817 return false;
2818}
2819
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002820std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002821 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002822 if (applicationHandle != nullptr) {
2823 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002824 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 } else {
2826 return applicationHandle->getName();
2827 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002828 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002829 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002831 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 }
2833}
2834
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002835void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002836 if (!isUserActivityEvent(eventEntry)) {
2837 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002838 return;
2839 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002840 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002841 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002842 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002843 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002844 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002845 if (DEBUG_DISPATCH_CYCLE) {
2846 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 return;
2849 }
2850 }
2851
2852 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002853 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002854 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002855 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2856 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 return;
2858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002860 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 eventType = USER_ACTIVITY_EVENT_TOUCH;
2862 }
2863 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002865 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002866 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2867 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002868 return;
2869 }
2870 eventType = USER_ACTIVITY_EVENT_BUTTON;
2871 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002873 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002874 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002875 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002876 break;
2877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 }
2879
Prabir Pradhancef936d2021-07-21 16:17:52 +00002880 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2881 REQUIRES(mLock) {
2882 scoped_unlock unlock(mLock);
2883 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2884 };
2885 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886}
2887
2888void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002890 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002891 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002892 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002894 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002895 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002896 ATRACE_NAME(message.c_str());
2897 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002898 if (DEBUG_DISPATCH_CYCLE) {
2899 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2900 "globalScaleFactor=%f, pointerIds=0x%x %s",
2901 connection->getInputChannelName().c_str(), inputTarget.flags,
2902 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2903 inputTarget.getPointerInfoString().c_str());
2904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905
2906 // Skip this event if the connection status is not normal.
2907 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002908 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002909 if (DEBUG_DISPATCH_CYCLE) {
2910 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002911 connection->getInputChannelName().c_str(),
2912 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 return;
2915 }
2916
2917 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002918 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2919 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2920 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002921 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002924 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002925 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002926 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 if (!splitMotionEntry) {
2928 return; // split event was dropped
2929 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002930 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2931 std::string reason = std::string("reason=pointer cancel on split window");
2932 android_log_event_list(LOGTAG_INPUT_CANCEL)
2933 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2934 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002935 if (DEBUG_FOCUS) {
2936 ALOGD("channel '%s' ~ Split motion event.",
2937 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002938 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002939 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002940 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2941 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 return;
2943 }
2944 }
2945
2946 // Not splitting. Enqueue dispatch entries for the event as is.
2947 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2948}
2949
2950void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002953 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002954 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002956 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002957 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002958 ATRACE_NAME(message.c_str());
2959 }
2960
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002961 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962
2963 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002968 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002970 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002972 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002974 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002975 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976
2977 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002978 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 startDispatchCycleLocked(currentTime, connection);
2980 }
2981}
2982
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002985 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002987 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002988 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2989 connection->getInputChannelName().c_str(),
2990 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002991 ATRACE_NAME(message.c_str());
2992 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002993 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 if (!(inputTargetFlags & dispatchMode)) {
2995 return;
2996 }
2997 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2998
2999 // This is a new event.
3000 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003001 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003002 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003004 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3005 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003008 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003009 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003010 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003011 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 dispatchEntry->resolvedAction = keyEntry.action;
3013 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3016 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003017 if (DEBUG_DISPATCH_CYCLE) {
3018 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3019 "event",
3020 connection->getInputChannelName().c_str());
3021 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003022 return; // skip the inconsistent event
3023 }
3024 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003027 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003028 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003029 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3030 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3031 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3032 static_cast<int32_t>(IdGenerator::Source::OTHER);
3033 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3036 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3038 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3039 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3040 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3041 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3042 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3043 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3044 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003045 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003046 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 }
3048 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003049 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3050 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003051 if (DEBUG_DISPATCH_CYCLE) {
3052 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3053 "enter event",
3054 connection->getInputChannelName().c_str());
3055 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003056 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3057 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003061 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3063 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3064 }
3065 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3066 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3070 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003071 if (DEBUG_DISPATCH_CYCLE) {
3072 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3073 "event",
3074 connection->getInputChannelName().c_str());
3075 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 return; // skip the inconsistent event
3077 }
3078
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003079 dispatchEntry->resolvedEventId =
3080 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3081 ? mIdGenerator.nextId()
3082 : motionEntry.id;
3083 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3084 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3085 ") to MotionEvent(id=0x%" PRIx32 ").",
3086 motionEntry.id, dispatchEntry->resolvedEventId);
3087 ATRACE_NAME(message.c_str());
3088 }
3089
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003090 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3091 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3092 // Skip reporting pointer down outside focus to the policy.
3093 break;
3094 }
3095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003096 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003097 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098
3099 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003101 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003102 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003103 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3104 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003105 break;
3106 }
Chris Yef59a2f42020-10-16 12:55:26 -07003107 case EventEntry::Type::SENSOR: {
3108 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3109 break;
3110 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003111 case EventEntry::Type::CONFIGURATION_CHANGED:
3112 case EventEntry::Type::DEVICE_RESET: {
3113 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003114 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003115 break;
3116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118
3119 // Remember that we are waiting for this dispatch to complete.
3120 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003121 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
3123
3124 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003125 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003126 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003127}
3128
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003129/**
3130 * This function is purely for debugging. It helps us understand where the user interaction
3131 * was taking place. For example, if user is touching launcher, we will see a log that user
3132 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3133 * We will see both launcher and wallpaper in that list.
3134 * Once the interaction with a particular set of connections starts, no new logs will be printed
3135 * until the set of interacted connections changes.
3136 *
3137 * The following items are skipped, to reduce the logspam:
3138 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3139 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3140 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3141 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3142 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003143 */
3144void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3145 const std::vector<InputTarget>& targets) {
3146 // Skip ACTION_UP events, and all events other than keys and motions
3147 if (entry.type == EventEntry::Type::KEY) {
3148 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3149 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3150 return;
3151 }
3152 } else if (entry.type == EventEntry::Type::MOTION) {
3153 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3154 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3155 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3156 return;
3157 }
3158 } else {
3159 return; // Not a key or a motion
3160 }
3161
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003162 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003163 std::vector<sp<Connection>> newConnections;
3164 for (const InputTarget& target : targets) {
3165 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3166 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3167 continue; // Skip windows that receive ACTION_OUTSIDE
3168 }
3169
3170 sp<IBinder> token = target.inputChannel->getConnectionToken();
3171 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003172 if (connection == nullptr) {
3173 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003174 }
3175 newConnectionTokens.insert(std::move(token));
3176 newConnections.emplace_back(connection);
3177 }
3178 if (newConnectionTokens == mInteractionConnectionTokens) {
3179 return; // no change
3180 }
3181 mInteractionConnectionTokens = newConnectionTokens;
3182
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003183 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003184 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003185 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003186 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003187 std::string message = "Interaction with: " + targetList;
3188 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003189 message += "<none>";
3190 }
3191 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3192}
3193
chaviwfd6d3512019-03-25 13:23:49 -07003194void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003195 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003196 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003197 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3198 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003199 return;
3200 }
3201
Vishnu Nairc519ff72021-01-21 08:23:08 -08003202 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003203 if (focusedToken == token) {
3204 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003205 return;
3206 }
3207
Prabir Pradhancef936d2021-07-21 16:17:52 +00003208 auto command = [this, token]() REQUIRES(mLock) {
3209 scoped_unlock unlock(mLock);
3210 mPolicy->onPointerDownOutsideFocus(token);
3211 };
3212 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213}
3214
3215void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003217 if (ATRACE_ENABLED()) {
3218 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003220 ATRACE_NAME(message.c_str());
3221 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003222 if (DEBUG_DISPATCH_CYCLE) {
3223 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003226 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003227 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003229 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003230 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231
3232 // Publish the event.
3233 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3235 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003236 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3238 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 status = connection->inputPublisher
3242 .publishKeyEvent(dispatchEntry->seq,
3243 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3244 keyEntry.source, keyEntry.displayId,
3245 std::move(hmac), dispatchEntry->resolvedAction,
3246 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3247 keyEntry.scanCode, keyEntry.metaState,
3248 keyEntry.repeatCount, keyEntry.downTime,
3249 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
3252
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003253 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003254 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258
chaviw82357092020-01-28 13:13:06 -08003259 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3262 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003263 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003264 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3265 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003266 // Don't apply window scale here since we don't want scale to affect raw
3267 // coordinates. The scale will be sent back to the client and applied
3268 // later when requesting relative coordinates.
3269 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3270 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 }
3272 usingCoords = scaledCoords;
3273 }
3274 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003275 // We don't want the dispatch target to know.
3276 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003277 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003278 scaledCoords[i].clear();
3279 }
3280 usingCoords = scaledCoords;
3281 }
3282 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003284 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003285
3286 // Publish the motion event.
3287 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003288 .publishMotionEvent(dispatchEntry->seq,
3289 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 motionEntry.deviceId, motionEntry.source,
3291 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003292 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 motionEntry.edgeFlags, motionEntry.metaState,
3296 motionEntry.buttonState,
3297 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003298 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 motionEntry.xPrecision, motionEntry.yPrecision,
3300 motionEntry.xCursorPosition,
3301 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003302 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003303 motionEntry.downTime, motionEntry.eventTime,
3304 motionEntry.pointerCount,
3305 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 break;
3307 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003308
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003309 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003310 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003311 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003313 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003314 break;
3315 }
3316
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003317 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3318 const TouchModeEntry& touchModeEntry =
3319 static_cast<const TouchModeEntry&>(eventEntry);
3320 status = connection->inputPublisher
3321 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3322 touchModeEntry.inTouchMode);
3323
3324 break;
3325 }
3326
Prabir Pradhan99987712020-11-10 18:43:05 -08003327 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3328 const auto& captureEntry =
3329 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3330 status = connection->inputPublisher
3331 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003332 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003333 break;
3334 }
3335
arthurhungb89ccb02020-12-30 16:19:01 +08003336 case EventEntry::Type::DRAG: {
3337 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3338 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3339 dragEntry.id, dragEntry.x,
3340 dragEntry.y,
3341 dragEntry.isExiting);
3342 break;
3343 }
3344
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003345 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003346 case EventEntry::Type::DEVICE_RESET:
3347 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003348 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003349 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
3353
3354 // Check the result.
3355 if (status) {
3356 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003357 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 "This is unexpected because the wait queue is empty, so the pipe "
3360 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003361 "event to it, status=%s(%d)",
3362 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3363 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3365 } else {
3366 // Pipe is full and we are waiting for the app to finish process some events
3367 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003368 if (DEBUG_DISPATCH_CYCLE) {
3369 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3370 "waiting for the application to catch up",
3371 connection->getInputChannelName().c_str());
3372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 }
3374 } else {
3375 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003376 "status=%s(%d)",
3377 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3378 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3380 }
3381 return;
3382 }
3383
3384 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003385 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3386 connection->outboundQueue.end(),
3387 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003388 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003389 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003390 if (connection->responsive) {
3391 mAnrTracker.insert(dispatchEntry->timeoutTime,
3392 connection->inputChannel->getConnectionToken());
3393 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003394 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 }
3396}
3397
chaviw09c8d2d2020-08-24 15:48:26 -07003398std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3399 size_t size;
3400 switch (event.type) {
3401 case VerifiedInputEvent::Type::KEY: {
3402 size = sizeof(VerifiedKeyEvent);
3403 break;
3404 }
3405 case VerifiedInputEvent::Type::MOTION: {
3406 size = sizeof(VerifiedMotionEvent);
3407 break;
3408 }
3409 }
3410 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3411 return mHmacKeyManager.sign(start, size);
3412}
3413
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003414const std::array<uint8_t, 32> InputDispatcher::getSignature(
3415 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003416 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3417 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003418 // Only sign events up and down events as the purely move events
3419 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003420 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003421 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003422
3423 VerifiedMotionEvent verifiedEvent =
3424 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3425 verifiedEvent.actionMasked = actionMasked;
3426 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3427 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003428}
3429
3430const std::array<uint8_t, 32> InputDispatcher::getSignature(
3431 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3432 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3433 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3434 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003435 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003436}
3437
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003440 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003441 if (DEBUG_DISPATCH_CYCLE) {
3442 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3443 connection->getInputChannelName().c_str(), seq, toString(handled));
3444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003446 if (connection->status == Connection::Status::BROKEN ||
3447 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 return;
3449 }
3450
3451 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003452 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3453 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3454 };
3455 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456}
3457
3458void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 const sp<Connection>& connection,
3460 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003461 if (DEBUG_DISPATCH_CYCLE) {
3462 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3463 connection->getInputChannelName().c_str(), toString(notify));
3464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
3466 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003467 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003468 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003469 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003470 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
3472 // The connection appears to be unrecoverably broken.
3473 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003474 if (connection->status == Connection::Status::NORMAL) {
3475 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
3477 if (notify) {
3478 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003479 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3480 connection->getInputChannelName().c_str());
3481
3482 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003483 scoped_unlock unlock(mLock);
3484 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3485 };
3486 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
3488 }
3489}
3490
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003491void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3492 while (!queue.empty()) {
3493 DispatchEntry* dispatchEntry = queue.front();
3494 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003495 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 }
3497}
3498
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003499void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
3503 delete dispatchEntry;
3504}
3505
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003506int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3507 std::scoped_lock _l(mLock);
3508 sp<Connection> connection = getConnectionLocked(connectionToken);
3509 if (connection == nullptr) {
3510 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3511 connectionToken.get(), events);
3512 return 0; // remove the callback
3513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003515 bool notify;
3516 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3517 if (!(events & ALOOPER_EVENT_INPUT)) {
3518 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3519 "events=0x%x",
3520 connection->getInputChannelName().c_str(), events);
3521 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003524 nsecs_t currentTime = now();
3525 bool gotOne = false;
3526 status_t status = OK;
3527 for (;;) {
3528 Result<InputPublisher::ConsumerResponse> result =
3529 connection->inputPublisher.receiveConsumerResponse();
3530 if (!result.ok()) {
3531 status = result.error().code();
3532 break;
3533 }
3534
3535 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3536 const InputPublisher::Finished& finish =
3537 std::get<InputPublisher::Finished>(*result);
3538 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3539 finish.consumeTime);
3540 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003541 if (shouldReportMetricsForConnection(*connection)) {
3542 const InputPublisher::Timeline& timeline =
3543 std::get<InputPublisher::Timeline>(*result);
3544 mLatencyTracker
3545 .trackGraphicsLatency(timeline.inputEventId,
3546 connection->inputChannel->getConnectionToken(),
3547 std::move(timeline.graphicsTimeline));
3548 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003549 }
3550 gotOne = true;
3551 }
3552 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003553 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003554 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 return 1;
3556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
3558
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003559 notify = status != DEAD_OBJECT || !connection->monitor;
3560 if (notify) {
3561 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3562 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3563 status);
3564 }
3565 } else {
3566 // Monitor channels are never explicitly unregistered.
3567 // We do it automatically when the remote endpoint is closed so don't warn about them.
3568 const bool stillHaveWindowHandle =
3569 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3570 notify = !connection->monitor && stillHaveWindowHandle;
3571 if (notify) {
3572 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3573 connection->getInputChannelName().c_str(), events);
3574 }
3575 }
3576
3577 // Remove the channel.
3578 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3579 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580}
3581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003584 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003585 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 }
3587}
3588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003590 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003591 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003592 for (const Monitor& monitor : monitors) {
3593 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003594 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003595 }
3596}
3597
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003599 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003600 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003601 if (connection == nullptr) {
3602 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003604
3605 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606}
3607
3608void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3609 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003610 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 return;
3612 }
3613
3614 nsecs_t currentTime = now();
3615
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003616 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003617 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003619 if (cancelationEvents.empty()) {
3620 return;
3621 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003622 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3623 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3624 "with reality: %s, mode=%d.",
3625 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3626 options.mode);
3627 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003628
Arthur Hungb3307ee2021-10-14 10:57:37 +00003629 std::string reason = std::string("reason=").append(options.reason);
3630 android_log_event_list(LOGTAG_INPUT_CANCEL)
3631 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3632
Svet Ganov5d3bc372020-01-26 23:11:07 -08003633 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003634 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003635 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3636 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003637 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003638 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003639 target.globalScaleFactor = windowInfo->globalScaleFactor;
3640 }
3641 target.inputChannel = connection->inputChannel;
3642 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3643
hongzuo liu474c1672022-09-06 02:51:35 +00003644 const bool wasEmpty = connection->outboundQueue.empty();
3645
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003646 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003647 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003648 switch (cancelationEventEntry->type) {
3649 case EventEntry::Type::KEY: {
3650 logOutboundKeyDetails("cancel - ",
3651 static_cast<const KeyEntry&>(*cancelationEventEntry));
3652 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003654 case EventEntry::Type::MOTION: {
3655 logOutboundMotionDetails("cancel - ",
3656 static_cast<const MotionEntry&>(*cancelationEventEntry));
3657 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003659 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003660 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003661 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3662 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003663 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003664 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003665 break;
3666 }
3667 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003668 case EventEntry::Type::DEVICE_RESET:
3669 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003670 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003671 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003672 break;
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3677 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003679
hongzuo liu474c1672022-09-06 02:51:35 +00003680 // If the outbound queue was previously empty, start the dispatch cycle going.
3681 if (wasEmpty && !connection->outboundQueue.empty()) {
3682 startDispatchCycleLocked(currentTime, connection);
3683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684}
3685
Svet Ganov5d3bc372020-01-26 23:11:07 -08003686void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungba703c32022-12-08 07:45:36 +00003687 const sp<Connection>& connection, int32_t targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003688 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003689 return;
3690 }
3691
3692 nsecs_t currentTime = now();
3693
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003695 connection->inputState.synthesizePointerDownEvents(currentTime);
3696
3697 if (downEvents.empty()) {
3698 return;
3699 }
3700
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003701 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003702 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3703 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003704 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003705
3706 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003707 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003708 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3709 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003710 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003711 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712 target.globalScaleFactor = windowInfo->globalScaleFactor;
3713 }
3714 target.inputChannel = connection->inputChannel;
Arthur Hungba703c32022-12-08 07:45:36 +00003715 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716
hongzuo liu474c1672022-09-06 02:51:35 +00003717 const bool wasEmpty = connection->outboundQueue.empty();
3718
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003719 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720 switch (downEventEntry->type) {
3721 case EventEntry::Type::MOTION: {
3722 logOutboundMotionDetails("down - ",
3723 static_cast<const MotionEntry&>(*downEventEntry));
3724 break;
3725 }
3726
3727 case EventEntry::Type::KEY:
3728 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003729 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003730 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003731 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003732 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003733 case EventEntry::Type::SENSOR:
3734 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003735 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003736 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003737 break;
3738 }
3739 }
3740
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003741 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3742 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 }
hongzuo liu474c1672022-09-06 02:51:35 +00003744 // If the outbound queue was previously empty, start the dispatch cycle going.
3745 if (wasEmpty && !connection->outboundQueue.empty()) {
3746 startDispatchCycleLocked(currentTime, connection);
3747 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003748}
3749
Arthur Hungba703c32022-12-08 07:45:36 +00003750void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3751 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3752 if (windowHandle != nullptr) {
3753 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3754 if (wallpaperConnection != nullptr) {
3755 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3756 }
3757 }
3758}
3759
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003760std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3761 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 ALOG_ASSERT(pointerIds.value != 0);
3763
3764 uint32_t splitPointerIndexMap[MAX_POINTERS];
3765 PointerProperties splitPointerProperties[MAX_POINTERS];
3766 PointerCoords splitPointerCoords[MAX_POINTERS];
3767
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003768 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 uint32_t splitPointerCount = 0;
3770
3771 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003772 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003774 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 uint32_t pointerId = uint32_t(pointerProperties.id);
3776 if (pointerIds.hasBit(pointerId)) {
3777 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3778 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3779 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003780 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 splitPointerCount += 1;
3782 }
3783 }
3784
3785 if (splitPointerCount != pointerIds.count()) {
3786 // This is bad. We are missing some of the pointers that we expected to deliver.
3787 // Most likely this indicates that we received an ACTION_MOVE events that has
3788 // different pointer ids than we expected based on the previous ACTION_DOWN
3789 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3790 // in this way.
3791 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 "we expected there to be %d pointers. This probably means we received "
3793 "a broken sequence of pointer ids from the input device.",
3794 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003795 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003798 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3801 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3803 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003804 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 uint32_t pointerId = uint32_t(pointerProperties.id);
3806 if (pointerIds.hasBit(pointerId)) {
3807 if (pointerIds.count() == 1) {
3808 // The first/last pointer went down/up.
3809 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003811 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3812 ? AMOTION_EVENT_ACTION_CANCEL
3813 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 } else {
3815 // A secondary pointer went down/up.
3816 uint32_t splitPointerIndex = 0;
3817 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3818 splitPointerIndex += 1;
3819 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003820 action = maskedAction |
3821 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
3823 } else {
3824 // An unrelated pointer changed.
3825 action = AMOTION_EVENT_ACTION_MOVE;
3826 }
3827 }
3828
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003829 int32_t newId = mIdGenerator.nextId();
3830 if (ATRACE_ENABLED()) {
3831 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3832 ") to MotionEvent(id=0x%" PRIx32 ").",
3833 originalMotionEntry.id, newId);
3834 ATRACE_NAME(message.c_str());
3835 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003836 std::unique_ptr<MotionEntry> splitMotionEntry =
3837 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3838 originalMotionEntry.deviceId, originalMotionEntry.source,
3839 originalMotionEntry.displayId,
3840 originalMotionEntry.policyFlags, action,
3841 originalMotionEntry.actionButton,
3842 originalMotionEntry.flags, originalMotionEntry.metaState,
3843 originalMotionEntry.buttonState,
3844 originalMotionEntry.classification,
3845 originalMotionEntry.edgeFlags,
3846 originalMotionEntry.xPrecision,
3847 originalMotionEntry.yPrecision,
3848 originalMotionEntry.xCursorPosition,
3849 originalMotionEntry.yCursorPosition,
3850 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003851 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003853 if (originalMotionEntry.injectionState) {
3854 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 splitMotionEntry->injectionState->refCount += 1;
3856 }
3857
3858 return splitMotionEntry;
3859}
3860
3861void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003862 if (DEBUG_INBOUND_EVENT_DETAILS) {
3863 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
Antonio Kantekf16f2832021-09-28 04:39:20 +00003866 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003868 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003870 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3871 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3872 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 } // release lock
3874
3875 if (needWake) {
3876 mLooper->wake();
3877 }
3878}
3879
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003880/**
3881 * If one of the meta shortcuts is detected, process them here:
3882 * Meta + Backspace -> generate BACK
3883 * Meta + Enter -> generate HOME
3884 * This will potentially overwrite keyCode and metaState.
3885 */
3886void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003887 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003888 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3889 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3890 if (keyCode == AKEYCODE_DEL) {
3891 newKeyCode = AKEYCODE_BACK;
3892 } else if (keyCode == AKEYCODE_ENTER) {
3893 newKeyCode = AKEYCODE_HOME;
3894 }
3895 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003896 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003897 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003898 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003899 keyCode = newKeyCode;
3900 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3901 }
3902 } else if (action == AKEY_EVENT_ACTION_UP) {
3903 // In order to maintain a consistent stream of up and down events, check to see if the key
3904 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3905 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003906 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003907 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003908 auto replacementIt = mReplacedKeys.find(replacement);
3909 if (replacementIt != mReplacedKeys.end()) {
3910 keyCode = replacementIt->second;
3911 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003912 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3913 }
3914 }
3915}
3916
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003918 if (DEBUG_INBOUND_EVENT_DETAILS) {
3919 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3920 "policyFlags=0x%x, action=0x%x, "
3921 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3922 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3923 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3924 args->downTime);
3925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 if (!validateKeyEvent(args->action)) {
3927 return;
3928 }
3929
3930 uint32_t policyFlags = args->policyFlags;
3931 int32_t flags = args->flags;
3932 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003933 // InputDispatcher tracks and generates key repeats on behalf of
3934 // whatever notifies it, so repeatCount should always be set to 0
3935 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3937 policyFlags |= POLICY_FLAG_VIRTUAL;
3938 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 if (policyFlags & POLICY_FLAG_FUNCTION) {
3941 metaState |= AMETA_FUNCTION_ON;
3942 }
3943
3944 policyFlags |= POLICY_FLAG_TRUSTED;
3945
Michael Wright78f24442014-08-06 15:55:28 -07003946 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003947 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003948
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003950 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003951 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3952 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
Michael Wright2b3c3302018-03-02 17:19:13 +00003954 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003956 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3957 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960
Antonio Kantekf16f2832021-09-28 04:39:20 +00003961 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 { // acquire lock
3963 mLock.lock();
3964
3965 if (shouldSendKeyToInputFilterLocked(args)) {
3966 mLock.unlock();
3967
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003968 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3970 return; // event was consumed by the filter
3971 }
3972
3973 mLock.lock();
3974 }
3975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003976 std::unique_ptr<KeyEntry> newEntry =
3977 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3978 args->displayId, policyFlags, args->action, flags,
3979 keyCode, args->scanCode, metaState, repeatCount,
3980 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003982 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 mLock.unlock();
3984 } // release lock
3985
3986 if (needWake) {
3987 mLooper->wake();
3988 }
3989}
3990
3991bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3992 return mInputFilterEnabled;
3993}
3994
3995void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003996 if (DEBUG_INBOUND_EVENT_DETAILS) {
3997 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3998 "displayId=%" PRId32 ", policyFlags=0x%x, "
3999 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4000 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4001 "yCursorPosition=%f, downTime=%" PRId64,
4002 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4003 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4004 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4005 args->xCursorPosition, args->yCursorPosition, args->downTime);
4006 for (uint32_t i = 0; i < args->pointerCount; i++) {
4007 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4008 "x=%f, y=%f, pressure=%f, size=%f, "
4009 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4010 "orientation=%f",
4011 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4012 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4013 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4014 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4015 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4016 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4017 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4018 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4019 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4020 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004023 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4024 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 return;
4026 }
4027
4028 uint32_t policyFlags = args->policyFlags;
4029 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004030
4031 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004032 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004033 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4034 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004035 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Antonio Kantekf16f2832021-09-28 04:39:20 +00004038 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 { // acquire lock
4040 mLock.lock();
4041
4042 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004043 ui::Transform displayTransform;
4044 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4045 displayTransform = it->second.transform;
4046 }
4047
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 mLock.unlock();
4049
4050 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004051 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4052 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004053 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004054 displayTransform, args->xPrecision, args->yPrecision,
4055 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004056 args->downTime, args->eventTime, args->pointerCount,
4057 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
4059 policyFlags |= POLICY_FLAG_FILTERED;
4060 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4061 return; // event was consumed by the filter
4062 }
4063
4064 mLock.lock();
4065 }
4066
4067 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004068 std::unique_ptr<MotionEntry> newEntry =
4069 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4070 args->source, args->displayId, policyFlags,
4071 args->action, args->actionButton, args->flags,
4072 args->metaState, args->buttonState,
4073 args->classification, args->edgeFlags,
4074 args->xPrecision, args->yPrecision,
4075 args->xCursorPosition, args->yCursorPosition,
4076 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004077 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004079 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4080 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4081 !mInputFilterEnabled) {
4082 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4083 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4084 }
4085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004086 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 mLock.unlock();
4088 } // release lock
4089
4090 if (needWake) {
4091 mLooper->wake();
4092 }
4093}
4094
Chris Yef59a2f42020-10-16 12:55:26 -07004095void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004096 if (DEBUG_INBOUND_EVENT_DETAILS) {
4097 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4098 " sensorType=%s",
4099 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004100 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004101 }
Chris Yef59a2f42020-10-16 12:55:26 -07004102
Antonio Kantekf16f2832021-09-28 04:39:20 +00004103 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004104 { // acquire lock
4105 mLock.lock();
4106
4107 // Just enqueue a new sensor event.
4108 std::unique_ptr<SensorEntry> newEntry =
4109 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4110 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4111 args->sensorType, args->accuracy,
4112 args->accuracyChanged, args->values);
4113
4114 needWake = enqueueInboundEventLocked(std::move(newEntry));
4115 mLock.unlock();
4116 } // release lock
4117
4118 if (needWake) {
4119 mLooper->wake();
4120 }
4121}
4122
Chris Yefb552902021-02-03 17:18:37 -08004123void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004124 if (DEBUG_INBOUND_EVENT_DETAILS) {
4125 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4126 args->deviceId, args->isOn);
4127 }
Chris Yefb552902021-02-03 17:18:37 -08004128 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4129}
4130
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004132 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133}
4134
4135void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004136 if (DEBUG_INBOUND_EVENT_DETAILS) {
4137 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4138 "switchMask=0x%08x",
4139 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141
4142 uint32_t policyFlags = args->policyFlags;
4143 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145}
4146
4147void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004148 if (DEBUG_INBOUND_EVENT_DETAILS) {
4149 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4150 args->deviceId);
4151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
Antonio Kantekf16f2832021-09-28 04:39:20 +00004153 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004155 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004157 std::unique_ptr<DeviceResetEntry> newEntry =
4158 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4159 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 } // release lock
4161
4162 if (needWake) {
4163 mLooper->wake();
4164 }
4165}
4166
Prabir Pradhan7e186182020-11-10 13:56:45 -08004167void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004168 if (DEBUG_INBOUND_EVENT_DETAILS) {
4169 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004170 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004171 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004172
Antonio Kantekf16f2832021-09-28 04:39:20 +00004173 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004174 { // acquire lock
4175 std::scoped_lock _l(mLock);
4176 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004177 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004178 needWake = enqueueInboundEventLocked(std::move(entry));
4179 } // release lock
4180
4181 if (needWake) {
4182 mLooper->wake();
4183 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004184}
4185
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004186InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4187 std::optional<int32_t> targetUid,
4188 InputEventInjectionSync syncMode,
4189 std::chrono::milliseconds timeout,
4190 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004191 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004192 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4193 "policyFlags=0x%08x",
4194 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4195 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004196 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004197 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004199 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004201 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004202 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4203 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4204 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4205 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4206 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004207 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004208 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004209 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004210 }
4211
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004212 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004214 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004215 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4216 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004218 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004221 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004222 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4223 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4224 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004225 int32_t keyCode = incomingKey.getKeyCode();
4226 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004229 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004231 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4232 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4233 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4236 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004237 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238
4239 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4240 android::base::Timer t;
4241 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4242 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4243 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4244 std::to_string(t.duration().count()).c_str());
4245 }
4246 }
4247
4248 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004249 std::unique_ptr<KeyEntry> injectedEntry =
4250 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004252 incomingKey.getDisplayId(), policyFlags, action,
4253 flags, keyCode, incomingKey.getScanCode(), metaState,
4254 incomingKey.getRepeatCount(),
4255 incomingKey.getDownTime());
4256 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004261 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004262 const int32_t action = motionEvent.getAction();
4263 const bool isPointerEvent =
4264 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4265 // If a pointer event has no displayId specified, inject it to the default display.
4266 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4267 ? ADISPLAY_ID_DEFAULT
4268 : event->getDisplayId();
4269 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004270 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004271 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004272 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004274 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 }
4276
4277 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004278 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004279 android::base::Timer t;
4280 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4281 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4282 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4283 std::to_string(t.duration().count()).c_str());
4284 }
4285 }
4286
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004287 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4288 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4289 }
4290
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004292 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4293 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004294 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004295 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4296 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004297 displayId, policyFlags, action, actionButton,
4298 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004299 motionEvent.getButtonState(),
4300 motionEvent.getClassification(),
4301 motionEvent.getEdgeFlags(),
4302 motionEvent.getXPrecision(),
4303 motionEvent.getYPrecision(),
4304 motionEvent.getRawXCursorPosition(),
4305 motionEvent.getRawYCursorPosition(),
4306 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004307 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004308 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004309 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004310 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 sampleEventTimes += 1;
4312 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004314 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4315 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004316 displayId, policyFlags, action, actionButton,
4317 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 motionEvent.getButtonState(),
4319 motionEvent.getClassification(),
4320 motionEvent.getEdgeFlags(),
4321 motionEvent.getXPrecision(),
4322 motionEvent.getYPrecision(),
4323 motionEvent.getRawXCursorPosition(),
4324 motionEvent.getRawYCursorPosition(),
4325 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004326 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004327 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004328 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4329 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004330 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 }
4332 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004335 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004336 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004340 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004341 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 injectionState->injectionIsAsync = true;
4343 }
4344
4345 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004346 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
4348 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004349 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004351 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
4353
4354 mLock.unlock();
4355
4356 if (needWake) {
4357 mLooper->wake();
4358 }
4359
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004360 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004362 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 if (syncMode == InputEventInjectionSync::NONE) {
4365 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 } else {
4367 for (;;) {
4368 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 break;
4371 }
4372
4373 nsecs_t remainingTimeout = endTime - now();
4374 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004375 if (DEBUG_INJECTION) {
4376 ALOGD("injectInputEvent - Timed out waiting for injection result "
4377 "to become available.");
4378 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004379 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 break;
4381 }
4382
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004383 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4387 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004389 if (DEBUG_INJECTION) {
4390 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4391 injectionState->pendingForegroundDispatches);
4392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 nsecs_t remainingTimeout = endTime - now();
4394 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004395 if (DEBUG_INJECTION) {
4396 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4397 "dispatches to finish.");
4398 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004399 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 break;
4401 }
4402
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004403 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 }
4405 }
4406 }
4407
4408 injectionState->release();
4409 } // release lock
4410
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004411 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004412 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
4415 return injectionResult;
4416}
4417
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004418std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004419 std::array<uint8_t, 32> calculatedHmac;
4420 std::unique_ptr<VerifiedInputEvent> result;
4421 switch (event.getType()) {
4422 case AINPUT_EVENT_TYPE_KEY: {
4423 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4424 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4425 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004426 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004427 break;
4428 }
4429 case AINPUT_EVENT_TYPE_MOTION: {
4430 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4431 VerifiedMotionEvent verifiedMotionEvent =
4432 verifiedMotionEventFromMotionEvent(motionEvent);
4433 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004434 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004435 break;
4436 }
4437 default: {
4438 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4439 return nullptr;
4440 }
4441 }
4442 if (calculatedHmac == INVALID_HMAC) {
4443 return nullptr;
4444 }
4445 if (calculatedHmac != event.getHmac()) {
4446 return nullptr;
4447 }
4448 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004449}
4450
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004451void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004452 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004453 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004455 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004456 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004459 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 // Log the outcome since the injector did not wait for the injection result.
4461 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004462 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004463 ALOGV("Asynchronous input event injection succeeded.");
4464 break;
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004465 case InputEventInjectionResult::TARGET_MISMATCH:
4466 ALOGV("Asynchronous input event injection target mismatch.");
4467 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004468 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004469 ALOGW("Asynchronous input event injection failed.");
4470 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004471 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004472 ALOGW("Asynchronous input event injection timed out.");
4473 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004474 case InputEventInjectionResult::PENDING:
4475 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4476 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 }
4478 }
4479
4480 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004481 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483}
4484
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004485void InputDispatcher::transformMotionEntryForInjectionLocked(
4486 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004487 // Input injection works in the logical display coordinate space, but the input pipeline works
4488 // display space, so we need to transform the injected events accordingly.
4489 const auto it = mDisplayInfos.find(entry.displayId);
4490 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004491 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004492
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004493 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4494 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4495 const vec2 cursor =
4496 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4497 {entry.xCursorPosition, entry.yCursorPosition});
4498 entry.xCursorPosition = cursor.x;
4499 entry.yCursorPosition = cursor.y;
4500 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004501 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004502 entry.pointerCoords[i] =
4503 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4504 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004505 }
4506}
4507
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004508void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4509 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 if (injectionState) {
4511 injectionState->pendingForegroundDispatches += 1;
4512 }
4513}
4514
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004515void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4516 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 if (injectionState) {
4518 injectionState->pendingForegroundDispatches -= 1;
4519
4520 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004521 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 }
4523 }
4524}
4525
chaviw98318de2021-05-19 16:45:23 -05004526const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004527 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004528 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004529 auto it = mWindowHandlesByDisplay.find(displayId);
4530 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004531}
4532
chaviw98318de2021-05-19 16:45:23 -05004533sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004534 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004535 if (windowHandleToken == nullptr) {
4536 return nullptr;
4537 }
4538
Arthur Hungb92218b2018-08-14 12:00:21 +08004539 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004540 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4541 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004542 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004543 return windowHandle;
4544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 }
4546 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004547 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548}
4549
chaviw98318de2021-05-19 16:45:23 -05004550sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4551 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004552 if (windowHandleToken == nullptr) {
4553 return nullptr;
4554 }
4555
chaviw98318de2021-05-19 16:45:23 -05004556 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004557 if (windowHandle->getToken() == windowHandleToken) {
4558 return windowHandle;
4559 }
4560 }
4561 return nullptr;
4562}
4563
chaviw98318de2021-05-19 16:45:23 -05004564sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4565 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004566 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004567 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4568 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004569 if (handle->getId() == windowHandle->getId() &&
4570 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004571 if (windowHandle->getInfo()->displayId != it.first) {
4572 ALOGE("Found window %s in display %" PRId32
4573 ", but it should belong to display %" PRId32,
4574 windowHandle->getName().c_str(), it.first,
4575 windowHandle->getInfo()->displayId);
4576 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004577 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 }
4580 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004581 return nullptr;
4582}
4583
chaviw98318de2021-05-19 16:45:23 -05004584sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004585 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4586 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587}
4588
chaviw98318de2021-05-19 16:45:23 -05004589bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004590 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4591 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004592 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004593 if (connection != nullptr && noInputChannel) {
4594 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4595 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4596 return false;
4597 }
4598
4599 if (connection == nullptr) {
4600 if (!noInputChannel) {
4601 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4602 }
4603 return false;
4604 }
4605 if (!connection->responsive) {
4606 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4607 return false;
4608 }
4609 return true;
4610}
4611
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004612std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4613 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004614 auto connectionIt = mConnectionsByToken.find(token);
4615 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004616 return nullptr;
4617 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004618 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004619}
4620
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004621void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004622 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4623 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004624 // Remove all handles on a display if there are no windows left.
4625 mWindowHandlesByDisplay.erase(displayId);
4626 return;
4627 }
4628
4629 // Since we compare the pointer of input window handles across window updates, we need
4630 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004631 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4632 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4633 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004634 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004635 }
4636
chaviw98318de2021-05-19 16:45:23 -05004637 std::vector<sp<WindowInfoHandle>> newHandles;
4638 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004639 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004640 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004641 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004642 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004643 const bool canReceiveInput =
4644 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4645 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004646 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004647 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004648 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004649 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004650 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004651 }
4652
4653 if (info->displayId != displayId) {
4654 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4655 handle->getName().c_str(), displayId, info->displayId);
4656 continue;
4657 }
4658
Robert Carredd13602020-04-13 17:24:34 -07004659 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4660 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004661 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004662 oldHandle->updateFrom(handle);
4663 newHandles.push_back(oldHandle);
4664 } else {
4665 newHandles.push_back(handle);
4666 }
4667 }
4668
4669 // Insert or replace
4670 mWindowHandlesByDisplay[displayId] = newHandles;
4671}
4672
Arthur Hung72d8dc32020-03-28 00:48:39 +00004673void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004674 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004675 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004676 { // acquire lock
4677 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004678 for (const auto& [displayId, handles] : handlesPerDisplay) {
4679 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004680 }
4681 }
4682 // Wake up poll loop since it may need to make new input dispatching choices.
4683 mLooper->wake();
4684}
4685
Arthur Hungb92218b2018-08-14 12:00:21 +08004686/**
4687 * Called from InputManagerService, update window handle list by displayId that can receive input.
4688 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4689 * If set an empty list, remove all handles from the specific display.
4690 * For focused handle, check if need to change and send a cancel event to previous one.
4691 * For removed handle, check if need to send a cancel event if already in touch.
4692 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004693void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004694 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004695 if (DEBUG_FOCUS) {
4696 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004697 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004698 windowList += iwh->getName() + " ";
4699 }
4700 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702
Prabir Pradhand65552b2021-10-07 11:23:50 -07004703 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004704 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004705 const WindowInfo& info = *window->getInfo();
4706
4707 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004708 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004709 if (noInputWindow && window->getToken() != nullptr) {
4710 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4711 window->getName().c_str());
4712 window->releaseChannel();
4713 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004714
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004715 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004716 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4717 !info.inputConfig.test(
4718 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004719 "%s has feature SPY, but is not a trusted overlay.",
4720 window->getName().c_str());
4721
Prabir Pradhand65552b2021-10-07 11:23:50 -07004722 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004723 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4724 !info.inputConfig.test(
4725 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004726 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4727 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004728 }
4729
Arthur Hung72d8dc32020-03-28 00:48:39 +00004730 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004731 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004733 // Save the old windows' orientation by ID before it gets updated.
4734 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004735 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004736 oldWindowOrientations.emplace(handle->getId(),
4737 handle->getInfo()->transform.getOrientation());
4738 }
4739
chaviw98318de2021-05-19 16:45:23 -05004740 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004741
chaviw98318de2021-05-19 16:45:23 -05004742 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Tommy Nordgrenab0cedb2022-10-13 11:25:57 +02004743 if (mLastHoverWindowHandle) {
4744 const WindowInfo* lastHoverWindowInfo = mLastHoverWindowHandle->getInfo();
4745 if (lastHoverWindowInfo->displayId == displayId &&
4746 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4747 windowHandles.end()) {
4748 mLastHoverWindowHandle = nullptr;
4749 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004750 }
4751
Vishnu Nairc519ff72021-01-21 08:23:08 -08004752 std::optional<FocusResolver::FocusChanges> changes =
4753 mFocusResolver.setInputWindows(displayId, windowHandles);
4754 if (changes) {
4755 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004758 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4759 mTouchStatesByDisplay.find(displayId);
4760 if (stateIt != mTouchStatesByDisplay.end()) {
4761 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004762 for (size_t i = 0; i < state.windows.size();) {
4763 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004764 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004765 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004766 ALOGD("Touched window was removed: %s in display %" PRId32,
4767 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004768 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004769 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004770 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4771 if (touchedInputChannel != nullptr) {
4772 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4773 "touched window was removed");
4774 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004775 // Since we are about to drop the touch, cancel the events for the wallpaper as
4776 // well.
4777 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004778 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4779 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004780 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungba703c32022-12-08 07:45:36 +00004781 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 state.windows.erase(state.windows.begin() + i);
4785 } else {
4786 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 }
4788 }
arthurhungb89ccb02020-12-30 16:19:01 +08004789
arthurhung6d4bed92021-03-17 11:59:33 +08004790 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004791 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004792 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004793 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004794 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004795 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4796 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004797 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004798 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004799 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004800
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004801 // Determine if the orientation of any of the input windows have changed, and cancel all
4802 // pointer events if necessary.
4803 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4804 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4805 if (newWindowHandle != nullptr &&
4806 newWindowHandle->getInfo()->transform.getOrientation() !=
4807 oldWindowOrientations[oldWindowHandle->getId()]) {
4808 std::shared_ptr<InputChannel> inputChannel =
4809 getInputChannelLocked(newWindowHandle->getToken());
4810 if (inputChannel != nullptr) {
4811 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4812 "touched window's orientation changed");
4813 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004814 }
4815 }
4816 }
4817
Arthur Hung72d8dc32020-03-28 00:48:39 +00004818 // Release information for windows that are no longer present.
4819 // This ensures that unused input channels are released promptly.
4820 // Otherwise, they might stick around until the window handle is destroyed
4821 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004822 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004823 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004824 if (DEBUG_FOCUS) {
4825 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004826 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004827 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004828 }
chaviw291d88a2019-02-14 10:33:58 -08004829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830}
4831
4832void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004833 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004834 if (DEBUG_FOCUS) {
4835 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4836 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4837 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004838 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004839 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004840 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 } // release lock
4842
4843 // Wake up poll loop since it may need to make new input dispatching choices.
4844 mLooper->wake();
4845}
4846
Vishnu Nair599f1412021-06-21 10:39:58 -07004847void InputDispatcher::setFocusedApplicationLocked(
4848 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4849 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4850 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4851
4852 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4853 return; // This application is already focused. No need to wake up or change anything.
4854 }
4855
4856 // Set the new application handle.
4857 if (inputApplicationHandle != nullptr) {
4858 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4859 } else {
4860 mFocusedApplicationHandlesByDisplay.erase(displayId);
4861 }
4862
4863 // No matter what the old focused application was, stop waiting on it because it is
4864 // no longer focused.
4865 resetNoFocusedWindowTimeoutLocked();
4866}
4867
Tiger Huang721e26f2018-07-24 22:26:19 +08004868/**
4869 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4870 * the display not specified.
4871 *
4872 * We track any unreleased events for each window. If a window loses the ability to receive the
4873 * released event, we will send a cancel event to it. So when the focused display is changed, we
4874 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4875 * display. The display-specified events won't be affected.
4876 */
4877void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004878 if (DEBUG_FOCUS) {
4879 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4880 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004881 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004882 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004883
4884 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004885 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004886 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004887 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004888 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004889 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004890 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004891 CancelationOptions
4892 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4893 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004894 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004895 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4896 }
4897 }
4898 mFocusedDisplayId = displayId;
4899
Chris Ye3c2d6f52020-08-09 10:39:48 -07004900 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004901 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004902 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004903
Vishnu Nairad321cd2020-08-20 16:40:21 -07004904 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004905 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004906 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004907 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004908 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004909 }
4910 }
4911 }
4912
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004913 if (DEBUG_FOCUS) {
4914 logDispatchStateLocked();
4915 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004916 } // release lock
4917
4918 // Wake up poll loop since it may need to make new input dispatching choices.
4919 mLooper->wake();
4920}
4921
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004923 if (DEBUG_FOCUS) {
4924 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
4927 bool changed;
4928 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004929 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
4931 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4932 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004933 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 }
4935
4936 if (mDispatchEnabled && !enabled) {
4937 resetAndDropEverythingLocked("dispatcher is being disabled");
4938 }
4939
4940 mDispatchEnabled = enabled;
4941 mDispatchFrozen = frozen;
4942 changed = true;
4943 } else {
4944 changed = false;
4945 }
4946
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004947 if (DEBUG_FOCUS) {
4948 logDispatchStateLocked();
4949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 } // release lock
4951
4952 if (changed) {
4953 // Wake up poll loop since it may need to make new input dispatching choices.
4954 mLooper->wake();
4955 }
4956}
4957
4958void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004959 if (DEBUG_FOCUS) {
4960 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962
4963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004964 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
4966 if (mInputFilterEnabled == enabled) {
4967 return;
4968 }
4969
4970 mInputFilterEnabled = enabled;
4971 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4972 } // release lock
4973
4974 // Wake up poll loop since there might be work to do to drop everything.
4975 mLooper->wake();
4976}
4977
Antonio Kantekea47acb2021-12-23 12:41:25 -08004978bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4979 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004980 bool needWake = false;
4981 {
4982 std::scoped_lock lock(mLock);
4983 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004984 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004985 }
4986 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004987 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4988 "hasPermission=%s)",
4989 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4990 }
4991 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07004992 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
4993 !recentWindowsAreOwnedByLocked(pid, uid)) {
4994 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
4995 "window nor none of the previously interacted window",
4996 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004997 return false;
4998 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004999 }
5000
5001 // TODO(b/198499018): Store touch mode per display.
5002 mInTouchMode = inTouchMode;
5003
Antonio Kantekf16f2832021-09-28 04:39:20 +00005004 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5005 needWake = enqueueInboundEventLocked(std::move(entry));
5006 } // release lock
5007
5008 if (needWake) {
5009 mLooper->wake();
5010 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005011 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005012}
5013
Antonio Kantek48710e42022-03-24 14:19:30 -07005014bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5015 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5016 if (focusedToken == nullptr) {
5017 return false;
5018 }
5019 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5020 return isWindowOwnedBy(windowHandle, pid, uid);
5021}
5022
5023bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5024 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5025 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5026 const sp<WindowInfoHandle> windowHandle =
5027 getWindowHandleLocked(connectionToken);
5028 return isWindowOwnedBy(windowHandle, pid, uid);
5029 }) != mInteractionConnectionTokens.end();
5030}
5031
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005032void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5033 if (opacity < 0 || opacity > 1) {
5034 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5035 return;
5036 }
5037
5038 std::scoped_lock lock(mLock);
5039 mMaximumObscuringOpacityForTouch = opacity;
5040}
5041
5042void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5043 std::scoped_lock lock(mLock);
5044 mBlockUntrustedTouchesMode = mode;
5045}
5046
Arthur Hungabbb9d82021-09-01 14:52:30 +00005047std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5048 const sp<IBinder>& token) {
5049 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5050 for (TouchedWindow& w : state.windows) {
5051 if (w.windowHandle->getToken() == token) {
5052 return std::make_pair(&state, &w);
5053 }
5054 }
5055 }
5056 return std::make_pair(nullptr, nullptr);
5057}
5058
arthurhungb89ccb02020-12-30 16:19:01 +08005059bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5060 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005061 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005062 if (DEBUG_FOCUS) {
5063 ALOGD("Trivial transfer to same window.");
5064 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005065 return true;
5066 }
5067
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005069 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005070
Arthur Hungabbb9d82021-09-01 14:52:30 +00005071 // Find the target touch state and touched window by fromToken.
5072 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5073 if (state == nullptr || touchedWindow == nullptr) {
5074 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 return false;
5076 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005077
5078 const int32_t displayId = state->displayId;
5079 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5080 if (toWindowHandle == nullptr) {
5081 ALOGW("Cannot transfer focus because to window not found.");
5082 return false;
5083 }
5084
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005085 if (DEBUG_FOCUS) {
5086 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005087 touchedWindow->windowHandle->getName().c_str(),
5088 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 }
5090
Arthur Hungabbb9d82021-09-01 14:52:30 +00005091 // Erase old window.
5092 int32_t oldTargetFlags = touchedWindow->targetFlags;
5093 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungba703c32022-12-08 07:45:36 +00005094 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005095 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096
Arthur Hungabbb9d82021-09-01 14:52:30 +00005097 // Add new window.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005098 int32_t newTargetFlags =
5099 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5100 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5101 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5102 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005103 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104
Arthur Hungabbb9d82021-09-01 14:52:30 +00005105 // Store the dragging window.
5106 if (isDragDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00005107 if (pointerIds.count() != 1) {
5108 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5109 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005110 return false;
5111 }
Arthur Hung02701602022-07-15 09:35:36 +00005112 // Track the pointer id for drag window and generate the drag state.
5113 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005114 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
5116
Arthur Hungabbb9d82021-09-01 14:52:30 +00005117 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005118 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5119 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005120 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005121 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005122 CancelationOptions
5123 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5124 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungba703c32022-12-08 07:45:36 +00005126 synthesizePointerDownEventsForConnectionLocked(toConnection, newTargetFlags);
5127 // Check if the wallpaper window should deliver the corresponding event.
5128 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5129 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005132 if (DEBUG_FOCUS) {
5133 logDispatchStateLocked();
5134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 } // release lock
5136
5137 // Wake up poll loop since it may need to make new input dispatching choices.
5138 mLooper->wake();
5139 return true;
5140}
5141
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005142/**
5143 * Get the touched foreground window on the given display.
5144 * Return null if there are no windows touched on that display, or if more than one foreground
5145 * window is being touched.
5146 */
5147sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5148 auto stateIt = mTouchStatesByDisplay.find(displayId);
5149 if (stateIt == mTouchStatesByDisplay.end()) {
5150 ALOGI("No touch state on display %" PRId32, displayId);
5151 return nullptr;
5152 }
5153
5154 const TouchState& state = stateIt->second;
5155 sp<WindowInfoHandle> touchedForegroundWindow;
5156 // If multiple foreground windows are touched, return nullptr
5157 for (const TouchedWindow& window : state.windows) {
5158 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5159 if (touchedForegroundWindow != nullptr) {
5160 ALOGI("Two or more foreground windows: %s and %s",
5161 touchedForegroundWindow->getName().c_str(),
5162 window.windowHandle->getName().c_str());
5163 return nullptr;
5164 }
5165 touchedForegroundWindow = window.windowHandle;
5166 }
5167 }
5168 return touchedForegroundWindow;
5169}
5170
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005171// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005172bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005173 sp<IBinder> fromToken;
5174 { // acquire lock
5175 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005176 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005177 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005178 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5179 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005180 return false;
5181 }
5182
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005183 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5184 if (from == nullptr) {
5185 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5186 return false;
5187 }
5188
5189 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005190 } // release lock
5191
5192 return transferTouchFocus(fromToken, destChannelToken);
5193}
5194
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005196 if (DEBUG_FOCUS) {
5197 ALOGD("Resetting and dropping all events (%s).", reason);
5198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199
5200 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5201 synthesizeCancelationEventsForAllConnectionsLocked(options);
5202
5203 resetKeyRepeatLocked();
5204 releasePendingEventLocked();
5205 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005206 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005208 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005209 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005211 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212}
5213
5214void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216 dumpDispatchStateLocked(dump);
5217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005218 std::istringstream stream(dump);
5219 std::string line;
5220
5221 while (std::getline(stream, line, '\n')) {
5222 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 }
5224}
5225
Prabir Pradhan99987712020-11-10 18:43:05 -08005226std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5227 std::string dump;
5228
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005229 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5230 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005231
5232 std::string windowName = "None";
5233 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005234 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005235 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5236 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5237 : "token has capture without window";
5238 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005239 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005240
5241 return dump;
5242}
5243
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005244void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005245 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5246 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5247 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005248 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249
Tiger Huang721e26f2018-07-24 22:26:19 +08005250 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5251 dump += StringPrintf(INDENT "FocusedApplications:\n");
5252 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5253 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005254 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005255 const std::chrono::duration timeout =
5256 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005258 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005259 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005262 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005264
Vishnu Nairc519ff72021-01-21 08:23:08 -08005265 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005266 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005268 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005269 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005270 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5271 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005272 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005273 state.displayId, toString(state.down), toString(state.split),
5274 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005275 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005276 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005277 for (size_t i = 0; i < state.windows.size(); i++) {
5278 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005279 dump += StringPrintf(INDENT4
5280 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5281 i, touchedWindow.windowHandle->getName().c_str(),
5282 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005283 }
5284 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005285 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 }
5288 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291
arthurhung6d4bed92021-03-17 11:59:33 +08005292 if (mDragState) {
5293 dump += StringPrintf(INDENT "DragState:\n");
5294 mDragState->dump(dump, INDENT2);
5295 }
5296
Arthur Hungb92218b2018-08-14 12:00:21 +08005297 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005298 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5299 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5300 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5301 const auto& displayInfo = it->second;
5302 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5303 displayInfo.logicalHeight);
5304 displayInfo.transform.dump(dump, "transform", INDENT4);
5305 } else {
5306 dump += INDENT2 "No DisplayInfo found!\n";
5307 }
5308
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005309 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005310 dump += INDENT2 "Windows:\n";
5311 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005312 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5313 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005315 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005316 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005317 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005318 "applicationInfo.name=%s, "
5319 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005320 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005321 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005322 windowInfo->displayId,
5323 windowInfo->inputConfig.string().c_str(),
5324 windowInfo->alpha, windowInfo->frameLeft,
5325 windowInfo->frameTop, windowInfo->frameRight,
5326 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005327 windowInfo->applicationInfo.name.c_str(),
5328 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005329 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005330 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005331 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005332 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005333 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005334 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005335 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005336 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005337 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005338 }
5339 } else {
5340 dump += INDENT2 "Windows: <none>\n";
5341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 }
5343 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005344 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005347 if (!mGlobalMonitorsByDisplay.empty()) {
5348 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5349 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005350 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005353 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 }
5355
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005356 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357
5358 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005359 if (!mRecentQueue.empty()) {
5360 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005361 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005362 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005363 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005364 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 }
5366 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005367 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 }
5369
5370 // Dump event currently being dispatched.
5371 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005372 dump += INDENT "PendingEvent:\n";
5373 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005374 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005375 dump += StringPrintf(", age=%" PRId64 "ms\n",
5376 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005378 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
5380
5381 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005382 if (!mInboundQueue.empty()) {
5383 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005384 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005385 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005386 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005387 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005390 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 }
5392
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005393 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005394 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005395 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5396 const KeyReplacement& replacement = pair.first;
5397 int32_t newKeyCode = pair.second;
5398 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005399 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005400 }
5401 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005402 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005403 }
5404
Prabir Pradhancef936d2021-07-21 16:17:52 +00005405 if (!mCommandQueue.empty()) {
5406 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5407 } else {
5408 dump += INDENT "CommandQueue: <empty>\n";
5409 }
5410
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005411 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005412 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005413 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005414 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005415 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005416 connection->inputChannel->getFd().get(),
5417 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005418 connection->getWindowName().c_str(),
5419 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005420 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005422 if (!connection->outboundQueue.empty()) {
5423 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5424 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005425 dump += dumpQueue(connection->outboundQueue, currentTime);
5426
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005428 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005431 if (!connection->waitQueue.empty()) {
5432 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5433 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005434 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 }
5438 }
5439 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005440 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 }
5442
5443 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005444 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5445 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005447 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005450 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005451 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5452 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5453 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005454 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005455 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456}
5457
Michael Wright3dd60e22019-03-27 22:06:44 +00005458void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5459 const size_t numMonitors = monitors.size();
5460 for (size_t i = 0; i < numMonitors; i++) {
5461 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005462 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005463 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5464 dump += "\n";
5465 }
5466}
5467
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005468class LooperEventCallback : public LooperCallback {
5469public:
5470 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5471 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5472
5473private:
5474 std::function<int(int events)> mCallback;
5475};
5476
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005477Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005478 if (DEBUG_CHANNEL_CREATION) {
5479 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005482 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005483 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005484 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005485
5486 if (result) {
5487 return base::Error(result) << "Failed to open input channel pair with name " << name;
5488 }
5489
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005491 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005492 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005493 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005494 sp<Connection> connection =
5495 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005497 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5498 ALOGE("Created a new connection, but the token %p is already known", token.get());
5499 }
5500 mConnectionsByToken.emplace(token, connection);
5501
5502 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5503 this, std::placeholders::_1, token);
5504
5505 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 } // release lock
5507
5508 // Wake the looper because some connections have changed.
5509 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005510 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511}
5512
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005513Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005514 const std::string& name,
5515 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005516 std::shared_ptr<InputChannel> serverChannel;
5517 std::unique_ptr<InputChannel> clientChannel;
5518 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5519 if (result) {
5520 return base::Error(result) << "Failed to open input channel pair with name " << name;
5521 }
5522
Michael Wright3dd60e22019-03-27 22:06:44 +00005523 { // acquire lock
5524 std::scoped_lock _l(mLock);
5525
5526 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005527 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5528 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005529 }
5530
Garfield Tan15601662020-09-22 15:32:38 -07005531 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005532 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005533 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005534
5535 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5536 ALOGE("Created a new connection, but the token %p is already known", token.get());
5537 }
5538 mConnectionsByToken.emplace(token, connection);
5539 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5540 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005541
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005542 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005543
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005544 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005545 }
Garfield Tan15601662020-09-22 15:32:38 -07005546
Michael Wright3dd60e22019-03-27 22:06:44 +00005547 // Wake the looper because some connections have changed.
5548 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005549 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005550}
5551
Garfield Tan15601662020-09-22 15:32:38 -07005552status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005554 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555
Garfield Tan15601662020-09-22 15:32:38 -07005556 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 if (status) {
5558 return status;
5559 }
5560 } // release lock
5561
5562 // Wake the poll loop because removing the connection may have changed the current
5563 // synchronization state.
5564 mLooper->wake();
5565 return OK;
5566}
5567
Garfield Tan15601662020-09-22 15:32:38 -07005568status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5569 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005570 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005571 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005572 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 return BAD_VALUE;
5574 }
5575
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005576 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005577
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005579 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 }
5581
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005582 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583
5584 nsecs_t currentTime = now();
5585 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5586
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005587 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005588 return OK;
5589}
5590
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005591void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005592 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5593 auto& [displayId, monitors] = *it;
5594 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5595 return monitor.inputChannel->getConnectionToken() == connectionToken;
5596 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005597
Michael Wright3dd60e22019-03-27 22:06:44 +00005598 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005599 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005600 } else {
5601 ++it;
5602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 }
5604}
5605
Michael Wright3dd60e22019-03-27 22:06:44 +00005606status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005607 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005608
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005609 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5610 if (!requestingChannel) {
5611 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5612 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005613 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005614
5615 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5616 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5617 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5618 " Ignoring.");
5619 return BAD_VALUE;
5620 }
5621
5622 TouchState& state = *statePtr;
5623
5624 // Send cancel events to all the input channels we're stealing from.
5625 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5626 "input channel stole pointer stream");
5627 options.deviceId = state.deviceId;
5628 options.displayId = state.displayId;
5629 std::string canceledWindows;
5630 for (const TouchedWindow& window : state.windows) {
5631 const std::shared_ptr<InputChannel> channel =
5632 getInputChannelLocked(window.windowHandle->getToken());
5633 if (channel != nullptr && channel->getConnectionToken() != token) {
5634 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5635 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5636 canceledWindows += channel->getName();
5637 }
5638 }
5639 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5640 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5641 canceledWindows.c_str());
5642
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005643 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005644 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005645 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005646 return OK;
5647}
5648
Prabir Pradhan99987712020-11-10 18:43:05 -08005649void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5650 { // acquire lock
5651 std::scoped_lock _l(mLock);
5652 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005653 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005654 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5655 windowHandle != nullptr ? windowHandle->getName().c_str()
5656 : "token without window");
5657 }
5658
Vishnu Nairc519ff72021-01-21 08:23:08 -08005659 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005660 if (focusedToken != windowToken) {
5661 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5662 enabled ? "enable" : "disable");
5663 return;
5664 }
5665
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005666 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005667 ALOGW("Ignoring request to %s Pointer Capture: "
5668 "window has %s requested pointer capture.",
5669 enabled ? "enable" : "disable", enabled ? "already" : "not");
5670 return;
5671 }
5672
Christine Franksb768bb42021-11-29 12:11:31 -08005673 if (enabled) {
5674 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5675 mIneligibleDisplaysForPointerCapture.end(),
5676 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5677 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5678 return;
5679 }
5680 }
5681
Prabir Pradhan99987712020-11-10 18:43:05 -08005682 setPointerCaptureLocked(enabled);
5683 } // release lock
5684
5685 // Wake the thread to process command entries.
5686 mLooper->wake();
5687}
5688
Christine Franksb768bb42021-11-29 12:11:31 -08005689void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5690 { // acquire lock
5691 std::scoped_lock _l(mLock);
5692 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5693 if (!isEligible) {
5694 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5695 }
5696 } // release lock
5697}
5698
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005699std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5700 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005701 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005702 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005703 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005704 }
5705 }
5706 }
5707 return std::nullopt;
5708}
5709
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005710sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005711 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005712 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005713 }
5714
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005715 for (const auto& [token, connection] : mConnectionsByToken) {
5716 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005717 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 }
5719 }
Robert Carr4e670e52018-08-15 13:26:12 -07005720
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005721 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722}
5723
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005724std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5725 sp<Connection> connection = getConnectionLocked(connectionToken);
5726 if (connection == nullptr) {
5727 return "<nullptr>";
5728 }
5729 return connection->getInputChannelName();
5730}
5731
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005732void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005733 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005734 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005735}
5736
Prabir Pradhancef936d2021-07-21 16:17:52 +00005737void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5738 const sp<Connection>& connection, uint32_t seq,
5739 bool handled, nsecs_t consumeTime) {
5740 // Handle post-event policy actions.
5741 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5742 if (dispatchEntryIt == connection->waitQueue.end()) {
5743 return;
5744 }
5745 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5746 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5747 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5748 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5749 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5750 }
5751 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5752 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5753 connection->inputChannel->getConnectionToken(),
5754 dispatchEntry->deliveryTime, consumeTime, finishTime);
5755 }
5756
5757 bool restartEvent;
5758 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5759 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5760 restartEvent =
5761 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5762 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5763 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5764 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5765 handled);
5766 } else {
5767 restartEvent = false;
5768 }
5769
5770 // Dequeue the event and start the next cycle.
5771 // Because the lock might have been released, it is possible that the
5772 // contents of the wait queue to have been drained, so we need to double-check
5773 // a few things.
5774 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5775 if (dispatchEntryIt != connection->waitQueue.end()) {
5776 dispatchEntry = *dispatchEntryIt;
5777 connection->waitQueue.erase(dispatchEntryIt);
5778 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5779 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5780 if (!connection->responsive) {
5781 connection->responsive = isConnectionResponsive(*connection);
5782 if (connection->responsive) {
5783 // The connection was unresponsive, and now it's responsive.
5784 processConnectionResponsiveLocked(*connection);
5785 }
5786 }
5787 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005788 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005789 connection->outboundQueue.push_front(dispatchEntry);
5790 traceOutboundQueueLength(*connection);
5791 } else {
5792 releaseDispatchEntry(dispatchEntry);
5793 }
5794 }
5795
5796 // Start the next dispatch cycle for this connection.
5797 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798}
5799
Prabir Pradhancef936d2021-07-21 16:17:52 +00005800void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5801 const sp<IBinder>& newToken) {
5802 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5803 scoped_unlock unlock(mLock);
5804 mPolicy->notifyFocusChanged(oldToken, newToken);
5805 };
5806 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807}
5808
Prabir Pradhancef936d2021-07-21 16:17:52 +00005809void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5810 auto command = [this, token, x, y]() REQUIRES(mLock) {
5811 scoped_unlock unlock(mLock);
5812 mPolicy->notifyDropWindow(token, x, y);
5813 };
5814 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005815}
5816
Prabir Pradhancef936d2021-07-21 16:17:52 +00005817void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5818 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5819 scoped_unlock unlock(mLock);
5820 mPolicy->notifyUntrustedTouch(obscuringPackage);
5821 };
5822 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005823}
5824
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005825void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5826 if (connection == nullptr) {
5827 LOG_ALWAYS_FATAL("Caller must check for nullness");
5828 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005829 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5830 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005831 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005832 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005833 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005834 return;
5835 }
5836 /**
5837 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5838 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5839 * has changed. This could cause newer entries to time out before the already dispatched
5840 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5841 * processes the events linearly. So providing information about the oldest entry seems to be
5842 * most useful.
5843 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005844 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005845 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5846 std::string reason =
5847 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005848 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005849 ns2ms(currentWait),
5850 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005851 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005852 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005853
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005854 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5855
5856 // Stop waking up for events on this connection, it is already unresponsive
5857 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005858}
5859
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005860void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5861 std::string reason =
5862 StringPrintf("%s does not have a focused window", application->getName().c_str());
5863 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005864
Prabir Pradhancef936d2021-07-21 16:17:52 +00005865 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5866 scoped_unlock unlock(mLock);
5867 mPolicy->notifyNoFocusedWindowAnr(application);
5868 };
5869 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005870}
5871
chaviw98318de2021-05-19 16:45:23 -05005872void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005873 const std::string& reason) {
5874 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5875 updateLastAnrStateLocked(windowLabel, reason);
5876}
5877
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005878void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5879 const std::string& reason) {
5880 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005881 updateLastAnrStateLocked(windowLabel, reason);
5882}
5883
5884void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5885 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005887 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 struct tm tm;
5889 localtime_r(&t, &tm);
5890 char timestr[64];
5891 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005892 mLastAnrState.clear();
5893 mLastAnrState += INDENT "ANR:\n";
5894 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5896 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005897 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898}
5899
Prabir Pradhancef936d2021-07-21 16:17:52 +00005900void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5901 KeyEntry& entry) {
5902 const KeyEvent event = createKeyEvent(entry);
5903 nsecs_t delay = 0;
5904 { // release lock
5905 scoped_unlock unlock(mLock);
5906 android::base::Timer t;
5907 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5908 entry.policyFlags);
5909 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5910 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5911 std::to_string(t.duration().count()).c_str());
5912 }
5913 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914
5915 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005916 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005917 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005920 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5921 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923}
5924
Prabir Pradhancef936d2021-07-21 16:17:52 +00005925void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005926 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005927 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005928 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005929 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005930 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005931 };
5932 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005933}
5934
Prabir Pradhanedd96402022-02-15 01:46:16 -08005935void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5936 std::optional<int32_t> pid) {
5937 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005938 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005939 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005940 };
5941 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005942}
5943
5944/**
5945 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5946 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5947 * command entry to the command queue.
5948 */
5949void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5950 std::string reason) {
5951 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005952 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005953 if (connection.monitor) {
5954 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5955 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005956 pid = findMonitorPidByTokenLocked(connectionToken);
5957 } else {
5958 // The connection is a window
5959 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5960 reason.c_str());
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 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005967}
5968
5969/**
5970 * Tell the policy that a connection has become responsive so that it can stop ANR.
5971 */
5972void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5973 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005974 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005975 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005976 pid = findMonitorPidByTokenLocked(connectionToken);
5977 } else {
5978 // The connection is a window
5979 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5980 if (handle != nullptr) {
5981 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005982 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005983 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005984 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005985}
5986
Prabir Pradhancef936d2021-07-21 16:17:52 +00005987bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005988 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005989 KeyEntry& keyEntry, bool handled) {
5990 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005991 if (!handled) {
5992 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005993 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005994 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005995 return false;
5996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005998 // Get the fallback key state.
5999 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006000 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006001 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006002 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006003 connection->inputState.removeFallbackKey(originalKeyCode);
6004 }
6005
6006 if (handled || !dispatchEntry->hasForegroundTarget()) {
6007 // If the application handles the original key for which we previously
6008 // generated a fallback or if the window is not a foreground window,
6009 // then cancel the associated fallback key, if any.
6010 if (fallbackKeyCode != -1) {
6011 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006012 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6013 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6014 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6015 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6016 keyEntry.policyFlags);
6017 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006018 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006019 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020
6021 mLock.unlock();
6022
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006023 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006024 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025
6026 mLock.lock();
6027
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006028 // Cancel the fallback key.
6029 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006031 "application handled the original non-fallback key "
6032 "or is no longer a foreground target, "
6033 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034 options.keyCode = fallbackKeyCode;
6035 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006037 connection->inputState.removeFallbackKey(originalKeyCode);
6038 }
6039 } else {
6040 // If the application did not handle a non-fallback key, first check
6041 // that we are in a good state to perform unhandled key event processing
6042 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006043 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006045 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6046 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6047 "since this is not an initial down. "
6048 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6049 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6050 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006051 return false;
6052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006055 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6056 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6057 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6058 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6059 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006060 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061
6062 mLock.unlock();
6063
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006064 bool fallback =
6065 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006066 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067
6068 mLock.lock();
6069
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006070 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006071 connection->inputState.removeFallbackKey(originalKeyCode);
6072 return false;
6073 }
6074
6075 // Latch the fallback keycode for this key on an initial down.
6076 // The fallback keycode cannot change at any other point in the lifecycle.
6077 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006079 fallbackKeyCode = event.getKeyCode();
6080 } else {
6081 fallbackKeyCode = AKEYCODE_UNKNOWN;
6082 }
6083 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6084 }
6085
6086 ALOG_ASSERT(fallbackKeyCode != -1);
6087
6088 // Cancel the fallback key if the policy decides not to send it anymore.
6089 // We will continue to dispatch the key to the policy but we will no
6090 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006091 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6092 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006093 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6094 if (fallback) {
6095 ALOGD("Unhandled key event: Policy requested to send key %d"
6096 "as a fallback for %d, but on the DOWN it had requested "
6097 "to send %d instead. Fallback canceled.",
6098 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6099 } else {
6100 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6101 "but on the DOWN it had requested to send %d. "
6102 "Fallback canceled.",
6103 originalKeyCode, fallbackKeyCode);
6104 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006105 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106
6107 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6108 "canceling fallback, policy no longer desires it");
6109 options.keyCode = fallbackKeyCode;
6110 synthesizeCancelationEventsForConnectionLocked(connection, options);
6111
6112 fallback = false;
6113 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006114 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006115 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116 }
6117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006119 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6120 {
6121 std::string msg;
6122 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6123 connection->inputState.getFallbackKeys();
6124 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6125 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6126 }
6127 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6128 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006129 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006130 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006131
6132 if (fallback) {
6133 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006134 keyEntry.eventTime = event.getEventTime();
6135 keyEntry.deviceId = event.getDeviceId();
6136 keyEntry.source = event.getSource();
6137 keyEntry.displayId = event.getDisplayId();
6138 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6139 keyEntry.keyCode = fallbackKeyCode;
6140 keyEntry.scanCode = event.getScanCode();
6141 keyEntry.metaState = event.getMetaState();
6142 keyEntry.repeatCount = event.getRepeatCount();
6143 keyEntry.downTime = event.getDownTime();
6144 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006145
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006146 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6147 ALOGD("Unhandled key event: Dispatching fallback key. "
6148 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6149 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6150 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006151 return true; // restart the event
6152 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006153 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6154 ALOGD("Unhandled key event: No fallback key.");
6155 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006156
6157 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006158 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159 }
6160 }
6161 return false;
6162}
6163
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006165 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006166 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 return false;
6168}
6169
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170void InputDispatcher::traceInboundQueueLengthLocked() {
6171 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006172 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006173 }
6174}
6175
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006176void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177 if (ATRACE_ENABLED()) {
6178 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006179 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6180 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181 }
6182}
6183
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006184void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185 if (ATRACE_ENABLED()) {
6186 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006187 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6188 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 }
6190}
6191
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006192void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006193 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006195 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006196 dumpDispatchStateLocked(dump);
6197
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006198 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006199 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006200 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 }
6202}
6203
6204void InputDispatcher::monitor() {
6205 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006206 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006208 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209}
6210
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006211/**
6212 * Wake up the dispatcher and wait until it processes all events and commands.
6213 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6214 * this method can be safely called from any thread, as long as you've ensured that
6215 * the work you are interested in completing has already been queued.
6216 */
6217bool InputDispatcher::waitForIdle() {
6218 /**
6219 * Timeout should represent the longest possible time that a device might spend processing
6220 * events and commands.
6221 */
6222 constexpr std::chrono::duration TIMEOUT = 100ms;
6223 std::unique_lock lock(mLock);
6224 mLooper->wake();
6225 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6226 return result == std::cv_status::no_timeout;
6227}
6228
Vishnu Naire798b472020-07-23 13:52:21 -07006229/**
6230 * Sets focus to the window identified by the token. This must be called
6231 * after updating any input window handles.
6232 *
6233 * Params:
6234 * request.token - input channel token used to identify the window that should gain focus.
6235 * request.focusedToken - the token that the caller expects currently to be focused. If the
6236 * specified token does not match the currently focused window, this request will be dropped.
6237 * If the specified focused token matches the currently focused window, the call will succeed.
6238 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6239 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6240 * when requesting the focus change. This determines which request gets
6241 * precedence if there is a focus change request from another source such as pointer down.
6242 */
Vishnu Nair958da932020-08-21 17:12:37 -07006243void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6244 { // acquire lock
6245 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006246 std::optional<FocusResolver::FocusChanges> changes =
6247 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6248 if (changes) {
6249 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006250 }
6251 } // release lock
6252 // Wake up poll loop since it may need to make new input dispatching choices.
6253 mLooper->wake();
6254}
6255
Vishnu Nairc519ff72021-01-21 08:23:08 -08006256void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6257 if (changes.oldFocus) {
6258 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006259 if (focusedInputChannel) {
6260 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6261 "focus left window");
6262 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006263 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006264 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006265 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006266 if (changes.newFocus) {
6267 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006268 }
6269
Prabir Pradhan99987712020-11-10 18:43:05 -08006270 // If a window has pointer capture, then it must have focus. We need to ensure that this
6271 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6272 // If the window loses focus before it loses pointer capture, then the window can be in a state
6273 // where it has pointer capture but not focus, violating the contract. Therefore we must
6274 // dispatch the pointer capture event before the focus event. Since focus events are added to
6275 // the front of the queue (above), we add the pointer capture event to the front of the queue
6276 // after the focus events are added. This ensures the pointer capture event ends up at the
6277 // front.
6278 disablePointerCaptureForcedLocked();
6279
Vishnu Nairc519ff72021-01-21 08:23:08 -08006280 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006281 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006282 }
6283}
Vishnu Nair958da932020-08-21 17:12:37 -07006284
Prabir Pradhan99987712020-11-10 18:43:05 -08006285void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006286 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006287 return;
6288 }
6289
6290 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6291
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006292 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006293 setPointerCaptureLocked(false);
6294 }
6295
6296 if (!mWindowTokenWithPointerCapture) {
6297 // No need to send capture changes because no window has capture.
6298 return;
6299 }
6300
6301 if (mPendingEvent != nullptr) {
6302 // Move the pending event to the front of the queue. This will give the chance
6303 // for the pending event to be dropped if it is a captured event.
6304 mInboundQueue.push_front(mPendingEvent);
6305 mPendingEvent = nullptr;
6306 }
6307
6308 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006309 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006310 mInboundQueue.push_front(std::move(entry));
6311}
6312
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006313void InputDispatcher::setPointerCaptureLocked(bool enable) {
6314 mCurrentPointerCaptureRequest.enable = enable;
6315 mCurrentPointerCaptureRequest.seq++;
6316 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006317 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006318 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006319 };
6320 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006321}
6322
Vishnu Nair599f1412021-06-21 10:39:58 -07006323void InputDispatcher::displayRemoved(int32_t displayId) {
6324 { // acquire lock
6325 std::scoped_lock _l(mLock);
6326 // Set an empty list to remove all handles from the specific display.
6327 setInputWindowsLocked(/* window handles */ {}, displayId);
6328 setFocusedApplicationLocked(displayId, nullptr);
6329 // Call focus resolver to clean up stale requests. This must be called after input windows
6330 // have been removed for the removed display.
6331 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006332 // Reset pointer capture eligibility, regardless of previous state.
6333 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006334 } // release lock
6335
6336 // Wake up poll loop since it may need to make new input dispatching choices.
6337 mLooper->wake();
6338}
6339
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006340void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6341 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006342 // The listener sends the windows as a flattened array. Separate the windows by display for
6343 // more convenient parsing.
6344 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006345 for (const auto& info : windowInfos) {
6346 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6347 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6348 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006349
6350 { // acquire lock
6351 std::scoped_lock _l(mLock);
Prabir Pradhan73fe4812022-07-22 20:22:18 +00006352
6353 // Ensure that we have an entry created for all existing displays so that if a displayId has
6354 // no windows, we can tell that the windows were removed from the display.
6355 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6356 handlesPerDisplay[displayId];
6357 }
6358
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006359 mDisplayInfos.clear();
6360 for (const auto& displayInfo : displayInfos) {
6361 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6362 }
6363
6364 for (const auto& [displayId, handles] : handlesPerDisplay) {
6365 setInputWindowsLocked(handles, displayId);
6366 }
6367 }
6368 // Wake up poll loop since it may need to make new input dispatching choices.
6369 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006370}
6371
Vishnu Nair062a8672021-09-03 16:07:44 -07006372bool InputDispatcher::shouldDropInput(
6373 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006374 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6375 (windowHandle->getInfo()->inputConfig.test(
6376 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006377 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006378 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6379 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006380 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006381 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006382 windowHandle->getInfo()->displayId);
6383 return true;
6384 }
6385 return false;
6386}
6387
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006388void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6389 const std::vector<gui::WindowInfo>& windowInfos,
6390 const std::vector<DisplayInfo>& displayInfos) {
6391 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6392}
6393
Arthur Hungdfd528e2021-12-08 13:23:04 +00006394void InputDispatcher::cancelCurrentTouch() {
6395 {
6396 std::scoped_lock _l(mLock);
6397 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6398 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6399 "cancel current touch");
6400 synthesizeCancelationEventsForAllConnectionsLocked(options);
6401
6402 mTouchStatesByDisplay.clear();
6403 mLastHoverWindowHandle.clear();
6404 }
6405 // Wake up poll loop since there might be work to do.
6406 mLooper->wake();
6407}
6408
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006409void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6410 std::scoped_lock _l(mLock);
6411 mMonitorDispatchingTimeout = timeout;
6412}
6413
Arthur Hungba703c32022-12-08 07:45:36 +00006414void InputDispatcher::slipWallpaperTouch(int32_t targetFlags,
6415 const sp<WindowInfoHandle>& oldWindowHandle,
6416 const sp<WindowInfoHandle>& newWindowHandle,
6417 TouchState& state, const BitSet32& pointerIds) {
6418 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6419 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6420 const bool newHasWallpaper = (targetFlags & InputTarget::FLAG_FOREGROUND) &&
6421 newWindowHandle->getInfo()->inputConfig.test(
6422 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6423 const sp<WindowInfoHandle> oldWallpaper =
6424 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6425 const sp<WindowInfoHandle> newWallpaper =
6426 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6427 if (oldWallpaper == newWallpaper) {
6428 return;
6429 }
6430
6431 if (oldWallpaper != nullptr) {
6432 state.addOrUpdateWindow(oldWallpaper, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
6433 BitSet32(0));
6434 }
6435
6436 if (newWallpaper != nullptr) {
6437 state.addOrUpdateWindow(newWallpaper,
6438 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER |
6439 InputTarget::FLAG_WINDOW_IS_OBSCURED |
6440 InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED,
6441 pointerIds);
6442 }
6443}
6444
6445void InputDispatcher::transferWallpaperTouch(int32_t oldTargetFlags, int32_t newTargetFlags,
6446 const sp<WindowInfoHandle> fromWindowHandle,
6447 const sp<WindowInfoHandle> toWindowHandle,
6448 TouchState& state, const BitSet32& pointerIds) {
6449 const bool oldHasWallpaper = (oldTargetFlags & InputTarget::FLAG_FOREGROUND) &&
6450 fromWindowHandle->getInfo()->inputConfig.test(
6451 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6452 const bool newHasWallpaper = (newTargetFlags & InputTarget::FLAG_FOREGROUND) &&
6453 toWindowHandle->getInfo()->inputConfig.test(
6454 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6455
6456 const sp<WindowInfoHandle> oldWallpaper =
6457 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6458 const sp<WindowInfoHandle> newWallpaper =
6459 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6460 if (oldWallpaper == newWallpaper) {
6461 return;
6462 }
6463
6464 if (oldWallpaper != nullptr) {
6465 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6466 "transferring touch focus to another window");
6467 state.removeWindowByToken(oldWallpaper->getToken());
6468 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6469 }
6470
6471 if (newWallpaper != nullptr) {
6472 int32_t wallpaperFlags =
6473 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
6474 wallpaperFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED |
6475 InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
6476 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds);
6477 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6478 if (wallpaperConnection != nullptr) {
6479 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6480 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6481 synthesizePointerDownEventsForConnectionLocked(wallpaperConnection, wallpaperFlags);
6482 }
6483 }
6484}
6485
6486sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6487 const sp<WindowInfoHandle>& windowHandle) const {
6488 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6489 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6490 bool foundWindow = false;
6491 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6492 if (!foundWindow && otherHandle != windowHandle) {
6493 continue;
6494 }
6495 if (windowHandle == otherHandle) {
6496 foundWindow = true;
6497 continue;
6498 }
6499
6500 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6501 return otherHandle;
6502 }
6503 }
6504 return nullptr;
6505}
6506
Garfield Tane84e6f92019-08-29 17:28:41 -07006507} // namespace android::inputdispatcher