blob: 5f48c1de6b63c9dc95cfb27734e91fb84c9f394e [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
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -070022#include <InputFlingerProperties.sysprop.h>
Michael Wright2b3c3302018-03-02 17:19:13 +000023#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100028#include <binder/IServiceManager.h>
29#include <com/android/internal/compat/IPlatformCompatNative.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080030#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070033#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000034#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070048#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#define INDENT " "
51#define INDENT2 " "
52#define INDENT3 " "
53#define INDENT4 " "
54
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080055using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000056using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070058using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050059using android::gui::FocusRequest;
60using android::gui::TouchOcclusionMode;
61using android::gui::WindowInfo;
62using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080063using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100064using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080065using android::os::InputEventInjectionResult;
66using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100067using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068
Garfield Tane84e6f92019-08-29 17:28:41 -070069namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Prabir Pradhancef936d2021-07-21 16:17:52 +000071namespace {
72
Prabir Pradhan61a5d242021-07-26 16:41:09 +000073// Log detailed debug messages about each inbound event notification to the dispatcher.
74constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
75
76// Log detailed debug messages about each outbound event processed by the dispatcher.
77constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
78
79// Log debug messages about the dispatch cycle.
80constexpr bool DEBUG_DISPATCH_CYCLE = false;
81
82// Log debug messages about channel creation
83constexpr bool DEBUG_CHANNEL_CREATION = false;
84
85// Log debug messages about input event injection.
86constexpr bool DEBUG_INJECTION = false;
87
88// Log debug messages about input focus tracking.
89constexpr bool DEBUG_FOCUS = false;
90
91// Log debug messages about touch occlusion
92// STOPSHIP(b/169067926): Set to false
93constexpr bool DEBUG_TOUCH_OCCLUSION = true;
94
95// Log debug messages about the app switch latency optimization.
96constexpr bool DEBUG_APP_SWITCH = false;
97
98// Log debug messages about hover events.
99constexpr bool DEBUG_HOVER = false;
100
Prabir Pradhancef936d2021-07-21 16:17:52 +0000101// Temporarily releases a held mutex for the lifetime of the instance.
102// Named to match std::scoped_lock
103class scoped_unlock {
104public:
105 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
106 ~scoped_unlock() { mMutex.lock(); }
107
108private:
109 std::mutex& mMutex;
110};
111
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700112// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
113// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000114bool isPerWindowInputRotationEnabled() {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700115 static const bool PER_WINDOW_INPUT_ROTATION =
Vadim Tryshev7719c7d2021-08-27 17:28:43 +0000116 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700117
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700118 return PER_WINDOW_INPUT_ROTATION;
119}
120
Michael Wrightd02c5b62014-02-10 15:10:22 -0800121// Default input dispatching timeout if there is no focused application or paused window
122// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800123const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
124 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
125 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126
127// Amount of time to allow for all pending events to be processed when an app switch
128// key is on the way. This is used to preempt input dispatch and drop input events
129// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000130constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131
132// Amount of time to allow for an event to be dispatched (measured since its eventTime)
133// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000134constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136// 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 +0000137constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
138
139// Log a warning when an interception call takes longer than this to process.
140constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700142// Additional key latency in case a connection is still processing some motion events.
143// This will help with the case when a user touched a button that opens a new window,
144// and gives us the chance to dispatch the key to this new window.
145constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
146
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000148constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
149
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000150// Event log tags. See EventLogTags.logtags for reference
151constexpr int LOGTAG_INPUT_INTERACTION = 62000;
152constexpr int LOGTAG_INPUT_FOCUS = 62001;
153
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000154inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800155 return systemTime(SYSTEM_TIME_MONOTONIC);
156}
157
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000158inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 return value ? "true" : "false";
160}
161
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000162inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000163 if (binder == nullptr) {
164 return "<null>";
165 }
166 return StringPrintf("%p", binder.get());
167}
168
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000169inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
171 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172}
173
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000174bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AKEY_EVENT_ACTION_DOWN:
177 case AKEY_EVENT_ACTION_UP:
178 return true;
179 default:
180 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 }
182}
183
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000184bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 ALOGE("Key event has invalid action code 0x%x", action);
187 return false;
188 }
189 return true;
190}
191
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000192bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 case AMOTION_EVENT_ACTION_DOWN:
195 case AMOTION_EVENT_ACTION_UP:
196 case AMOTION_EVENT_ACTION_CANCEL:
197 case AMOTION_EVENT_ACTION_MOVE:
198 case AMOTION_EVENT_ACTION_OUTSIDE:
199 case AMOTION_EVENT_ACTION_HOVER_ENTER:
200 case AMOTION_EVENT_ACTION_HOVER_MOVE:
201 case AMOTION_EVENT_ACTION_HOVER_EXIT:
202 case AMOTION_EVENT_ACTION_SCROLL:
203 return true;
204 case AMOTION_EVENT_ACTION_POINTER_DOWN:
205 case AMOTION_EVENT_ACTION_POINTER_UP: {
206 int32_t index = getMotionEventActionPointerIndex(action);
207 return index >= 0 && index < pointerCount;
208 }
209 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
210 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
211 return actionButton != 0;
212 default:
213 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
215}
216
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000217int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500218 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
219}
220
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000221bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
222 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700223 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 ALOGE("Motion event has invalid action code 0x%x", action);
225 return false;
226 }
227 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000228 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700229 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 return false;
231 }
232 BitSet32 pointerIdBits;
233 for (size_t i = 0; i < pointerCount; i++) {
234 int32_t id = pointerProperties[i].id;
235 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700236 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
237 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800238 return false;
239 }
240 if (pointerIdBits.hasBit(id)) {
241 ALOGE("Motion event has duplicate pointer id %d", id);
242 return false;
243 }
244 pointerIdBits.markBit(id);
245 }
246 return true;
247}
248
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000249std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000251 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 }
253
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000254 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 bool first = true;
256 Region::const_iterator cur = region.begin();
257 Region::const_iterator const tail = region.end();
258 while (cur != tail) {
259 if (first) {
260 first = false;
261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800262 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800264 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 cur++;
266 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000267 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268}
269
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000270std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500271 constexpr size_t maxEntries = 50; // max events to print
272 constexpr size_t skipBegin = maxEntries / 2;
273 const size_t skipEnd = queue.size() - maxEntries / 2;
274 // skip from maxEntries / 2 ... size() - maxEntries/2
275 // only print from 0 .. skipBegin and then from skipEnd .. size()
276
277 std::string dump;
278 for (size_t i = 0; i < queue.size(); i++) {
279 const DispatchEntry& entry = *queue[i];
280 if (i >= skipBegin && i < skipEnd) {
281 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
282 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
283 continue;
284 }
285 dump.append(INDENT4);
286 dump += entry.eventEntry->getDescription();
287 dump += StringPrintf(", seq=%" PRIu32
288 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
289 entry.seq, entry.targetFlags, entry.resolvedAction,
290 ns2ms(currentTime - entry.eventEntry->eventTime));
291 if (entry.deliveryTime != 0) {
292 // This entry was delivered, so add information on how long we've been waiting
293 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
294 }
295 dump.append("\n");
296 }
297 return dump;
298}
299
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700300/**
301 * Find the entry in std::unordered_map by key, and return it.
302 * If the entry is not found, return a default constructed entry.
303 *
304 * Useful when the entries are vectors, since an empty vector will be returned
305 * if the entry is not found.
306 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
307 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700308template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000309V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700310 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700311 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800312}
313
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000314bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700315 if (first == second) {
316 return true;
317 }
318
319 if (first == nullptr || second == nullptr) {
320 return false;
321 }
322
323 return first->getToken() == second->getToken();
324}
325
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000326bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000327 if (first == nullptr || second == nullptr) {
328 return false;
329 }
330 return first->applicationInfo.token != nullptr &&
331 first->applicationInfo.token == second->applicationInfo.token;
332}
333
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000334bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800335 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
336}
337
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000338std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
339 std::shared_ptr<EventEntry> eventEntry,
340 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900341 if (eventEntry->type == EventEntry::Type::MOTION) {
342 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700343 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
344 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900345 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700346 // Use identity transform for joystick and position-based (touchpad) events because they
347 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900348 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700349 identityTransform, 1.0f /*globalScaleFactor*/);
yunho.shinf4a80b82020-11-16 21:13:57 +0900350 }
351 }
352
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 if (inputTarget.useDefaultPointerTransform()) {
354 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700356 inputTarget.displayTransform,
357 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358 }
359
360 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700363 std::vector<PointerCoords> pointerCoords;
364 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 // Use the first pointer information to normalize all other pointers. This could be any pointer
367 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // uses the transform for the normalized pointer.
369 const ui::Transform& firstPointerTransform =
370 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
371 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 // Iterate through all pointers in the event to normalize against the first.
374 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
375 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
376 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700377 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700380 // First, apply the current pointer's transform to update the coordinates into
381 // window space.
382 pointerCoords[pointerIndex].transform(currTransform);
383 // Next, apply the inverse transform of the normalized coordinates so the
384 // current coordinates are transformed into the normalized coordinate space.
385 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386 }
387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700388 std::unique_ptr<MotionEntry> combinedMotionEntry =
389 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
390 motionEntry.deviceId, motionEntry.source,
391 motionEntry.displayId, motionEntry.policyFlags,
392 motionEntry.action, motionEntry.actionButton,
393 motionEntry.flags, motionEntry.metaState,
394 motionEntry.buttonState, motionEntry.classification,
395 motionEntry.edgeFlags, motionEntry.xPrecision,
396 motionEntry.yPrecision, motionEntry.xCursorPosition,
397 motionEntry.yCursorPosition, motionEntry.downTime,
398 motionEntry.pointerCount, motionEntry.pointerProperties,
399 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400
401 if (motionEntry.injectionState) {
402 combinedMotionEntry->injectionState = motionEntry.injectionState;
403 combinedMotionEntry->injectionState->refCount += 1;
404 }
405
406 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700407 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700408 firstPointerTransform, inputTarget.displayTransform,
409 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000410 return dispatchEntry;
411}
412
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000413status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
414 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700415 std::unique_ptr<InputChannel> uniqueServerChannel;
416 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
417
418 serverChannel = std::move(uniqueServerChannel);
419 return result;
420}
421
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500422template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000423bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424 if (lhs == nullptr && rhs == nullptr) {
425 return true;
426 }
427 if (lhs == nullptr || rhs == nullptr) {
428 return false;
429 }
430 return *lhs == *rhs;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433sp<IPlatformCompatNative> getCompatService() {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000434 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
435 if (service == nullptr) {
436 ALOGE("Failed to link to compat service");
437 return nullptr;
438 }
439 return interface_cast<IPlatformCompatNative>(service);
440}
441
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000442KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000443 KeyEvent event;
444 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
445 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
446 entry.repeatCount, entry.downTime, entry.eventTime);
447 return event;
448}
449
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000450std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000451 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
452 const sp<IBinder>& token) {
453 for (const auto& it : monitorsByDisplay) {
454 const std::vector<Monitor>& monitors = it.second;
455 for (const Monitor& monitor : monitors) {
456 if (monitor.inputChannel->getConnectionToken() == token) {
457 return monitor.pid;
458 }
459 }
460 }
461 return std::nullopt;
462}
463
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000464bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000465 // Do not keep track of gesture monitors. They receive every event and would disproportionately
466 // affect the statistics.
467 if (connection.monitor) {
468 return false;
469 }
470 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
471 if (!connection.responsive) {
472 return false;
473 }
474 return true;
475}
476
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000477bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000478 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
479 const int32_t& inputEventId = eventEntry.id;
480 if (inputEventId != dispatchEntry.resolvedEventId) {
481 // Event was transmuted
482 return false;
483 }
484 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
485 return false;
486 }
487 // Only track latency for events that originated from hardware
488 if (eventEntry.isSynthesized()) {
489 return false;
490 }
491 const EventEntry::Type& inputEventEntryType = eventEntry.type;
492 if (inputEventEntryType == EventEntry::Type::KEY) {
493 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
494 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
495 return false;
496 }
497 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
498 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
499 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
500 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
501 return false;
502 }
503 } else {
504 // Not a key or a motion
505 return false;
506 }
507 if (!shouldReportMetricsForConnection(connection)) {
508 return false;
509 }
510 return true;
511}
512
Prabir Pradhancef936d2021-07-21 16:17:52 +0000513/**
514 * Connection is responsive if it has no events in the waitQueue that are older than the
515 * current time.
516 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000517bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000518 const nsecs_t currentTime = now();
519 for (const DispatchEntry* entry : connection.waitQueue) {
520 if (entry->timeoutTime < currentTime) {
521 return false;
522 }
523 }
524 return true;
525}
526
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000527} // namespace
528
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529// --- InputDispatcher ---
530
Garfield Tan00f511d2019-06-12 16:55:40 -0700531InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
532 : mPolicy(policy),
533 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700534 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800535 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700536 mAppSwitchSawKeyDown(false),
537 mAppSwitchDueTime(LONG_LONG_MAX),
538 mNextUnblockedEvent(nullptr),
539 mDispatchEnabled(false),
540 mDispatchFrozen(false),
541 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800542 // mInTouchMode will be initialized by the WindowManager to the default device config.
543 // To avoid leaking stack in case that call never comes, and for tests,
544 // initialize it here anyways.
545 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100546 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000547 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800548 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000549 mLatencyAggregator(),
550 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000551 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800553 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554
Yi Kong9b14ac62018-07-17 13:48:38 -0700555 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556
557 policy->getDispatcherConfiguration(&mConfig);
558}
559
560InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000561 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562
Prabir Pradhancef936d2021-07-21 16:17:52 +0000563 resetKeyRepeatLocked();
564 releasePendingEventLocked();
565 drainInboundQueueLocked();
566 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000568 while (!mConnectionsByToken.empty()) {
569 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000570 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
571 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 }
573}
574
chaviw15fab6f2021-06-07 14:15:52 -0500575void InputDispatcher::onFirstRef() {
576 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
577}
578
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700579status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700580 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700581 return ALREADY_EXISTS;
582 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700583 mThread = std::make_unique<InputThread>(
584 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
585 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700586}
587
588status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700589 if (mThread && mThread->isCallingThread()) {
590 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591 return INVALID_OPERATION;
592 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700593 mThread.reset();
594 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595}
596
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597void InputDispatcher::dispatchOnce() {
598 nsecs_t nextWakeupTime = LONG_LONG_MAX;
599 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800600 std::scoped_lock _l(mLock);
601 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602
603 // Run a dispatch loop if there are no pending commands.
604 // The dispatch loop might enqueue commands to run afterwards.
605 if (!haveCommandsLocked()) {
606 dispatchOnceInnerLocked(&nextWakeupTime);
607 }
608
609 // Run all pending commands if there are any.
610 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000611 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 nextWakeupTime = LONG_LONG_MIN;
613 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800614
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700615 // If we are still waiting for ack on some events,
616 // we might have to wake up earlier to check if an app is anr'ing.
617 const nsecs_t nextAnrCheck = processAnrsLocked();
618 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
619
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800620 // We are about to enter an infinitely long sleep, because we have no commands or
621 // pending or queued events
622 if (nextWakeupTime == LONG_LONG_MAX) {
623 mDispatcherEnteredIdle.notify_all();
624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 } // release lock
626
627 // Wait for callback or timeout or wake. (make sure we round up, not down)
628 nsecs_t currentTime = now();
629 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
630 mLooper->pollOnce(timeoutMillis);
631}
632
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700633/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500634 * Raise ANR if there is no focused window.
635 * Before the ANR is raised, do a final state check:
636 * 1. The currently focused application must be the same one we are waiting for.
637 * 2. Ensure we still don't have a focused window.
638 */
639void InputDispatcher::processNoFocusedWindowAnrLocked() {
640 // Check if the application that we are waiting for is still focused.
641 std::shared_ptr<InputApplicationHandle> focusedApplication =
642 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
643 if (focusedApplication == nullptr ||
644 focusedApplication->getApplicationToken() !=
645 mAwaitedFocusedApplication->getApplicationToken()) {
646 // Unexpected because we should have reset the ANR timer when focused application changed
647 ALOGE("Waited for a focused window, but focused application has already changed to %s",
648 focusedApplication->getName().c_str());
649 return; // The focused application has changed.
650 }
651
chaviw98318de2021-05-19 16:45:23 -0500652 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500653 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
654 if (focusedWindowHandle != nullptr) {
655 return; // We now have a focused window. No need for ANR.
656 }
657 onAnrLocked(mAwaitedFocusedApplication);
658}
659
660/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700661 * Check if any of the connections' wait queues have events that are too old.
662 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
663 * Return the time at which we should wake up next.
664 */
665nsecs_t InputDispatcher::processAnrsLocked() {
666 const nsecs_t currentTime = now();
667 nsecs_t nextAnrCheck = LONG_LONG_MAX;
668 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
669 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
670 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500671 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700672 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500673 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700674 return LONG_LONG_MIN;
675 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500676 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700677 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
678 }
679 }
680
681 // Check if any connection ANRs are due
682 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
683 if (currentTime < nextAnrCheck) { // most likely scenario
684 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
685 }
686
687 // If we reached here, we have an unresponsive connection.
688 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
689 if (connection == nullptr) {
690 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
691 return nextAnrCheck;
692 }
693 connection->responsive = false;
694 // Stop waking up for this unresponsive connection
695 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000696 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700697 return LONG_LONG_MIN;
698}
699
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500700std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500701 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700702 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500703 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500705 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706}
707
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
709 nsecs_t currentTime = now();
710
Jeff Browndc5992e2014-04-11 01:27:26 -0700711 // Reset the key repeat timer whenever normal dispatch is suspended while the
712 // device is in a non-interactive state. This is to ensure that we abort a key
713 // repeat if the device is just coming out of sleep.
714 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 resetKeyRepeatLocked();
716 }
717
718 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
719 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100720 if (DEBUG_FOCUS) {
721 ALOGD("Dispatch frozen. Waiting some more.");
722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 return;
724 }
725
726 // Optimize latency of app switches.
727 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
728 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
729 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
730 if (mAppSwitchDueTime < *nextWakeupTime) {
731 *nextWakeupTime = mAppSwitchDueTime;
732 }
733
734 // Ready to start a new event.
735 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700737 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 if (isAppSwitchDue) {
739 // The inbound queue is empty so the app switch key we were waiting
740 // for will never arrive. Stop waiting for it.
741 resetPendingAppSwitchLocked(false);
742 isAppSwitchDue = false;
743 }
744
745 // Synthesize a key repeat if appropriate.
746 if (mKeyRepeatState.lastKeyEntry) {
747 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
748 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
749 } else {
750 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
751 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
752 }
753 }
754 }
755
756 // Nothing to do if there is no pending event.
757 if (!mPendingEvent) {
758 return;
759 }
760 } else {
761 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700762 mPendingEvent = mInboundQueue.front();
763 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 traceInboundQueueLengthLocked();
765 }
766
767 // Poke user activity for this event.
768 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700769 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 }
772
773 // Now we have an event to dispatch.
774 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700775 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700777 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700779 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 }
783
784 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787
788 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700789 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700790 const ConfigurationChangedEntry& typedEntry =
791 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700793 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 break;
795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700797 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700798 const DeviceResetEntry& typedEntry =
799 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700800 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700801 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 break;
803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100805 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700806 std::shared_ptr<FocusEntry> typedEntry =
807 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100808 dispatchFocusLocked(currentTime, typedEntry);
809 done = true;
810 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
811 break;
812 }
813
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700814 case EventEntry::Type::TOUCH_MODE_CHANGED: {
815 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
816 dispatchTouchModeChangeLocked(currentTime, typedEntry);
817 done = true;
818 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
819 break;
820 }
821
Prabir Pradhan99987712020-11-10 18:43:05 -0800822 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
823 const auto typedEntry =
824 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
825 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
826 done = true;
827 break;
828 }
829
arthurhungb89ccb02020-12-30 16:19:01 +0800830 case EventEntry::Type::DRAG: {
831 std::shared_ptr<DragEntry> typedEntry =
832 std::static_pointer_cast<DragEntry>(mPendingEvent);
833 dispatchDragLocked(currentTime, typedEntry);
834 done = true;
835 break;
836 }
837
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700838 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700840 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700841 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700842 resetPendingAppSwitchLocked(true);
843 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700844 } else if (dropReason == DropReason::NOT_DROPPED) {
845 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 }
847 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700848 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700849 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
852 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700853 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700854 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 break;
856 }
857
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700858 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700859 std::shared_ptr<MotionEntry> motionEntry =
860 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
862 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700864 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
868 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700870 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
Chris Yef59a2f42020-10-16 12:55:26 -0700873
874 case EventEntry::Type::SENSOR: {
875 std::shared_ptr<SensorEntry> sensorEntry =
876 std::static_pointer_cast<SensorEntry>(mPendingEvent);
877 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
878 dropReason = DropReason::APP_SWITCH;
879 }
880 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
881 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
882 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
883 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
884 dropReason = DropReason::STALE;
885 }
886 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
887 done = true;
888 break;
889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 }
891
892 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 }
Michael Wright3a981722015-06-10 15:26:13 +0100896 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897
898 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901}
902
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700903/**
904 * Return true if the events preceding this incoming motion event should be dropped
905 * Return false otherwise (the default behaviour)
906 */
907bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700908 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700909 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700910
911 // Optimize case where the current application is unresponsive and the user
912 // decides to touch a window in a different application.
913 // If the application takes too long to catch up then we drop all events preceding
914 // the touch into the other window.
915 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700916 int32_t displayId = motionEntry.displayId;
917 int32_t x = static_cast<int32_t>(
918 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
919 int32_t y = static_cast<int32_t>(
920 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500921 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700922 findTouchedWindowAtLocked(displayId, x, y, nullptr);
923 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700924 touchedWindowHandle->getApplicationToken() !=
925 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 ALOGI("Pruning input queue because user touched a different application while waiting "
928 "for %s",
929 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 return true;
931 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932
933 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700934 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700936 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000937 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 // This monitor could take more input. Drop all events preceding this
939 // event, so that gesture monitor could get a chance to receive the stream
940 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
941 "responsive gesture monitor that may handle the event",
942 mAwaitedFocusedApplication->getName().c_str());
943 return true;
944 }
945 }
946 }
947
948 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
949 // yet been processed by some connections, the dispatcher will wait for these motion
950 // events to be processed before dispatching the key event. This is because these motion events
951 // may cause a new window to be launched, which the user might expect to receive focus.
952 // To prevent waiting forever for such events, just send the key to the currently focused window
953 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
954 ALOGD("Received a new pointer down event, stop waiting for events to process and "
955 "just send the pending key event to the focused window.");
956 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700957 }
958 return false;
959}
960
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700961bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700962 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700963 mInboundQueue.push_back(std::move(newEntry));
964 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 traceInboundQueueLengthLocked();
966
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700968 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 // Optimize app switch latency.
970 // If the application takes too long to catch up then we drop all events preceding
971 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700972 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700974 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700976 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000978 if (DEBUG_APP_SWITCH) {
979 ALOGD("App switch is pending!");
980 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700981 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 mAppSwitchSawKeyDown = false;
983 needWake = true;
984 }
985 }
986 }
987 break;
988 }
989
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700990 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
992 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700993 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100997 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700998 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
999 break;
1000 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001001 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001002 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001003 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001004 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001005 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1006 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001007 // nothing to do
1008 break;
1009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
1012 return needWake;
1013}
1014
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001015void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001016 // Do not store sensor event in recent queue to avoid flooding the queue.
1017 if (entry->type != EventEntry::Type::SENSOR) {
1018 mRecentQueue.push_back(entry);
1019 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001020 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001021 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
1023}
1024
chaviw98318de2021-05-19 16:45:23 -05001025sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1026 int32_t y, TouchState* touchState,
1027 bool addOutsideTargets,
1028 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001029 if (addOutsideTargets && touchState == nullptr) {
1030 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001033 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1034 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001035 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001036 continue;
1037 }
chaviw98318de2021-05-19 16:45:23 -05001038 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001040 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041
1042 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001043 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1044 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1045 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1047 // Found window.
1048 return windowHandle;
1049 }
1050 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001051
chaviw98318de2021-05-19 16:45:23 -05001052 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001053 touchState->addOrUpdateWindow(windowHandle,
1054 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1055 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
1059 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001060 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061}
1062
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001063void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 const char* reason;
1065 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001066 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001067 if (DEBUG_INBOUND_EVENT_DETAILS) {
1068 ALOGD("Dropped event because policy consumed it.");
1069 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 reason = "inbound event was dropped because the policy consumed it";
1071 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001072 case DropReason::DISABLED:
1073 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 ALOGI("Dropped event because input dispatch is disabled.");
1075 }
1076 reason = "inbound event was dropped because input dispatch is disabled";
1077 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001078 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 ALOGI("Dropped event because of pending overdue app switch.");
1080 reason = "inbound event was dropped because of pending overdue app switch";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 ALOGI("Dropped event because the current application is not responding and the user "
1084 "has started interacting with a different application.");
1085 reason = "inbound event was dropped because the current application is not responding "
1086 "and the user has started interacting with a different application";
1087 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because it is stale.");
1090 reason = "inbound event was dropped because it is stale";
1091 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001092 case DropReason::NO_POINTER_CAPTURE:
1093 ALOGI("Dropped event because there is no window with Pointer Capture.");
1094 reason = "inbound event was dropped because there is no window with Pointer Capture";
1095 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 case DropReason::NOT_DROPPED: {
1097 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
1101
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001103 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1105 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001108 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1110 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1112 synthesizeCancelationEventsForAllConnectionsLocked(options);
1113 } else {
1114 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1115 synthesizeCancelationEventsForAllConnectionsLocked(options);
1116 }
1117 break;
1118 }
Chris Yef59a2f42020-10-16 12:55:26 -07001119 case EventEntry::Type::SENSOR: {
1120 break;
1121 }
arthurhungb89ccb02020-12-30 16:19:01 +08001122 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1123 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001124 break;
1125 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001126 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001127 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001128 case EventEntry::Type::CONFIGURATION_CHANGED:
1129 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001130 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001131 break;
1132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 }
1134}
1135
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001136static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1138 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139}
1140
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001141bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1142 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1143 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1144 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145}
1146
1147bool InputDispatcher::isAppSwitchPendingLocked() {
1148 return mAppSwitchDueTime != LONG_LONG_MAX;
1149}
1150
1151void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1152 mAppSwitchDueTime = LONG_LONG_MAX;
1153
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001154 if (DEBUG_APP_SWITCH) {
1155 if (handled) {
1156 ALOGD("App switch has arrived.");
1157 } else {
1158 ALOGD("App switch was abandoned.");
1159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161}
1162
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001164 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165}
1166
Prabir Pradhancef936d2021-07-21 16:17:52 +00001167bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001168 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 return false;
1170 }
1171
1172 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001173 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001174 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001175 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1176 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001177 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 return true;
1179}
1180
Prabir Pradhancef936d2021-07-21 16:17:52 +00001181void InputDispatcher::postCommandLocked(Command&& command) {
1182 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183}
1184
1185void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001186 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001187 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001188 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 releaseInboundEventLocked(entry);
1190 }
1191 traceInboundQueueLengthLocked();
1192}
1193
1194void InputDispatcher::releasePendingEventLocked() {
1195 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001197 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 }
1199}
1200
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001203 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001204 if (DEBUG_DISPATCH_CYCLE) {
1205 ALOGD("Injected inbound event was dropped.");
1206 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
1209 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001210 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 }
1212 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213}
1214
1215void InputDispatcher::resetKeyRepeatLocked() {
1216 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001217 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
1219}
1220
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001221std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1222 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223
Michael Wright2e732952014-09-24 13:26:59 -07001224 uint32_t policyFlags = entry->policyFlags &
1225 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227 std::shared_ptr<KeyEntry> newEntry =
1228 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1229 entry->source, entry->displayId, policyFlags, entry->action,
1230 entry->flags, entry->keyCode, entry->scanCode,
1231 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233 newEntry->syntheticRepeat = true;
1234 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237}
1238
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001240 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001241 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1242 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244
1245 // Reset key repeating in case a keyboard device was added or removed or something.
1246 resetKeyRepeatLocked();
1247
1248 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001249 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1250 scoped_unlock unlock(mLock);
1251 mPolicy->notifyConfigurationChanged(eventTime);
1252 };
1253 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 return true;
1255}
1256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1258 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001259 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1260 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1261 entry.deviceId);
1262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263
liushenxiang42232912021-05-21 20:24:09 +08001264 // Reset key repeating in case a keyboard device was disabled or enabled.
1265 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1266 resetKeyRepeatLocked();
1267 }
1268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001270 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 synthesizeCancelationEventsForAllConnectionsLocked(options);
1272 return true;
1273}
1274
Vishnu Nairad321cd2020-08-20 16:40:21 -07001275void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001276 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001277 if (mPendingEvent != nullptr) {
1278 // Move the pending event to the front of the queue. This will give the chance
1279 // for the pending event to get dispatched to the newly focused window
1280 mInboundQueue.push_front(mPendingEvent);
1281 mPendingEvent = nullptr;
1282 }
1283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 std::unique_ptr<FocusEntry> focusEntry =
1285 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1286 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001287
1288 // This event should go to the front of the queue, but behind all other focus events
1289 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001291 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 [](const std::shared_ptr<EventEntry>& event) {
1293 return event->type == EventEntry::Type::FOCUS;
1294 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001295
1296 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001297 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001298}
1299
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001301 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001302 if (channel == nullptr) {
1303 return; // Window has gone away
1304 }
1305 InputTarget target;
1306 target.inputChannel = channel;
1307 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1308 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001309 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1310 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001311 std::string reason = std::string("reason=").append(entry->reason);
1312 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001313 dispatchEventLocked(currentTime, entry, {target});
1314}
1315
Prabir Pradhan99987712020-11-10 18:43:05 -08001316void InputDispatcher::dispatchPointerCaptureChangedLocked(
1317 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1318 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001319 dropReason = DropReason::NOT_DROPPED;
1320
Prabir Pradhan99987712020-11-10 18:43:05 -08001321 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001322 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001323
1324 if (entry->pointerCaptureRequest.enable) {
1325 // Enable Pointer Capture.
1326 if (haveWindowWithPointerCapture &&
1327 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1328 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1329 "to the window.");
1330 }
1331 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 // This can happen if a window requests capture and immediately releases capture.
1333 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001334 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001335 return;
1336 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001337 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1338 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1339 return;
1340 }
1341
Vishnu Nairc519ff72021-01-21 08:23:08 -08001342 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001343 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1344 mWindowTokenWithPointerCapture = token;
1345 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001346 // Disable Pointer Capture.
1347 // We do not check if the sequence number matches for requests to disable Pointer Capture
1348 // for two reasons:
1349 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1350 // to disable capture with the same sequence number: one generated by
1351 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1352 // Capture being disabled in InputReader.
1353 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1354 // actual Pointer Capture state that affects events being generated by input devices is
1355 // in InputReader.
1356 if (!haveWindowWithPointerCapture) {
1357 // Pointer capture was already forcefully disabled because of focus change.
1358 dropReason = DropReason::NOT_DROPPED;
1359 return;
1360 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001361 token = mWindowTokenWithPointerCapture;
1362 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001363 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001364 setPointerCaptureLocked(false);
1365 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001366 }
1367
1368 auto channel = getInputChannelLocked(token);
1369 if (channel == nullptr) {
1370 // Window has gone away, clean up Pointer Capture state.
1371 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001372 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001373 setPointerCaptureLocked(false);
1374 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 return;
1376 }
1377 InputTarget target;
1378 target.inputChannel = channel;
1379 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1380 entry->dispatchInProgress = true;
1381 dispatchEventLocked(currentTime, entry, {target});
1382
1383 dropReason = DropReason::NOT_DROPPED;
1384}
1385
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001386void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1387 const std::shared_ptr<TouchModeEntry>& entry) {
1388 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1389 getWindowHandlesLocked(mFocusedDisplayId);
1390 if (windowHandles.empty()) {
1391 return;
1392 }
1393 const std::vector<InputTarget> inputTargets =
1394 getInputTargetsFromWindowHandlesLocked(windowHandles);
1395 if (inputTargets.empty()) {
1396 return;
1397 }
1398 entry->dispatchInProgress = true;
1399 dispatchEventLocked(currentTime, entry, inputTargets);
1400}
1401
1402std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1403 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1404 std::vector<InputTarget> inputTargets;
1405 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1406 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1407 const sp<IBinder>& token = handle->getToken();
1408 if (token == nullptr) {
1409 continue;
1410 }
1411 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1412 if (channel == nullptr) {
1413 continue; // Window has gone away
1414 }
1415 InputTarget target;
1416 target.inputChannel = channel;
1417 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1418 inputTargets.push_back(target);
1419 }
1420 return inputTargets;
1421}
1422
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001424 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001426 if (!entry->dispatchInProgress) {
1427 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1428 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1429 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1430 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001431 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 // We have seen two identical key downs in a row which indicates that the device
1433 // driver is automatically generating key repeats itself. We take note of the
1434 // repeat here, but we disable our own next key repeat timer since it is clear that
1435 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001436 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1437 // Make sure we don't get key down from a different device. If a different
1438 // device Id has same key pressed down, the new device Id will replace the
1439 // current one to hold the key repeat with repeat count reset.
1440 // In the future when got a KEY_UP on the device id, drop it and do not
1441 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1443 resetKeyRepeatLocked();
1444 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1445 } else {
1446 // Not a repeat. Save key down state in case we do see a repeat later.
1447 resetKeyRepeatLocked();
1448 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1449 }
1450 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001451 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1452 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001454 if (DEBUG_INBOUND_EVENT_DETAILS) {
1455 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1456 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 resetKeyRepeatLocked();
1459 }
1460
1461 if (entry->repeatCount == 1) {
1462 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1463 } else {
1464 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1465 }
1466
1467 entry->dispatchInProgress = true;
1468
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 }
1471
1472 // Handle case where the policy asked us to try again later last time.
1473 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1474 if (currentTime < entry->interceptKeyWakeupTime) {
1475 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1476 *nextWakeupTime = entry->interceptKeyWakeupTime;
1477 }
1478 return false; // wait until next wakeup
1479 }
1480 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1481 entry->interceptKeyWakeupTime = 0;
1482 }
1483
1484 // Give the policy a chance to intercept the key.
1485 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1486 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001487 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001488 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001489
1490 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1491 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1492 };
1493 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 return false; // wait for the command to run
1495 } else {
1496 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1497 }
1498 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001499 if (*dropReason == DropReason::NOT_DROPPED) {
1500 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502 }
1503
1504 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001505 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001506 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001507 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1508 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001509 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 return true;
1511 }
1512
1513 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001514 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001515 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001516 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001517 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 return false;
1519 }
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001522 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 return true;
1524 }
1525
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001526 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001527 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528
1529 // Dispatch the key.
1530 dispatchEventLocked(currentTime, entry, inputTargets);
1531 return true;
1532}
1533
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001534void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001535 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1536 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1537 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1538 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1539 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1540 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1541 entry.metaState, entry.repeatCount, entry.downTime);
1542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543}
1544
Prabir Pradhancef936d2021-07-21 16:17:52 +00001545void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1546 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001547 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001548 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1549 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1550 "source=0x%x, sensorType=%s",
1551 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001552 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001553 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001554 auto command = [this, entry]() REQUIRES(mLock) {
1555 scoped_unlock unlock(mLock);
1556
1557 if (entry->accuracyChanged) {
1558 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1559 }
1560 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1561 entry->hwTimestamp, entry->values);
1562 };
1563 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001564}
1565
1566bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001567 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1568 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001569 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001570 }
Chris Yef59a2f42020-10-16 12:55:26 -07001571 { // acquire lock
1572 std::scoped_lock _l(mLock);
1573
1574 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1575 std::shared_ptr<EventEntry> entry = *it;
1576 if (entry->type == EventEntry::Type::SENSOR) {
1577 it = mInboundQueue.erase(it);
1578 releaseInboundEventLocked(entry);
1579 }
1580 }
1581 }
1582 return true;
1583}
1584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001586 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001587 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001589 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 entry->dispatchInProgress = true;
1591
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001592 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594
1595 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001596 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001597 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001598 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1599 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 return true;
1601 }
1602
1603 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1604
1605 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001606 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607
1608 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001609 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 if (isPointerEvent) {
1611 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001613 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 } else {
1616 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001617 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001618 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 return false;
1622 }
1623
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001624 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001625 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001626 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1627 return true;
1628 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001629 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001630 CancelationOptions::Mode mode(isPointerEvent
1631 ? CancelationOptions::CANCEL_POINTER_EVENTS
1632 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1633 CancelationOptions options(mode, "input event injection failed");
1634 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 return true;
1636 }
1637
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001638 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001639 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640
1641 // Dispatch the motion.
1642 if (conflictingPointerActions) {
1643 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 synthesizeCancelationEventsForAllConnectionsLocked(options);
1646 }
1647 dispatchEventLocked(currentTime, entry, inputTargets);
1648 return true;
1649}
1650
chaviw98318de2021-05-19 16:45:23 -05001651void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001652 bool isExiting, const MotionEntry& motionEntry) {
1653 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1654 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1655 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1656 PointerCoords pointerCoords;
1657 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1658 pointerCoords.transform(windowHandle->getInfo()->transform);
1659
1660 std::unique_ptr<DragEntry> dragEntry =
1661 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1662 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1663 pointerCoords.getY());
1664
1665 enqueueInboundEventLocked(std::move(dragEntry));
1666}
1667
1668void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1669 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1670 if (channel == nullptr) {
1671 return; // Window has gone away
1672 }
1673 InputTarget target;
1674 target.inputChannel = channel;
1675 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1676 entry->dispatchInProgress = true;
1677 dispatchEventLocked(currentTime, entry, {target});
1678}
1679
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001680void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001681 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1682 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1683 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001684 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001685 "metaState=0x%x, buttonState=0x%x,"
1686 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1687 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001688 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1689 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1690 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001692 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1693 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1694 "x=%f, y=%f, pressure=%f, size=%f, "
1695 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1696 "orientation=%f",
1697 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1698 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1699 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1700 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1701 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1702 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1703 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1704 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1705 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1706 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709}
1710
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001711void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1712 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001713 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001714 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001715 if (DEBUG_DISPATCH_CYCLE) {
1716 ALOGD("dispatchEventToCurrentInputTargets");
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001719 updateInteractionTokensLocked(*eventEntry, inputTargets);
1720
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1722
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001723 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001725 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001726 sp<Connection> connection =
1727 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001728 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001729 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001731 if (DEBUG_FOCUS) {
1732 ALOGD("Dropping event delivery to target with channel '%s' because it "
1733 "is no longer registered with the input dispatcher.",
1734 inputTarget.inputChannel->getName().c_str());
1735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737 }
1738}
1739
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001740void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1741 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1742 // If the policy decides to close the app, we will get a channel removal event via
1743 // unregisterInputChannel, and will clean up the connection that way. We are already not
1744 // sending new pointers to the connection when it blocked, but focused events will continue to
1745 // pile up.
1746 ALOGW("Canceling events for %s because it is unresponsive",
1747 connection->inputChannel->getName().c_str());
1748 if (connection->status == Connection::STATUS_NORMAL) {
1749 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1750 "application not responding");
1751 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 }
1753}
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001756 if (DEBUG_FOCUS) {
1757 ALOGD("Resetting ANR timeouts.");
1758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759
1760 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001761 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001762 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763}
1764
Tiger Huang721e26f2018-07-24 22:26:19 +08001765/**
1766 * Get the display id that the given event should go to. If this event specifies a valid display id,
1767 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1768 * Focused display is the display that the user most recently interacted with.
1769 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001770int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001771 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001772 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001773 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001774 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1775 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001776 break;
1777 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001778 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001779 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1780 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001781 break;
1782 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001783 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001784 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001785 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001786 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001787 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001788 case EventEntry::Type::SENSOR:
1789 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001790 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 return ADISPLAY_ID_NONE;
1792 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001793 }
1794 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1795}
1796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1798 const char* focusedWindowName) {
1799 if (mAnrTracker.empty()) {
1800 // already processed all events that we waited for
1801 mKeyIsWaitingForEventsTimeout = std::nullopt;
1802 return false;
1803 }
1804
1805 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1806 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001807 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001808 mKeyIsWaitingForEventsTimeout = currentTime +
1809 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1810 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811 return true;
1812 }
1813
1814 // We still have pending events, and already started the timer
1815 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1816 return true; // Still waiting
1817 }
1818
1819 // Waited too long, and some connection still hasn't processed all motions
1820 // Just send the key to the focused window
1821 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1822 focusedWindowName);
1823 mKeyIsWaitingForEventsTimeout = std::nullopt;
1824 return false;
1825}
1826
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1828 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1829 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001830 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831
Tiger Huang721e26f2018-07-24 22:26:19 +08001832 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001833 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001834 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001835 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1836
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 // If there is no currently focused window and no focused application
1838 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1840 ALOGI("Dropping %s event because there is no focused window or focused application in "
1841 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001842 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
1845
Vishnu Nair062a8672021-09-03 16:07:44 -07001846 // Drop key events if requested by input feature
1847 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1848 return InputEventInjectionResult::FAILED;
1849 }
1850
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001851 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1852 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1853 // start interacting with another application via touch (app switch). This code can be removed
1854 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1855 // an app is expected to have a focused window.
1856 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1857 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1858 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001859 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1860 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1861 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001862 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001863 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001864 ALOGW("Waiting because no window has focus but %s may eventually add a "
1865 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001866 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001869 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1870 // Already raised ANR. Drop the event
1871 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001872 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001873 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001874 } else {
1875 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001877 }
1878 }
1879
1880 // we have a valid, non-null focused window
1881 resetNoFocusedWindowTimeoutLocked();
1882
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001884 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001885 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
1887
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888 if (focusedWindowHandle->getInfo()->paused) {
1889 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001890 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001891 }
1892
1893 // If the event is a key event, then we must wait for all previous events to
1894 // complete before delivering it because previous events may have the
1895 // side-effect of transferring focus to a different window and we want to
1896 // ensure that the following keys are sent to the new window.
1897 //
1898 // Suppose the user touches a button in a window then immediately presses "A".
1899 // If the button causes a pop-up window to appear then we want to ensure that
1900 // the "A" key is delivered to the new pop-up window. This is because users
1901 // often anticipate pending UI changes when typing on a keyboard.
1902 // To obtain this behavior, we must serialize key events with respect to all
1903 // prior input events.
1904 if (entry.type == EventEntry::Type::KEY) {
1905 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1906 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910
1911 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001912 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001913 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1914 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915
1916 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918}
1919
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001920/**
1921 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1922 * that are currently unresponsive.
1923 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001924std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1925 const std::vector<Monitor>& monitors) const {
1926 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001928 [this](const Monitor& monitor) REQUIRES(mLock) {
1929 sp<Connection> connection =
1930 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 if (connection == nullptr) {
1932 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001933 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 return false;
1935 }
1936 if (!connection->responsive) {
1937 ALOGW("Unresponsive monitor %s will not get the new gesture",
1938 connection->inputChannel->getName().c_str());
1939 return false;
1940 }
1941 return true;
1942 });
1943 return responsiveMonitors;
1944}
1945
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001946InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1947 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1948 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001949 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 enum InjectionPermission {
1951 INJECTION_PERMISSION_UNKNOWN,
1952 INJECTION_PERMISSION_GRANTED,
1953 INJECTION_PERMISSION_DENIED
1954 };
1955
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 // For security reasons, we defer updating the touch state until we are sure that
1957 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001958 int32_t displayId = entry.displayId;
1959 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1961
1962 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001963 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001965 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1966 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001968 // Copy current touch state into tempTouchState.
1969 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1970 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001971 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001972 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001973 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1974 mTouchStatesByDisplay.find(displayId);
1975 if (oldStateIt != mTouchStatesByDisplay.end()) {
1976 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001977 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001978 }
1979
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001980 bool isSplit = tempTouchState.split;
1981 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1982 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1983 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001984 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1985 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1986 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1987 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1988 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 bool wrongDevice = false;
1991 if (newGesture) {
1992 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001993 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001994 ALOGI("Dropping event because a pointer for a different device is already down "
1995 "in display %" PRId32,
1996 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001997 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001998 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 switchedDevice = false;
2000 wrongDevice = true;
2001 goto Failed;
2002 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 tempTouchState.reset();
2004 tempTouchState.down = down;
2005 tempTouchState.deviceId = entry.deviceId;
2006 tempTouchState.source = entry.source;
2007 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002009 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002010 ALOGI("Dropping move event because a pointer for a different device is already active "
2011 "in display %" PRId32,
2012 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002013 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002014 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002015 switchedDevice = false;
2016 wrongDevice = true;
2017 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
2019
2020 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2021 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2022
Garfield Tan00f511d2019-06-12 16:55:40 -07002023 int32_t x;
2024 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002026 // Always dispatch mouse events to cursor position.
2027 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002028 x = int32_t(entry.xCursorPosition);
2029 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002030 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2032 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002033 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002034 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002035 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2036 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002037
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002039 if (newTouchedWindowHandle != nullptr &&
2040 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002041 // New window supports splitting, but we should never split mouse events.
2042 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 } else if (isSplit) {
2044 // New window does not support splitting but we have already split events.
2045 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002046 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048
2049 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002050 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002052 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 }
2054
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002055 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2056 ALOGI("Not sending touch event to %s because it is paused",
2057 newTouchedWindowHandle->getName().c_str());
2058 newTouchedWindowHandle = nullptr;
2059 }
2060
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002061 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002062 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002063 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2064 if (!isResponsive) {
2065 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002066 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2067 newTouchedWindowHandle = nullptr;
2068 }
2069 }
2070
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002071 // Drop events that can't be trusted due to occlusion
2072 if (newTouchedWindowHandle != nullptr &&
2073 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2074 TouchOcclusionInfo occlusionInfo =
2075 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002076 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002077 if (DEBUG_TOUCH_OCCLUSION) {
2078 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2079 for (const auto& log : occlusionInfo.debugInfo) {
2080 ALOGD("%s", log.c_str());
2081 }
2082 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002083 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002084 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2085 ALOGW("Dropping untrusted touch event due to %s/%d",
2086 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2087 newTouchedWindowHandle = nullptr;
2088 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002089 }
2090 }
2091
Vishnu Nair062a8672021-09-03 16:07:44 -07002092 // Drop touch events if requested by input feature
2093 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2094 newTouchedWindowHandle = nullptr;
2095 }
2096
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002097 const std::vector<Monitor> newGestureMonitors = isDown
2098 ? selectResponsiveMonitorsLocked(
2099 getValueByKey(mGestureMonitorsByDisplay, displayId))
2100 : std::vector<Monitor>{};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002101
Michael Wright3dd60e22019-03-27 22:06:44 +00002102 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2103 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 "(%d, %d) in display %" PRId32 ".",
2105 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002106 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002107 goto Failed;
2108 }
2109
2110 if (newTouchedWindowHandle != nullptr) {
2111 // Set target flags.
2112 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2113 if (isSplit) {
2114 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002116 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2117 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2118 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2119 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2120 }
2121
2122 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002123 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2124 newHoverWindowHandle = nullptr;
2125 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002126 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002127 }
2128
2129 // Update the temporary touch state.
2130 BitSet32 pointerIds;
2131 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002132 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002133 pointerIds.markBit(pointerId);
2134 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002135 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002138 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 } else {
2140 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2141
2142 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002143 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002144 if (DEBUG_FOCUS) {
2145 ALOGD("Dropping event because the pointer is not down or we previously "
2146 "dropped the pointer down event in display %" PRId32,
2147 displayId);
2148 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002149 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 goto Failed;
2151 }
2152
arthurhung6d4bed92021-03-17 11:59:33 +08002153 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002154
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002156 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002157 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002158 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2159 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160
chaviw98318de2021-05-19 16:45:23 -05002161 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002162 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002163 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002164
2165 // Drop touch events if requested by input feature
2166 if (newTouchedWindowHandle != nullptr &&
2167 shouldDropInput(entry, newTouchedWindowHandle)) {
2168 newTouchedWindowHandle = nullptr;
2169 }
2170
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002171 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2172 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002173 if (DEBUG_FOCUS) {
2174 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2175 oldTouchedWindowHandle->getName().c_str(),
2176 newTouchedWindowHandle->getName().c_str(), displayId);
2177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002179 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2180 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2181 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182
2183 // Make a slippery entrance into the new window.
2184 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2185 isSplit = true;
2186 }
2187
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 int32_t targetFlags =
2189 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 if (isSplit) {
2191 targetFlags |= InputTarget::FLAG_SPLIT;
2192 }
2193 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2194 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002195 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2196 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198
2199 BitSet32 pointerIds;
2200 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002201 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002203 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 }
2205 }
2206 }
2207
2208 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002209 // Let the previous window know that the hover sequence is over, unless we already did it
2210 // when dispatching it as is to newTouchedWindowHandle.
2211 if (mLastHoverWindowHandle != nullptr &&
2212 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2213 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002214 if (DEBUG_HOVER) {
2215 ALOGD("Sending hover exit event to window %s.",
2216 mLastHoverWindowHandle->getName().c_str());
2217 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2219 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 }
2221
Garfield Tandf26e862020-07-01 20:18:19 -07002222 // Let the new window know that the hover sequence is starting, unless we already did it
2223 // when dispatching it as is to newTouchedWindowHandle.
2224 if (newHoverWindowHandle != nullptr &&
2225 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2226 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002227 if (DEBUG_HOVER) {
2228 ALOGD("Sending hover enter event to window %s.",
2229 newHoverWindowHandle->getName().c_str());
2230 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2232 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2233 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235 }
2236
2237 // Check permission to inject into all touched foreground windows and ensure there
2238 // is at least one touched foreground window.
2239 {
2240 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002241 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2243 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002244 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002245 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 injectionPermission = INJECTION_PERMISSION_DENIED;
2247 goto Failed;
2248 }
2249 }
2250 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002252 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002253 ALOGI("Dropping event because there is no touched foreground window in display "
2254 "%" PRId32 " or gesture monitor to receive it.",
2255 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002256 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 goto Failed;
2258 }
2259
2260 // Permission granted to injection into all touched foreground windows.
2261 injectionPermission = INJECTION_PERMISSION_GRANTED;
2262 }
2263
2264 // Check whether windows listening for outside touches are owned by the same UID. If it is
2265 // set the policy flag that we will not reveal coordinate information to this window.
2266 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002267 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002268 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002269 if (foregroundWindowHandle) {
2270 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002271 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002272 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002273 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2274 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2275 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 InputTarget::FLAG_ZERO_COORDS,
2277 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
2280 }
2281 }
2282 }
2283
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 // If this is the first pointer going down and the touched window has a wallpaper
2285 // then also add the touched wallpaper windows so they are locked in for the duration
2286 // of the touch gesture.
2287 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2288 // engine only supports touch events. We would need to add a mechanism similar
2289 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2290 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002291 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002292 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002293 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002294 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002295 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002296 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2297 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002299 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002300 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 .addOrUpdateWindow(windowHandle,
2302 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2303 InputTarget::
2304 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2305 InputTarget::FLAG_DISPATCH_AS_IS,
2306 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 }
2309 }
2310 }
2311
2312 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002313 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002315 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002317 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 }
2319
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002320 for (const auto& monitor : tempTouchState.gestureMonitors) {
2321 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002322 }
2323
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 // Drop the outside or hover touch windows since we will not care about them
2325 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002326 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
2328Failed:
2329 // Check injection permission once and for all.
2330 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002331 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 injectionPermission = INJECTION_PERMISSION_GRANTED;
2333 } else {
2334 injectionPermission = INJECTION_PERMISSION_DENIED;
2335 }
2336 }
2337
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002338 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2339 return injectionResult;
2340 }
2341
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002343 if (!wrongDevice) {
2344 if (switchedDevice) {
2345 if (DEBUG_FOCUS) {
2346 ALOGD("Conflicting pointer actions: Switched to a different device.");
2347 }
2348 *outConflictingPointerActions = true;
2349 }
2350
2351 if (isHoverAction) {
2352 // Started hovering, therefore no longer down.
2353 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002354 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002355 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2356 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 *outConflictingPointerActions = true;
2359 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002360 tempTouchState.reset();
2361 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2362 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2363 tempTouchState.deviceId = entry.deviceId;
2364 tempTouchState.source = entry.source;
2365 tempTouchState.displayId = displayId;
2366 }
2367 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2368 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2369 // All pointers up or canceled.
2370 tempTouchState.reset();
2371 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2372 // First pointer went down.
2373 if (oldState && oldState->down) {
2374 if (DEBUG_FOCUS) {
2375 ALOGD("Conflicting pointer actions: Down received while already down.");
2376 }
2377 *outConflictingPointerActions = true;
2378 }
2379 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2380 // One pointer went up.
2381 if (isSplit) {
2382 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2383 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002385 for (size_t i = 0; i < tempTouchState.windows.size();) {
2386 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2387 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2388 touchedWindow.pointerIds.clearBit(pointerId);
2389 if (touchedWindow.pointerIds.isEmpty()) {
2390 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2391 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002396 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002397 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002398
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002399 // Save changes unless the action was scroll in which case the temporary touch
2400 // state was only valid for this one action.
2401 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2402 if (tempTouchState.displayId >= 0) {
2403 mTouchStatesByDisplay[displayId] = tempTouchState;
2404 } else {
2405 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002409 // Update hover state.
2410 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 }
2412
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 return injectionResult;
2414}
2415
arthurhung6d4bed92021-03-17 11:59:33 +08002416void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002417 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002418 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002419 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002420 if (dropWindow) {
2421 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002422 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002423 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002424 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002425 }
2426 mDragState.reset();
2427}
2428
2429void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2430 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002431 return;
2432 }
2433
arthurhung6d4bed92021-03-17 11:59:33 +08002434 if (!mDragState->isStartDrag) {
2435 mDragState->isStartDrag = true;
2436 mDragState->isStylusButtonDownAtStart =
2437 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2438 }
2439
arthurhungb89ccb02020-12-30 16:19:01 +08002440 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2441 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2442 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2443 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002444 // Handle the special case : stylus button no longer pressed.
2445 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2446 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2447 finishDragAndDrop(entry.displayId, x, y);
2448 return;
2449 }
2450
chaviw98318de2021-05-19 16:45:23 -05002451 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002452 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002453 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002454 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002455 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2456 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2457 if (mDragState->dragHoverWindowHandle != nullptr) {
2458 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2459 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002460 }
arthurhung6d4bed92021-03-17 11:59:33 +08002461 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002462 }
2463 // enqueue drag location if needed.
2464 if (hoverWindowHandle != nullptr) {
2465 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2466 }
arthurhung6d4bed92021-03-17 11:59:33 +08002467 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2468 finishDragAndDrop(entry.displayId, x, y);
2469 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002470 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002471 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002472 }
2473}
2474
chaviw98318de2021-05-19 16:45:23 -05002475void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 int32_t targetFlags, BitSet32 pointerIds,
2477 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002478 std::vector<InputTarget>::iterator it =
2479 std::find_if(inputTargets.begin(), inputTargets.end(),
2480 [&windowHandle](const InputTarget& inputTarget) {
2481 return inputTarget.inputChannel->getConnectionToken() ==
2482 windowHandle->getToken();
2483 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002484
chaviw98318de2021-05-19 16:45:23 -05002485 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002486
2487 if (it == inputTargets.end()) {
2488 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002489 std::shared_ptr<InputChannel> inputChannel =
2490 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002491 if (inputChannel == nullptr) {
2492 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2493 return;
2494 }
2495 inputTarget.inputChannel = inputChannel;
2496 inputTarget.flags = targetFlags;
2497 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002498 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2499 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002500 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002501 } else {
2502 ALOGI_IF(isPerWindowInputRotationEnabled(),
2503 "DisplayInfo not found for window on display: %d", windowInfo->displayId);
2504 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002505 inputTargets.push_back(inputTarget);
2506 it = inputTargets.end() - 1;
2507 }
2508
2509 ALOG_ASSERT(it->flags == targetFlags);
2510 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2511
chaviw1ff3d1e2020-07-01 15:53:47 -07002512 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513}
2514
Michael Wright3dd60e22019-03-27 22:06:44 +00002515void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002516 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002517 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2518 mGlobalMonitorsByDisplay.find(displayId);
2519
2520 if (it != mGlobalMonitorsByDisplay.end()) {
2521 const std::vector<Monitor>& monitors = it->second;
2522 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002523 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 }
2526}
2527
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002528void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002530 InputTarget target;
2531 target.inputChannel = monitor.inputChannel;
2532 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002533 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002534 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2535 // Input monitors always get un-rotated display coordinates. We undo the display
2536 // rotation that is present in the display transform so that display rotation is not
2537 // applied to these input targets.
2538 const auto& displayInfo = it->second;
2539 int32_t width = displayInfo.logicalWidth;
2540 int32_t height = displayInfo.logicalHeight;
2541 const auto orientation = displayInfo.transform.getOrientation();
2542 uint32_t inverseOrientation = orientation;
2543 if (orientation == ui::Transform::ROT_90) {
2544 inverseOrientation = ui::Transform::ROT_270;
2545 std::swap(width, height);
2546 } else if (orientation == ui::Transform::ROT_270) {
2547 inverseOrientation = ui::Transform::ROT_90;
2548 std::swap(width, height);
2549 }
2550 target.displayTransform =
2551 ui::Transform(inverseOrientation, width, height) * displayInfo.transform;
2552 t = t * target.displayTransform;
2553 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002554 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002555 inputTargets.push_back(target);
2556}
2557
chaviw98318de2021-05-19 16:45:23 -05002558bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002559 const InjectionState* injectionState) {
2560 if (injectionState &&
2561 (windowHandle == nullptr ||
2562 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2563 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002564 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 "owned by uid %d",
2567 injectionState->injectorPid, injectionState->injectorUid,
2568 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 } else {
2570 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573 return false;
2574 }
2575 return true;
2576}
2577
Robert Carrc9bf1d32020-04-13 17:21:08 -07002578/**
2579 * Indicate whether one window handle should be considered as obscuring
2580 * another window handle. We only check a few preconditions. Actually
2581 * checking the bounds is left to the caller.
2582 */
chaviw98318de2021-05-19 16:45:23 -05002583static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2584 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002585 // Compare by token so cloned layers aren't counted
2586 if (haveSameToken(windowHandle, otherHandle)) {
2587 return false;
2588 }
2589 auto info = windowHandle->getInfo();
2590 auto otherInfo = otherHandle->getInfo();
2591 if (!otherInfo->visible) {
2592 return false;
chaviw98318de2021-05-19 16:45:23 -05002593 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002594 // Those act as if they were invisible, so we don't need to flag them.
2595 // We do want to potentially flag touchable windows even if they have 0
2596 // opacity, since they can consume touches and alter the effects of the
2597 // user interaction (eg. apps that rely on
2598 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2599 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2600 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002601 } else if (info->ownerUid == otherInfo->ownerUid) {
2602 // If ownerUid is the same we don't generate occlusion events as there
2603 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002604 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002605 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002606 return false;
2607 } else if (otherInfo->displayId != info->displayId) {
2608 return false;
2609 }
2610 return true;
2611}
2612
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002613/**
2614 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2615 * untrusted, one should check:
2616 *
2617 * 1. If result.hasBlockingOcclusion is true.
2618 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2619 * BLOCK_UNTRUSTED.
2620 *
2621 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2622 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2623 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2624 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2625 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2626 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2627 *
2628 * If neither of those is true, then it means the touch can be allowed.
2629 */
2630InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002631 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2632 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002633 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002634 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002635 TouchOcclusionInfo info;
2636 info.hasBlockingOcclusion = false;
2637 info.obscuringOpacity = 0;
2638 info.obscuringUid = -1;
2639 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002640 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002641 if (windowHandle == otherHandle) {
2642 break; // All future windows are below us. Exit early.
2643 }
chaviw98318de2021-05-19 16:45:23 -05002644 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002645 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2646 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002647 if (DEBUG_TOUCH_OCCLUSION) {
2648 info.debugInfo.push_back(
2649 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2650 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002651 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2652 // we perform the checks below to see if the touch can be propagated or not based on the
2653 // window's touch occlusion mode
2654 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2655 info.hasBlockingOcclusion = true;
2656 info.obscuringUid = otherInfo->ownerUid;
2657 info.obscuringPackage = otherInfo->packageName;
2658 break;
2659 }
2660 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2661 uint32_t uid = otherInfo->ownerUid;
2662 float opacity =
2663 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2664 // Given windows A and B:
2665 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2666 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2667 opacityByUid[uid] = opacity;
2668 if (opacity > info.obscuringOpacity) {
2669 info.obscuringOpacity = opacity;
2670 info.obscuringUid = uid;
2671 info.obscuringPackage = otherInfo->packageName;
2672 }
2673 }
2674 }
2675 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002676 if (DEBUG_TOUCH_OCCLUSION) {
2677 info.debugInfo.push_back(
2678 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2679 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002680 return info;
2681}
2682
chaviw98318de2021-05-19 16:45:23 -05002683std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002684 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002685 return StringPrintf(INDENT2
2686 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2687 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2688 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2689 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002690 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002691 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002692 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2693 info->frameTop, info->frameRight, info->frameBottom,
2694 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002695 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2696 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2697 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002698}
2699
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002700bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2701 if (occlusionInfo.hasBlockingOcclusion) {
2702 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2703 occlusionInfo.obscuringUid);
2704 return false;
2705 }
2706 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2707 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2708 "%.2f, maximum allowed = %.2f)",
2709 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2710 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2711 return false;
2712 }
2713 return true;
2714}
2715
chaviw98318de2021-05-19 16:45:23 -05002716bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002719 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2720 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002721 if (windowHandle == otherHandle) {
2722 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 }
chaviw98318de2021-05-19 16:45:23 -05002724 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002725 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002726 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 return true;
2728 }
2729 }
2730 return false;
2731}
2732
chaviw98318de2021-05-19 16:45:23 -05002733bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002734 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002735 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2736 const WindowInfo* windowInfo = windowHandle->getInfo();
2737 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002738 if (windowHandle == otherHandle) {
2739 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002740 }
chaviw98318de2021-05-19 16:45:23 -05002741 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002742 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002743 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002744 return true;
2745 }
2746 }
2747 return false;
2748}
2749
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002750std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002751 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002752 if (applicationHandle != nullptr) {
2753 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002754 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 } else {
2756 return applicationHandle->getName();
2757 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002758 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002759 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002761 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
2763}
2764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002765void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002766 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002767 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2768 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002769 // Focus or pointer capture changed events are passed to apps, but do not represent user
2770 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002771 return;
2772 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002773 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002774 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002775 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002776 const WindowInfo* info = focusedWindowHandle->getInfo();
2777 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002778 if (DEBUG_DISPATCH_CYCLE) {
2779 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 return;
2782 }
2783 }
2784
2785 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002786 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002787 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002788 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2789 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 return;
2791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002793 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 eventType = USER_ACTIVITY_EVENT_TOUCH;
2795 }
2796 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002798 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2800 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 return;
2802 }
2803 eventType = USER_ACTIVITY_EVENT_BUTTON;
2804 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07002806 case EventEntry::Type::TOUCH_MODE_CHANGED: {
2807 break;
2808 }
2809
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002810 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002811 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002812 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002813 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002814 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2815 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002816 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002817 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002818 break;
2819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821
Prabir Pradhancef936d2021-07-21 16:17:52 +00002822 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2823 REQUIRES(mLock) {
2824 scoped_unlock unlock(mLock);
2825 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2826 };
2827 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828}
2829
2830void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002831 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002832 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002833 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002834 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002836 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002837 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002838 ATRACE_NAME(message.c_str());
2839 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002840 if (DEBUG_DISPATCH_CYCLE) {
2841 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2842 "globalScaleFactor=%f, pointerIds=0x%x %s",
2843 connection->getInputChannelName().c_str(), inputTarget.flags,
2844 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2845 inputTarget.getPointerInfoString().c_str());
2846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847
2848 // Skip this event if the connection status is not normal.
2849 // We don't want to enqueue additional outbound events if the connection is broken.
2850 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002851 if (DEBUG_DISPATCH_CYCLE) {
2852 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2853 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 return;
2856 }
2857
2858 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002859 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2860 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2861 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002862 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002864 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002865 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002866 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002867 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 if (!splitMotionEntry) {
2869 return; // split event was dropped
2870 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002871 if (DEBUG_FOCUS) {
2872 ALOGD("channel '%s' ~ Split motion event.",
2873 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002874 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002875 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2877 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 return;
2879 }
2880 }
2881
2882 // Not splitting. Enqueue dispatch entries for the event as is.
2883 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2884}
2885
2886void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002888 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002889 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002890 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002892 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002893 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002894 ATRACE_NAME(message.c_str());
2895 }
2896
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002897 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898
2899 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002900 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002902 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002903 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002904 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002906 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002908 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002910 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
2913 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002914 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 startDispatchCycleLocked(currentTime, connection);
2916 }
2917}
2918
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002920 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002921 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002923 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2925 connection->getInputChannelName().c_str(),
2926 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002927 ATRACE_NAME(message.c_str());
2928 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002929 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 if (!(inputTargetFlags & dispatchMode)) {
2931 return;
2932 }
2933 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2934
2935 // This is a new event.
2936 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002937 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002938 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002940 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2941 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002942 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002944 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002945 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002946 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002947 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 dispatchEntry->resolvedAction = keyEntry.action;
2949 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2952 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002953 if (DEBUG_DISPATCH_CYCLE) {
2954 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2955 "event",
2956 connection->getInputChannelName().c_str());
2957 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 return; // skip the inconsistent event
2959 }
2960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002963 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002964 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002965 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2966 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2967 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2968 static_cast<int32_t>(IdGenerator::Source::OTHER);
2969 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2971 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2972 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2973 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2974 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2975 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2976 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2977 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2978 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2979 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2980 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002981 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002982 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 }
2984 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002985 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2986 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002987 if (DEBUG_DISPATCH_CYCLE) {
2988 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2989 "enter event",
2990 connection->getInputChannelName().c_str());
2991 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002992 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2993 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002998 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2999 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3000 }
3001 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3002 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3006 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003007 if (DEBUG_DISPATCH_CYCLE) {
3008 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3009 "event",
3010 connection->getInputChannelName().c_str());
3011 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 return; // skip the inconsistent event
3013 }
3014
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003015 dispatchEntry->resolvedEventId =
3016 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3017 ? mIdGenerator.nextId()
3018 : motionEntry.id;
3019 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3020 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3021 ") to MotionEvent(id=0x%" PRIx32 ").",
3022 motionEntry.id, dispatchEntry->resolvedEventId);
3023 ATRACE_NAME(message.c_str());
3024 }
3025
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003026 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3027 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3028 // Skip reporting pointer down outside focus to the policy.
3029 break;
3030 }
3031
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003032 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003033 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034
3035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003037 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003038 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003039 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3040 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003041 break;
3042 }
Chris Yef59a2f42020-10-16 12:55:26 -07003043 case EventEntry::Type::SENSOR: {
3044 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3045 break;
3046 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003047 case EventEntry::Type::CONFIGURATION_CHANGED:
3048 case EventEntry::Type::DEVICE_RESET: {
3049 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003050 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003051 break;
3052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 }
3054
3055 // Remember that we are waiting for this dispatch to complete.
3056 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003057 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
3059
3060 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003061 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003062 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003063}
3064
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003065/**
3066 * This function is purely for debugging. It helps us understand where the user interaction
3067 * was taking place. For example, if user is touching launcher, we will see a log that user
3068 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3069 * We will see both launcher and wallpaper in that list.
3070 * Once the interaction with a particular set of connections starts, no new logs will be printed
3071 * until the set of interacted connections changes.
3072 *
3073 * The following items are skipped, to reduce the logspam:
3074 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3075 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3076 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3077 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3078 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003079 */
3080void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3081 const std::vector<InputTarget>& targets) {
3082 // Skip ACTION_UP events, and all events other than keys and motions
3083 if (entry.type == EventEntry::Type::KEY) {
3084 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3085 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3086 return;
3087 }
3088 } else if (entry.type == EventEntry::Type::MOTION) {
3089 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3090 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3091 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3092 return;
3093 }
3094 } else {
3095 return; // Not a key or a motion
3096 }
3097
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003098 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003099 std::vector<sp<Connection>> newConnections;
3100 for (const InputTarget& target : targets) {
3101 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3102 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3103 continue; // Skip windows that receive ACTION_OUTSIDE
3104 }
3105
3106 sp<IBinder> token = target.inputChannel->getConnectionToken();
3107 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003108 if (connection == nullptr) {
3109 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003110 }
3111 newConnectionTokens.insert(std::move(token));
3112 newConnections.emplace_back(connection);
3113 }
3114 if (newConnectionTokens == mInteractionConnectionTokens) {
3115 return; // no change
3116 }
3117 mInteractionConnectionTokens = newConnectionTokens;
3118
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003119 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003120 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003121 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003122 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003123 std::string message = "Interaction with: " + targetList;
3124 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003125 message += "<none>";
3126 }
3127 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3128}
3129
chaviwfd6d3512019-03-25 13:23:49 -07003130void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003131 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003132 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003133 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3134 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003135 return;
3136 }
3137
Vishnu Nairc519ff72021-01-21 08:23:08 -08003138 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003139 if (focusedToken == token) {
3140 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003141 return;
3142 }
3143
Prabir Pradhancef936d2021-07-21 16:17:52 +00003144 auto command = [this, token]() REQUIRES(mLock) {
3145 scoped_unlock unlock(mLock);
3146 mPolicy->onPointerDownOutsideFocus(token);
3147 };
3148 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149}
3150
3151void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003153 if (ATRACE_ENABLED()) {
3154 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003156 ATRACE_NAME(message.c_str());
3157 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003158 if (DEBUG_DISPATCH_CYCLE) {
3159 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003162 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3163 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003165 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003166 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003167 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
3169 // Publish the event.
3170 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3172 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003173 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003174 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3175 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003178 status = connection->inputPublisher
3179 .publishKeyEvent(dispatchEntry->seq,
3180 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3181 keyEntry.source, keyEntry.displayId,
3182 std::move(hmac), dispatchEntry->resolvedAction,
3183 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3184 keyEntry.scanCode, keyEntry.metaState,
3185 keyEntry.repeatCount, keyEntry.downTime,
3186 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 }
3189
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003190 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003191 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003194 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195
chaviw82357092020-01-28 13:13:06 -08003196 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003197 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3199 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003200 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003201 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3202 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003203 // Don't apply window scale here since we don't want scale to affect raw
3204 // coordinates. The scale will be sent back to the client and applied
3205 // later when requesting relative coordinates.
3206 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3207 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 }
3209 usingCoords = scaledCoords;
3210 }
3211 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 // We don't want the dispatch target to know.
3213 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003214 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 scaledCoords[i].clear();
3216 }
3217 usingCoords = scaledCoords;
3218 }
3219 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003220
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003221 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222
3223 // Publish the motion event.
3224 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003225 .publishMotionEvent(dispatchEntry->seq,
3226 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003227 motionEntry.deviceId, motionEntry.source,
3228 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003229 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003230 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 motionEntry.edgeFlags, motionEntry.metaState,
3233 motionEntry.buttonState,
3234 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003235 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 motionEntry.xPrecision, motionEntry.yPrecision,
3237 motionEntry.xCursorPosition,
3238 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003239 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 motionEntry.downTime, motionEntry.eventTime,
3241 motionEntry.pointerCount,
3242 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 break;
3244 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003245
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003246 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003248 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003249 focusEntry.id,
3250 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003251 mInTouchMode);
3252 break;
3253 }
3254
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003255 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3256 const TouchModeEntry& touchModeEntry =
3257 static_cast<const TouchModeEntry&>(eventEntry);
3258 status = connection->inputPublisher
3259 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3260 touchModeEntry.inTouchMode);
3261
3262 break;
3263 }
3264
Prabir Pradhan99987712020-11-10 18:43:05 -08003265 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3266 const auto& captureEntry =
3267 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3268 status = connection->inputPublisher
3269 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003270 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003271 break;
3272 }
3273
arthurhungb89ccb02020-12-30 16:19:01 +08003274 case EventEntry::Type::DRAG: {
3275 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3276 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3277 dragEntry.id, dragEntry.x,
3278 dragEntry.y,
3279 dragEntry.isExiting);
3280 break;
3281 }
3282
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003283 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003284 case EventEntry::Type::DEVICE_RESET:
3285 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003286 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003287 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 }
3291
3292 // Check the result.
3293 if (status) {
3294 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003295 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 "This is unexpected because the wait queue is empty, so the pipe "
3298 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003299 "event to it, status=%s(%d)",
3300 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3301 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3303 } else {
3304 // Pipe is full and we are waiting for the app to finish process some events
3305 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003306 if (DEBUG_DISPATCH_CYCLE) {
3307 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3308 "waiting for the application to catch up",
3309 connection->getInputChannelName().c_str());
3310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 }
3312 } else {
3313 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003314 "status=%s(%d)",
3315 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3316 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3318 }
3319 return;
3320 }
3321
3322 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003323 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3324 connection->outboundQueue.end(),
3325 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003326 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003327 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003328 if (connection->responsive) {
3329 mAnrTracker.insert(dispatchEntry->timeoutTime,
3330 connection->inputChannel->getConnectionToken());
3331 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003332 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
3334}
3335
chaviw09c8d2d2020-08-24 15:48:26 -07003336std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3337 size_t size;
3338 switch (event.type) {
3339 case VerifiedInputEvent::Type::KEY: {
3340 size = sizeof(VerifiedKeyEvent);
3341 break;
3342 }
3343 case VerifiedInputEvent::Type::MOTION: {
3344 size = sizeof(VerifiedMotionEvent);
3345 break;
3346 }
3347 }
3348 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3349 return mHmacKeyManager.sign(start, size);
3350}
3351
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003352const std::array<uint8_t, 32> InputDispatcher::getSignature(
3353 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3354 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3355 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3356 // Only sign events up and down events as the purely move events
3357 // are tied to their up/down counterparts so signing would be redundant.
3358 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3359 verifiedEvent.actionMasked = actionMasked;
3360 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003361 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003362 }
3363 return INVALID_HMAC;
3364}
3365
3366const std::array<uint8_t, 32> InputDispatcher::getSignature(
3367 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3368 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3369 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3370 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003371 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003372}
3373
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003375 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003376 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003377 if (DEBUG_DISPATCH_CYCLE) {
3378 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3379 connection->getInputChannelName().c_str(), seq, toString(handled));
3380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 if (connection->status == Connection::STATUS_BROKEN ||
3383 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 return;
3385 }
3386
3387 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003388 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3389 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3390 };
3391 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392}
3393
3394void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003395 const sp<Connection>& connection,
3396 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003397 if (DEBUG_DISPATCH_CYCLE) {
3398 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3399 connection->getInputChannelName().c_str(), toString(notify));
3400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
3402 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003403 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003404 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003405 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003406 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
3408 // The connection appears to be unrecoverably broken.
3409 // Ignore already broken or zombie connections.
3410 if (connection->status == Connection::STATUS_NORMAL) {
3411 connection->status = Connection::STATUS_BROKEN;
3412
3413 if (notify) {
3414 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003415 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3416 connection->getInputChannelName().c_str());
3417
3418 auto command = [this, connection]() REQUIRES(mLock) {
3419 if (connection->status == Connection::STATUS_ZOMBIE) return;
3420 scoped_unlock unlock(mLock);
3421 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3422 };
3423 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 }
3425 }
3426}
3427
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003428void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3429 while (!queue.empty()) {
3430 DispatchEntry* dispatchEntry = queue.front();
3431 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003432 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 }
3434}
3435
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003436void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003438 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 }
3440 delete dispatchEntry;
3441}
3442
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003443int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3444 std::scoped_lock _l(mLock);
3445 sp<Connection> connection = getConnectionLocked(connectionToken);
3446 if (connection == nullptr) {
3447 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3448 connectionToken.get(), events);
3449 return 0; // remove the callback
3450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003452 bool notify;
3453 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3454 if (!(events & ALOOPER_EVENT_INPUT)) {
3455 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3456 "events=0x%x",
3457 connection->getInputChannelName().c_str(), events);
3458 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 }
3460
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003461 nsecs_t currentTime = now();
3462 bool gotOne = false;
3463 status_t status = OK;
3464 for (;;) {
3465 Result<InputPublisher::ConsumerResponse> result =
3466 connection->inputPublisher.receiveConsumerResponse();
3467 if (!result.ok()) {
3468 status = result.error().code();
3469 break;
3470 }
3471
3472 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3473 const InputPublisher::Finished& finish =
3474 std::get<InputPublisher::Finished>(*result);
3475 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3476 finish.consumeTime);
3477 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003478 if (shouldReportMetricsForConnection(*connection)) {
3479 const InputPublisher::Timeline& timeline =
3480 std::get<InputPublisher::Timeline>(*result);
3481 mLatencyTracker
3482 .trackGraphicsLatency(timeline.inputEventId,
3483 connection->inputChannel->getConnectionToken(),
3484 std::move(timeline.graphicsTimeline));
3485 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003486 }
3487 gotOne = true;
3488 }
3489 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003490 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003491 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 return 1;
3493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
3495
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003496 notify = status != DEAD_OBJECT || !connection->monitor;
3497 if (notify) {
3498 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3499 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3500 status);
3501 }
3502 } else {
3503 // Monitor channels are never explicitly unregistered.
3504 // We do it automatically when the remote endpoint is closed so don't warn about them.
3505 const bool stillHaveWindowHandle =
3506 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3507 notify = !connection->monitor && stillHaveWindowHandle;
3508 if (notify) {
3509 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3510 connection->getInputChannelName().c_str(), events);
3511 }
3512 }
3513
3514 // Remove the channel.
3515 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3516 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517}
3518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003521 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003522 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524}
3525
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003526void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003527 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003528 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3529 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3530}
3531
3532void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3533 const CancelationOptions& options,
3534 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3535 for (const auto& it : monitorsByDisplay) {
3536 const std::vector<Monitor>& monitors = it.second;
3537 for (const Monitor& monitor : monitors) {
3538 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003539 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003540 }
3541}
3542
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003544 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003545 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003546 if (connection == nullptr) {
3547 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003549
3550 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551}
3552
3553void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3554 const sp<Connection>& connection, const CancelationOptions& options) {
3555 if (connection->status == Connection::STATUS_BROKEN) {
3556 return;
3557 }
3558
3559 nsecs_t currentTime = now();
3560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003561 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003562 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003564 if (cancelationEvents.empty()) {
3565 return;
3566 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003567 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3568 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3569 "with reality: %s, mode=%d.",
3570 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3571 options.mode);
3572 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003573
3574 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003575 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003576 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3577 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003578 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003579 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003580 target.globalScaleFactor = windowInfo->globalScaleFactor;
3581 }
3582 target.inputChannel = connection->inputChannel;
3583 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3584
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003585 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003586 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003587 switch (cancelationEventEntry->type) {
3588 case EventEntry::Type::KEY: {
3589 logOutboundKeyDetails("cancel - ",
3590 static_cast<const KeyEntry&>(*cancelationEventEntry));
3591 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003593 case EventEntry::Type::MOTION: {
3594 logOutboundMotionDetails("cancel - ",
3595 static_cast<const MotionEntry&>(*cancelationEventEntry));
3596 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003598 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003599 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003600 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3601 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003602 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003603 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003604 break;
3605 }
3606 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003607 case EventEntry::Type::DEVICE_RESET:
3608 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003609 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003610 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003611 break;
3612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
3614
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003615 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3616 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003618
3619 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620}
3621
Svet Ganov5d3bc372020-01-26 23:11:07 -08003622void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3623 const sp<Connection>& connection) {
3624 if (connection->status == Connection::STATUS_BROKEN) {
3625 return;
3626 }
3627
3628 nsecs_t currentTime = now();
3629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631 connection->inputState.synthesizePointerDownEvents(currentTime);
3632
3633 if (downEvents.empty()) {
3634 return;
3635 }
3636
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003637 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003638 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3639 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003640 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003641
3642 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003643 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003644 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3645 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003646 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003647 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003648 target.globalScaleFactor = windowInfo->globalScaleFactor;
3649 }
3650 target.inputChannel = connection->inputChannel;
3651 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3652
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003653 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654 switch (downEventEntry->type) {
3655 case EventEntry::Type::MOTION: {
3656 logOutboundMotionDetails("down - ",
3657 static_cast<const MotionEntry&>(*downEventEntry));
3658 break;
3659 }
3660
3661 case EventEntry::Type::KEY:
3662 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003663 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003665 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003666 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003667 case EventEntry::Type::SENSOR:
3668 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003670 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003671 break;
3672 }
3673 }
3674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3676 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003677 }
3678
3679 startDispatchCycleLocked(currentTime, connection);
3680}
3681
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003682std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3683 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 ALOG_ASSERT(pointerIds.value != 0);
3685
3686 uint32_t splitPointerIndexMap[MAX_POINTERS];
3687 PointerProperties splitPointerProperties[MAX_POINTERS];
3688 PointerCoords splitPointerCoords[MAX_POINTERS];
3689
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003690 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 uint32_t splitPointerCount = 0;
3692
3693 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003694 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003696 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 uint32_t pointerId = uint32_t(pointerProperties.id);
3698 if (pointerIds.hasBit(pointerId)) {
3699 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3700 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3701 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003702 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 splitPointerCount += 1;
3704 }
3705 }
3706
3707 if (splitPointerCount != pointerIds.count()) {
3708 // This is bad. We are missing some of the pointers that we expected to deliver.
3709 // Most likely this indicates that we received an ACTION_MOVE events that has
3710 // different pointer ids than we expected based on the previous ACTION_DOWN
3711 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3712 // in this way.
3713 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 "we expected there to be %d pointers. This probably means we received "
3715 "a broken sequence of pointer ids from the input device.",
3716 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003717 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003720 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3723 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3725 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003726 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 uint32_t pointerId = uint32_t(pointerProperties.id);
3728 if (pointerIds.hasBit(pointerId)) {
3729 if (pointerIds.count() == 1) {
3730 // The first/last pointer went down/up.
3731 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003733 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3734 ? AMOTION_EVENT_ACTION_CANCEL
3735 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 } else {
3737 // A secondary pointer went down/up.
3738 uint32_t splitPointerIndex = 0;
3739 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3740 splitPointerIndex += 1;
3741 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003742 action = maskedAction |
3743 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745 } else {
3746 // An unrelated pointer changed.
3747 action = AMOTION_EVENT_ACTION_MOVE;
3748 }
3749 }
3750
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003751 int32_t newId = mIdGenerator.nextId();
3752 if (ATRACE_ENABLED()) {
3753 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3754 ") to MotionEvent(id=0x%" PRIx32 ").",
3755 originalMotionEntry.id, newId);
3756 ATRACE_NAME(message.c_str());
3757 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003758 std::unique_ptr<MotionEntry> splitMotionEntry =
3759 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3760 originalMotionEntry.deviceId, originalMotionEntry.source,
3761 originalMotionEntry.displayId,
3762 originalMotionEntry.policyFlags, action,
3763 originalMotionEntry.actionButton,
3764 originalMotionEntry.flags, originalMotionEntry.metaState,
3765 originalMotionEntry.buttonState,
3766 originalMotionEntry.classification,
3767 originalMotionEntry.edgeFlags,
3768 originalMotionEntry.xPrecision,
3769 originalMotionEntry.yPrecision,
3770 originalMotionEntry.xCursorPosition,
3771 originalMotionEntry.yCursorPosition,
3772 originalMotionEntry.downTime, splitPointerCount,
3773 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003775 if (originalMotionEntry.injectionState) {
3776 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 splitMotionEntry->injectionState->refCount += 1;
3778 }
3779
3780 return splitMotionEntry;
3781}
3782
3783void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003784 if (DEBUG_INBOUND_EVENT_DETAILS) {
3785 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
3788 bool needWake;
3789 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003790 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003792 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3793 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3794 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 } // release lock
3796
3797 if (needWake) {
3798 mLooper->wake();
3799 }
3800}
3801
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003802/**
3803 * If one of the meta shortcuts is detected, process them here:
3804 * Meta + Backspace -> generate BACK
3805 * Meta + Enter -> generate HOME
3806 * This will potentially overwrite keyCode and metaState.
3807 */
3808void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003809 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003810 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3811 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3812 if (keyCode == AKEYCODE_DEL) {
3813 newKeyCode = AKEYCODE_BACK;
3814 } else if (keyCode == AKEYCODE_ENTER) {
3815 newKeyCode = AKEYCODE_HOME;
3816 }
3817 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003818 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003819 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003820 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003821 keyCode = newKeyCode;
3822 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3823 }
3824 } else if (action == AKEY_EVENT_ACTION_UP) {
3825 // In order to maintain a consistent stream of up and down events, check to see if the key
3826 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3827 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003828 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003829 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003830 auto replacementIt = mReplacedKeys.find(replacement);
3831 if (replacementIt != mReplacedKeys.end()) {
3832 keyCode = replacementIt->second;
3833 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003834 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3835 }
3836 }
3837}
3838
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003840 if (DEBUG_INBOUND_EVENT_DETAILS) {
3841 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3842 "policyFlags=0x%x, action=0x%x, "
3843 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3844 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3845 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3846 args->downTime);
3847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 if (!validateKeyEvent(args->action)) {
3849 return;
3850 }
3851
3852 uint32_t policyFlags = args->policyFlags;
3853 int32_t flags = args->flags;
3854 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003855 // InputDispatcher tracks and generates key repeats on behalf of
3856 // whatever notifies it, so repeatCount should always be set to 0
3857 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3859 policyFlags |= POLICY_FLAG_VIRTUAL;
3860 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 if (policyFlags & POLICY_FLAG_FUNCTION) {
3863 metaState |= AMETA_FUNCTION_ON;
3864 }
3865
3866 policyFlags |= POLICY_FLAG_TRUSTED;
3867
Michael Wright78f24442014-08-06 15:55:28 -07003868 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003869 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003870
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003872 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003873 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3874 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
Michael Wright2b3c3302018-03-02 17:19:13 +00003876 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003878 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3879 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003880 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 bool needWake;
3884 { // acquire lock
3885 mLock.lock();
3886
3887 if (shouldSendKeyToInputFilterLocked(args)) {
3888 mLock.unlock();
3889
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003890 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3892 return; // event was consumed by the filter
3893 }
3894
3895 mLock.lock();
3896 }
3897
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003898 std::unique_ptr<KeyEntry> newEntry =
3899 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3900 args->displayId, policyFlags, args->action, flags,
3901 keyCode, args->scanCode, metaState, repeatCount,
3902 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003904 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 mLock.unlock();
3906 } // release lock
3907
3908 if (needWake) {
3909 mLooper->wake();
3910 }
3911}
3912
3913bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3914 return mInputFilterEnabled;
3915}
3916
3917void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003918 if (DEBUG_INBOUND_EVENT_DETAILS) {
3919 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3920 "displayId=%" PRId32 ", policyFlags=0x%x, "
3921 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3922 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3923 "yCursorPosition=%f, downTime=%" PRId64,
3924 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3925 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3926 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3927 args->xCursorPosition, args->yCursorPosition, args->downTime);
3928 for (uint32_t i = 0; i < args->pointerCount; i++) {
3929 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3930 "x=%f, y=%f, pressure=%f, size=%f, "
3931 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3932 "orientation=%f",
3933 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3934 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3935 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3936 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3937 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3938 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3939 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3940 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3941 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3942 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003945 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3946 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 return;
3948 }
3949
3950 uint32_t policyFlags = args->policyFlags;
3951 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003952
3953 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003954 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003955 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3956 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 bool needWake;
3961 { // acquire lock
3962 mLock.lock();
3963
3964 if (shouldSendMotionToInputFilterLocked(args)) {
3965 mLock.unlock();
3966
3967 MotionEvent event;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003968 ui::Transform identityTransform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003969 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3970 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003971 args->metaState, args->buttonState, args->classification,
3972 identityTransform, args->xPrecision, args->yPrecision,
3973 args->xCursorPosition, args->yCursorPosition, identityTransform,
3974 args->downTime, args->eventTime, args->pointerCount,
3975 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
3977 policyFlags |= POLICY_FLAG_FILTERED;
3978 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3979 return; // event was consumed by the filter
3980 }
3981
3982 mLock.lock();
3983 }
3984
3985 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003986 std::unique_ptr<MotionEntry> newEntry =
3987 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3988 args->source, args->displayId, policyFlags,
3989 args->action, args->actionButton, args->flags,
3990 args->metaState, args->buttonState,
3991 args->classification, args->edgeFlags,
3992 args->xPrecision, args->yPrecision,
3993 args->xCursorPosition, args->yCursorPosition,
3994 args->downTime, args->pointerCount,
3995 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003997 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3998 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3999 !mInputFilterEnabled) {
4000 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4001 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4002 }
4003
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004004 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 mLock.unlock();
4006 } // release lock
4007
4008 if (needWake) {
4009 mLooper->wake();
4010 }
4011}
4012
Chris Yef59a2f42020-10-16 12:55:26 -07004013void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004014 if (DEBUG_INBOUND_EVENT_DETAILS) {
4015 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4016 " sensorType=%s",
4017 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004018 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004019 }
Chris Yef59a2f42020-10-16 12:55:26 -07004020
4021 bool needWake;
4022 { // acquire lock
4023 mLock.lock();
4024
4025 // Just enqueue a new sensor event.
4026 std::unique_ptr<SensorEntry> newEntry =
4027 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4028 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4029 args->sensorType, args->accuracy,
4030 args->accuracyChanged, args->values);
4031
4032 needWake = enqueueInboundEventLocked(std::move(newEntry));
4033 mLock.unlock();
4034 } // release lock
4035
4036 if (needWake) {
4037 mLooper->wake();
4038 }
4039}
4040
Chris Yefb552902021-02-03 17:18:37 -08004041void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004042 if (DEBUG_INBOUND_EVENT_DETAILS) {
4043 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4044 args->deviceId, args->isOn);
4045 }
Chris Yefb552902021-02-03 17:18:37 -08004046 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4047}
4048
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004050 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051}
4052
4053void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004054 if (DEBUG_INBOUND_EVENT_DETAILS) {
4055 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4056 "switchMask=0x%08x",
4057 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059
4060 uint32_t policyFlags = args->policyFlags;
4061 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063}
4064
4065void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004066 if (DEBUG_INBOUND_EVENT_DETAILS) {
4067 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4068 args->deviceId);
4069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
4071 bool needWake;
4072 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004073 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004075 std::unique_ptr<DeviceResetEntry> newEntry =
4076 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4077 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 } // release lock
4079
4080 if (needWake) {
4081 mLooper->wake();
4082 }
4083}
4084
Prabir Pradhan7e186182020-11-10 13:56:45 -08004085void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 if (DEBUG_INBOUND_EVENT_DETAILS) {
4087 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004088 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004089 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004090
Prabir Pradhan99987712020-11-10 18:43:05 -08004091 bool needWake;
4092 { // acquire lock
4093 std::scoped_lock _l(mLock);
4094 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004095 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004096 needWake = enqueueInboundEventLocked(std::move(entry));
4097 } // release lock
4098
4099 if (needWake) {
4100 mLooper->wake();
4101 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004102}
4103
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004104InputEventInjectionResult InputDispatcher::injectInputEvent(
4105 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4106 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004107 if (DEBUG_INBOUND_EVENT_DETAILS) {
4108 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4109 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4110 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4111 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004112 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
4114 policyFlags |= POLICY_FLAG_INJECTED;
4115 if (hasInjectionPermission(injectorPid, injectorUid)) {
4116 policyFlags |= POLICY_FLAG_TRUSTED;
4117 }
4118
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004120 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4121 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4122 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4123 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4124 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004125 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004126 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004127 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004128 }
4129
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004130 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004133 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4134 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004136 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004139 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004140 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4141 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4142 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004143 int32_t keyCode = incomingKey.getKeyCode();
4144 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004145 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004146 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004147 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004148 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004149 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4150 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4151 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4154 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004155 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156
4157 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4158 android::base::Timer t;
4159 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4160 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4161 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4162 std::to_string(t.duration().count()).c_str());
4163 }
4164 }
4165
4166 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004167 std::unique_ptr<KeyEntry> injectedEntry =
4168 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004169 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004170 incomingKey.getDisplayId(), policyFlags, action,
4171 flags, keyCode, incomingKey.getScanCode(), metaState,
4172 incomingKey.getRepeatCount(),
4173 incomingKey.getDownTime());
4174 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 }
4177
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004179 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4180 int32_t action = motionEvent.getAction();
4181 size_t pointerCount = motionEvent.getPointerCount();
4182 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4183 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004184 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004185 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188 }
4189
4190 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004191 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 android::base::Timer t;
4193 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4194 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4195 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4196 std::to_string(t.duration().count()).c_str());
4197 }
4198 }
4199
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004200 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4201 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4202 }
4203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004205 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4206 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004207 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004208 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4209 resolvedDeviceId, motionEvent.getSource(),
4210 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004211 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004212 motionEvent.getButtonState(),
4213 motionEvent.getClassification(),
4214 motionEvent.getEdgeFlags(),
4215 motionEvent.getXPrecision(),
4216 motionEvent.getYPrecision(),
4217 motionEvent.getRawXCursorPosition(),
4218 motionEvent.getRawYCursorPosition(),
4219 motionEvent.getDownTime(), uint32_t(pointerCount),
4220 pointerProperties, samplePointerCoords,
4221 motionEvent.getXOffset(),
4222 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004223 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 sampleEventTimes += 1;
4226 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004227 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4229 resolvedDeviceId, motionEvent.getSource(),
4230 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004231 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004232 motionEvent.getMetaState(),
4233 motionEvent.getButtonState(),
4234 motionEvent.getClassification(),
4235 motionEvent.getEdgeFlags(),
4236 motionEvent.getXPrecision(),
4237 motionEvent.getYPrecision(),
4238 motionEvent.getRawXCursorPosition(),
4239 motionEvent.getRawYCursorPosition(),
4240 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004241 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 samplePointerCoords, motionEvent.getXOffset(),
4243 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004244 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 }
4246 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004250 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004251 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 }
4253
4254 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004255 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 injectionState->injectionIsAsync = true;
4257 }
4258
4259 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004260 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
4262 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004263 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004264 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004265 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267
4268 mLock.unlock();
4269
4270 if (needWake) {
4271 mLooper->wake();
4272 }
4273
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004274 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004276 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004278 if (syncMode == InputEventInjectionSync::NONE) {
4279 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 } else {
4281 for (;;) {
4282 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 break;
4285 }
4286
4287 nsecs_t remainingTimeout = endTime - now();
4288 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004289 if (DEBUG_INJECTION) {
4290 ALOGD("injectInputEvent - Timed out waiting for injection result "
4291 "to become available.");
4292 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004293 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 break;
4295 }
4296
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004297 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 }
4299
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004300 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4301 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004303 if (DEBUG_INJECTION) {
4304 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4305 injectionState->pendingForegroundDispatches);
4306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 nsecs_t remainingTimeout = endTime - now();
4308 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004309 if (DEBUG_INJECTION) {
4310 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4311 "dispatches to finish.");
4312 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004313 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 break;
4315 }
4316
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004317 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319 }
4320 }
4321
4322 injectionState->release();
4323 } // release lock
4324
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004325 if (DEBUG_INJECTION) {
4326 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4327 injectionResult, injectorPid, injectorUid);
4328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329
4330 return injectionResult;
4331}
4332
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004333std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004334 std::array<uint8_t, 32> calculatedHmac;
4335 std::unique_ptr<VerifiedInputEvent> result;
4336 switch (event.getType()) {
4337 case AINPUT_EVENT_TYPE_KEY: {
4338 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4339 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4340 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004341 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004342 break;
4343 }
4344 case AINPUT_EVENT_TYPE_MOTION: {
4345 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4346 VerifiedMotionEvent verifiedMotionEvent =
4347 verifiedMotionEventFromMotionEvent(motionEvent);
4348 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004349 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004350 break;
4351 }
4352 default: {
4353 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4354 return nullptr;
4355 }
4356 }
4357 if (calculatedHmac == INVALID_HMAC) {
4358 return nullptr;
4359 }
4360 if (calculatedHmac != event.getHmac()) {
4361 return nullptr;
4362 }
4363 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004364}
4365
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 return injectorUid == 0 ||
4368 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369}
4370
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004371void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004375 if (DEBUG_INJECTION) {
4376 ALOGD("Setting input event injection result to %d. "
4377 "injectorPid=%d, injectorUid=%d",
4378 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004381 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 // Log the outcome since the injector did not wait for the injection result.
4383 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 ALOGV("Asynchronous input event injection succeeded.");
4386 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 ALOGW("Asynchronous input event injection failed.");
4389 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004390 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004391 ALOGW("Asynchronous input event injection permission denied.");
4392 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 ALOGW("Asynchronous input event injection timed out.");
4395 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 case InputEventInjectionResult::PENDING:
4397 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4398 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 }
4400 }
4401
4402 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004403 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 }
4405}
4406
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004407void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4408 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 if (injectionState) {
4410 injectionState->pendingForegroundDispatches += 1;
4411 }
4412}
4413
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004414void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4415 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 if (injectionState) {
4417 injectionState->pendingForegroundDispatches -= 1;
4418
4419 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004420 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422 }
4423}
4424
chaviw98318de2021-05-19 16:45:23 -05004425const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004426 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004427 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004428 auto it = mWindowHandlesByDisplay.find(displayId);
4429 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004430}
4431
chaviw98318de2021-05-19 16:45:23 -05004432sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004433 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004434 if (windowHandleToken == nullptr) {
4435 return nullptr;
4436 }
4437
Arthur Hungb92218b2018-08-14 12:00:21 +08004438 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004439 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4440 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004441 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004442 return windowHandle;
4443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 }
4445 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004446 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447}
4448
chaviw98318de2021-05-19 16:45:23 -05004449sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4450 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004451 if (windowHandleToken == nullptr) {
4452 return nullptr;
4453 }
4454
chaviw98318de2021-05-19 16:45:23 -05004455 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004456 if (windowHandle->getToken() == windowHandleToken) {
4457 return windowHandle;
4458 }
4459 }
4460 return nullptr;
4461}
4462
chaviw98318de2021-05-19 16:45:23 -05004463sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4464 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004465 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004466 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4467 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004468 if (handle->getId() == windowHandle->getId() &&
4469 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004470 if (windowHandle->getInfo()->displayId != it.first) {
4471 ALOGE("Found window %s in display %" PRId32
4472 ", but it should belong to display %" PRId32,
4473 windowHandle->getName().c_str(), it.first,
4474 windowHandle->getInfo()->displayId);
4475 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004476 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 }
4479 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004480 return nullptr;
4481}
4482
chaviw98318de2021-05-19 16:45:23 -05004483sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004484 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4485 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486}
4487
chaviw98318de2021-05-19 16:45:23 -05004488bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004489 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4490 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004491 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004492 if (connection != nullptr && noInputChannel) {
4493 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4494 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4495 return false;
4496 }
4497
4498 if (connection == nullptr) {
4499 if (!noInputChannel) {
4500 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4501 }
4502 return false;
4503 }
4504 if (!connection->responsive) {
4505 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4506 return false;
4507 }
4508 return true;
4509}
4510
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004511std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4512 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004513 auto connectionIt = mConnectionsByToken.find(token);
4514 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004515 return nullptr;
4516 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004517 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004518}
4519
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004520void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004521 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4522 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004523 // Remove all handles on a display if there are no windows left.
4524 mWindowHandlesByDisplay.erase(displayId);
4525 return;
4526 }
4527
4528 // Since we compare the pointer of input window handles across window updates, we need
4529 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004530 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4531 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4532 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004533 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004534 }
4535
chaviw98318de2021-05-19 16:45:23 -05004536 std::vector<sp<WindowInfoHandle>> newHandles;
4537 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004538 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004539 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004540 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004541 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4542 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4543 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004544 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004545 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004546 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004547 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004548 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004549 }
4550
4551 if (info->displayId != displayId) {
4552 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4553 handle->getName().c_str(), displayId, info->displayId);
4554 continue;
4555 }
4556
Robert Carredd13602020-04-13 17:24:34 -07004557 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4558 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004559 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004560 oldHandle->updateFrom(handle);
4561 newHandles.push_back(oldHandle);
4562 } else {
4563 newHandles.push_back(handle);
4564 }
4565 }
4566
4567 // Insert or replace
4568 mWindowHandlesByDisplay[displayId] = newHandles;
4569}
4570
Arthur Hung72d8dc32020-03-28 00:48:39 +00004571void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004572 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004573 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004574 { // acquire lock
4575 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004576 for (const auto& [displayId, handles] : handlesPerDisplay) {
4577 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004578 }
4579 }
4580 // Wake up poll loop since it may need to make new input dispatching choices.
4581 mLooper->wake();
4582}
4583
Arthur Hungb92218b2018-08-14 12:00:21 +08004584/**
4585 * Called from InputManagerService, update window handle list by displayId that can receive input.
4586 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4587 * If set an empty list, remove all handles from the specific display.
4588 * For focused handle, check if need to change and send a cancel event to previous one.
4589 * For removed handle, check if need to send a cancel event if already in touch.
4590 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004591void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004592 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004593 if (DEBUG_FOCUS) {
4594 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004595 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004596 windowList += iwh->getName() + " ";
4597 }
4598 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004601 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004602 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004603 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004604 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004605 if (noInputWindow && window->getToken() != nullptr) {
4606 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4607 window->getName().c_str());
4608 window->releaseChannel();
4609 }
4610 }
4611
Arthur Hung72d8dc32020-03-28 00:48:39 +00004612 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004613 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004615 // Save the old windows' orientation by ID before it gets updated.
4616 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004617 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004618 oldWindowOrientations.emplace(handle->getId(),
4619 handle->getInfo()->transform.getOrientation());
4620 }
4621
chaviw98318de2021-05-19 16:45:23 -05004622 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004623
chaviw98318de2021-05-19 16:45:23 -05004624 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004625 if (mLastHoverWindowHandle &&
4626 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4627 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004628 mLastHoverWindowHandle = nullptr;
4629 }
4630
Vishnu Nairc519ff72021-01-21 08:23:08 -08004631 std::optional<FocusResolver::FocusChanges> changes =
4632 mFocusResolver.setInputWindows(displayId, windowHandles);
4633 if (changes) {
4634 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004637 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4638 mTouchStatesByDisplay.find(displayId);
4639 if (stateIt != mTouchStatesByDisplay.end()) {
4640 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004641 for (size_t i = 0; i < state.windows.size();) {
4642 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004643 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004644 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004645 ALOGD("Touched window was removed: %s in display %" PRId32,
4646 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004647 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004648 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004649 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4650 if (touchedInputChannel != nullptr) {
4651 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4652 "touched window was removed");
4653 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004654 // Since we are about to drop the touch, cancel the events for the wallpaper as
4655 // well.
4656 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4657 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4658 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4659 if (wallpaper != nullptr) {
4660 sp<Connection> wallpaperConnection =
4661 getConnectionLocked(wallpaper->getToken());
4662 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4663 options);
4664 }
4665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004667 state.windows.erase(state.windows.begin() + i);
4668 } else {
4669 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 }
4671 }
arthurhungb89ccb02020-12-30 16:19:01 +08004672
arthurhung6d4bed92021-03-17 11:59:33 +08004673 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004674 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004675 if (mDragState &&
4676 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004677 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004678 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004679 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004680 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004681
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004682 if (isPerWindowInputRotationEnabled()) {
4683 // Determine if the orientation of any of the input windows have changed, and cancel all
4684 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004685 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4686 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004687 if (newWindowHandle != nullptr &&
4688 newWindowHandle->getInfo()->transform.getOrientation() !=
4689 oldWindowOrientations[oldWindowHandle->getId()]) {
4690 std::shared_ptr<InputChannel> inputChannel =
4691 getInputChannelLocked(newWindowHandle->getToken());
4692 if (inputChannel != nullptr) {
4693 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4694 "touched window's orientation changed");
4695 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4696 }
4697 }
4698 }
4699 }
4700
Arthur Hung72d8dc32020-03-28 00:48:39 +00004701 // Release information for windows that are no longer present.
4702 // This ensures that unused input channels are released promptly.
4703 // Otherwise, they might stick around until the window handle is destroyed
4704 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004705 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004706 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004707 if (DEBUG_FOCUS) {
4708 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004709 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004710 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004711 // To avoid making too many calls into the compat framework, only
4712 // check for window flags when windows are going away.
4713 // TODO(b/157929241) : delete this. This is only needed temporarily
4714 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004715 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004716 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4717 oldWindowHandle->getName().c_str());
4718 if (mCompatService != nullptr) {
4719 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4720 oldWindowHandle->getInfo()->ownerUid);
4721 }
4722 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004723 }
chaviw291d88a2019-02-14 10:33:58 -08004724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725}
4726
4727void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004728 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004729 if (DEBUG_FOCUS) {
4730 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4731 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4732 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004733 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004734 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004735 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 } // release lock
4737
4738 // Wake up poll loop since it may need to make new input dispatching choices.
4739 mLooper->wake();
4740}
4741
Vishnu Nair599f1412021-06-21 10:39:58 -07004742void InputDispatcher::setFocusedApplicationLocked(
4743 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4744 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4745 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4746
4747 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4748 return; // This application is already focused. No need to wake up or change anything.
4749 }
4750
4751 // Set the new application handle.
4752 if (inputApplicationHandle != nullptr) {
4753 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4754 } else {
4755 mFocusedApplicationHandlesByDisplay.erase(displayId);
4756 }
4757
4758 // No matter what the old focused application was, stop waiting on it because it is
4759 // no longer focused.
4760 resetNoFocusedWindowTimeoutLocked();
4761}
4762
Tiger Huang721e26f2018-07-24 22:26:19 +08004763/**
4764 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4765 * the display not specified.
4766 *
4767 * We track any unreleased events for each window. If a window loses the ability to receive the
4768 * released event, we will send a cancel event to it. So when the focused display is changed, we
4769 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4770 * display. The display-specified events won't be affected.
4771 */
4772void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004773 if (DEBUG_FOCUS) {
4774 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4775 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004776 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004777 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004778
4779 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004780 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004781 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004782 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004783 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004784 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004785 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004786 CancelationOptions
4787 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4788 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004789 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004790 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4791 }
4792 }
4793 mFocusedDisplayId = displayId;
4794
Chris Ye3c2d6f52020-08-09 10:39:48 -07004795 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004796 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004797 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004798
Vishnu Nairad321cd2020-08-20 16:40:21 -07004799 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004800 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004801 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004802 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004803 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004804 }
4805 }
4806 }
4807
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004808 if (DEBUG_FOCUS) {
4809 logDispatchStateLocked();
4810 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004811 } // release lock
4812
4813 // Wake up poll loop since it may need to make new input dispatching choices.
4814 mLooper->wake();
4815}
4816
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004818 if (DEBUG_FOCUS) {
4819 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821
4822 bool changed;
4823 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825
4826 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4827 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 }
4830
4831 if (mDispatchEnabled && !enabled) {
4832 resetAndDropEverythingLocked("dispatcher is being disabled");
4833 }
4834
4835 mDispatchEnabled = enabled;
4836 mDispatchFrozen = frozen;
4837 changed = true;
4838 } else {
4839 changed = false;
4840 }
4841
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004842 if (DEBUG_FOCUS) {
4843 logDispatchStateLocked();
4844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 } // release lock
4846
4847 if (changed) {
4848 // Wake up poll loop since it may need to make new input dispatching choices.
4849 mLooper->wake();
4850 }
4851}
4852
4853void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004854 if (DEBUG_FOCUS) {
4855 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857
4858 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004859 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860
4861 if (mInputFilterEnabled == enabled) {
4862 return;
4863 }
4864
4865 mInputFilterEnabled = enabled;
4866 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4867 } // release lock
4868
4869 // Wake up poll loop since there might be work to do to drop everything.
4870 mLooper->wake();
4871}
4872
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004873void InputDispatcher::setInTouchMode(bool inTouchMode) {
4874 std::scoped_lock lock(mLock);
4875 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004876 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004877}
4878
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004879void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4880 if (opacity < 0 || opacity > 1) {
4881 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4882 return;
4883 }
4884
4885 std::scoped_lock lock(mLock);
4886 mMaximumObscuringOpacityForTouch = opacity;
4887}
4888
4889void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4890 std::scoped_lock lock(mLock);
4891 mBlockUntrustedTouchesMode = mode;
4892}
4893
Arthur Hungabbb9d82021-09-01 14:52:30 +00004894std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4895 const sp<IBinder>& token) {
4896 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4897 for (TouchedWindow& w : state.windows) {
4898 if (w.windowHandle->getToken() == token) {
4899 return std::make_pair(&state, &w);
4900 }
4901 }
4902 }
4903 return std::make_pair(nullptr, nullptr);
4904}
4905
arthurhungb89ccb02020-12-30 16:19:01 +08004906bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4907 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004908 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004909 if (DEBUG_FOCUS) {
4910 ALOGD("Trivial transfer to same window.");
4911 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004912 return true;
4913 }
4914
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004916 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917
Arthur Hungabbb9d82021-09-01 14:52:30 +00004918 // Find the target touch state and touched window by fromToken.
4919 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4920 if (state == nullptr || touchedWindow == nullptr) {
4921 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 return false;
4923 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004924
4925 const int32_t displayId = state->displayId;
4926 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4927 if (toWindowHandle == nullptr) {
4928 ALOGW("Cannot transfer focus because to window not found.");
4929 return false;
4930 }
4931
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004932 if (DEBUG_FOCUS) {
4933 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004934 touchedWindow->windowHandle->getName().c_str(),
4935 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 }
4937
Arthur Hungabbb9d82021-09-01 14:52:30 +00004938 // Erase old window.
4939 int32_t oldTargetFlags = touchedWindow->targetFlags;
4940 BitSet32 pointerIds = touchedWindow->pointerIds;
4941 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942
Arthur Hungabbb9d82021-09-01 14:52:30 +00004943 // Add new window.
4944 int32_t newTargetFlags = oldTargetFlags &
4945 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4946 InputTarget::FLAG_DISPATCH_AS_IS);
4947 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948
Arthur Hungabbb9d82021-09-01 14:52:30 +00004949 // Store the dragging window.
4950 if (isDragDrop) {
4951 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 }
4953
Arthur Hungabbb9d82021-09-01 14:52:30 +00004954 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004955 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4956 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004957 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004958 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004959 CancelationOptions
4960 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4961 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004963 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964 }
4965
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004966 if (DEBUG_FOCUS) {
4967 logDispatchStateLocked();
4968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 } // release lock
4970
4971 // Wake up poll loop since it may need to make new input dispatching choices.
4972 mLooper->wake();
4973 return true;
4974}
4975
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004976// Binder call
4977bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4978 sp<IBinder> fromToken;
4979 { // acquire lock
4980 std::scoped_lock _l(mLock);
4981
Arthur Hungabbb9d82021-09-01 14:52:30 +00004982 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
4983 [](const auto& pair) { return pair.second.windows.size() == 1; });
4984 if (it == mTouchStatesByDisplay.end()) {
4985 ALOGW("Cannot transfer touch state because there is no exact window being touched");
4986 return false;
4987 }
4988 const int32_t displayId = it->first;
4989 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004990 if (toWindowHandle == nullptr) {
4991 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4992 return false;
4993 }
4994
Arthur Hungabbb9d82021-09-01 14:52:30 +00004995 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004996 const TouchedWindow& touchedWindow = state.windows[0];
4997 fromToken = touchedWindow.windowHandle->getToken();
4998 } // release lock
4999
5000 return transferTouchFocus(fromToken, destChannelToken);
5001}
5002
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005004 if (DEBUG_FOCUS) {
5005 ALOGD("Resetting and dropping all events (%s).", reason);
5006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007
5008 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5009 synthesizeCancelationEventsForAllConnectionsLocked(options);
5010
5011 resetKeyRepeatLocked();
5012 releasePendingEventLocked();
5013 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005016 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005017 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005019 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020}
5021
5022void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005023 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 dumpDispatchStateLocked(dump);
5025
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005026 std::istringstream stream(dump);
5027 std::string line;
5028
5029 while (std::getline(stream, line, '\n')) {
5030 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031 }
5032}
5033
Prabir Pradhan99987712020-11-10 18:43:05 -08005034std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5035 std::string dump;
5036
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005037 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5038 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005039
5040 std::string windowName = "None";
5041 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005042 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005043 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5044 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5045 : "token has capture without window";
5046 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005047 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005048
5049 return dump;
5050}
5051
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005052void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005053 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5054 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5055 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005056 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057
Tiger Huang721e26f2018-07-24 22:26:19 +08005058 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5059 dump += StringPrintf(INDENT "FocusedApplications:\n");
5060 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5061 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005062 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005063 const std::chrono::duration timeout =
5064 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005065 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005066 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005067 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005070 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005072
Vishnu Nairc519ff72021-01-21 08:23:08 -08005073 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005074 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005076 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005077 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005078 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5079 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005080 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005081 state.displayId, toString(state.down), toString(state.split),
5082 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005083 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005084 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005085 for (size_t i = 0; i < state.windows.size(); i++) {
5086 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005087 dump += StringPrintf(INDENT4
5088 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5089 i, touchedWindow.windowHandle->getName().c_str(),
5090 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005091 }
5092 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005093 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 }
5096 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005097 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 }
5099
arthurhung6d4bed92021-03-17 11:59:33 +08005100 if (mDragState) {
5101 dump += StringPrintf(INDENT "DragState:\n");
5102 mDragState->dump(dump, INDENT2);
5103 }
5104
Arthur Hungb92218b2018-08-14 12:00:21 +08005105 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005106 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5107 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5108 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5109 const auto& displayInfo = it->second;
5110 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5111 displayInfo.logicalHeight);
5112 displayInfo.transform.dump(dump, "transform", INDENT4);
5113 } else {
5114 dump += INDENT2 "No DisplayInfo found!\n";
5115 }
5116
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005117 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005118 dump += INDENT2 "Windows:\n";
5119 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005120 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5121 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005123 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005124 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005125 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005126 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005127 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005128 "applicationInfo.name=%s, "
5129 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005130 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005131 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005132 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005133 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005134 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005135 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005136 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005137 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005138 windowInfo->frameLeft, windowInfo->frameTop,
5139 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005140 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005141 windowInfo->applicationInfo.name.c_str(),
5142 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005143 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005144 dump += StringPrintf(", inputFeatures=%s",
5145 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005146 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005147 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005148 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005149 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005150 millis(windowInfo->dispatchingTimeout),
5151 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005152 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005153 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005154 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005155 }
5156 } else {
5157 dump += INDENT2 "Windows: <none>\n";
5158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005161 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163
Michael Wright3dd60e22019-03-27 22:06:44 +00005164 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005165 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005166 const std::vector<Monitor>& monitors = it.second;
5167 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5168 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005169 }
5170 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005171 const std::vector<Monitor>& monitors = it.second;
5172 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5173 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005176 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 }
5178
5179 nsecs_t currentTime = now();
5180
5181 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005182 if (!mRecentQueue.empty()) {
5183 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005184 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005185 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005186 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005187 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 }
5189 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005190 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 }
5192
5193 // Dump event currently being dispatched.
5194 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005195 dump += INDENT "PendingEvent:\n";
5196 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005197 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005198 dump += StringPrintf(", age=%" PRId64 "ms\n",
5199 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005201 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 }
5203
5204 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005205 if (!mInboundQueue.empty()) {
5206 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005207 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005208 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005209 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005210 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211 }
5212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005213 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 }
5215
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005216 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005217 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005218 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5219 const KeyReplacement& replacement = pair.first;
5220 int32_t newKeyCode = pair.second;
5221 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005222 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005223 }
5224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005225 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005226 }
5227
Prabir Pradhancef936d2021-07-21 16:17:52 +00005228 if (!mCommandQueue.empty()) {
5229 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5230 } else {
5231 dump += INDENT "CommandQueue: <empty>\n";
5232 }
5233
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005234 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005235 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005236 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005237 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005238 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005239 connection->inputChannel->getFd().get(),
5240 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005241 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005242 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005244 if (!connection->outboundQueue.empty()) {
5245 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5246 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005247 dump += dumpQueue(connection->outboundQueue, currentTime);
5248
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005250 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251 }
5252
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005253 if (!connection->waitQueue.empty()) {
5254 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5255 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005256 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005258 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 }
5260 }
5261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005262 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
5264
5265 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005266 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5267 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005269 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 }
5271
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005272 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005273 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5274 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5275 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005276 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005277 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278}
5279
Michael Wright3dd60e22019-03-27 22:06:44 +00005280void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5281 const size_t numMonitors = monitors.size();
5282 for (size_t i = 0; i < numMonitors; i++) {
5283 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005284 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005285 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5286 dump += "\n";
5287 }
5288}
5289
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005290class LooperEventCallback : public LooperCallback {
5291public:
5292 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5293 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5294
5295private:
5296 std::function<int(int events)> mCallback;
5297};
5298
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005299Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005300 if (DEBUG_CHANNEL_CREATION) {
5301 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005304 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005305 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005306 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005307
5308 if (result) {
5309 return base::Error(result) << "Failed to open input channel pair with name " << name;
5310 }
5311
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005313 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005314 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005315 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005316 sp<Connection> connection =
5317 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005319 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5320 ALOGE("Created a new connection, but the token %p is already known", token.get());
5321 }
5322 mConnectionsByToken.emplace(token, connection);
5323
5324 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5325 this, std::placeholders::_1, token);
5326
5327 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 } // release lock
5329
5330 // Wake the looper because some connections have changed.
5331 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005332 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333}
5334
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005335Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5336 bool isGestureMonitor,
5337 const std::string& name,
5338 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005339 std::shared_ptr<InputChannel> serverChannel;
5340 std::unique_ptr<InputChannel> clientChannel;
5341 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5342 if (result) {
5343 return base::Error(result) << "Failed to open input channel pair with name " << name;
5344 }
5345
Michael Wright3dd60e22019-03-27 22:06:44 +00005346 { // acquire lock
5347 std::scoped_lock _l(mLock);
5348
5349 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005350 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5351 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005352 }
5353
Garfield Tan15601662020-09-22 15:32:38 -07005354 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005355 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005356 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005357
5358 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5359 ALOGE("Created a new connection, but the token %p is already known", token.get());
5360 }
5361 mConnectionsByToken.emplace(token, connection);
5362 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5363 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005364
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005365 auto& monitorsByDisplay =
5366 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005367 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005368
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005369 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005370 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5371 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005372 }
Garfield Tan15601662020-09-22 15:32:38 -07005373
Michael Wright3dd60e22019-03-27 22:06:44 +00005374 // Wake the looper because some connections have changed.
5375 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005376 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005377}
5378
Garfield Tan15601662020-09-22 15:32:38 -07005379status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005381 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382
Garfield Tan15601662020-09-22 15:32:38 -07005383 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 if (status) {
5385 return status;
5386 }
5387 } // release lock
5388
5389 // Wake the poll loop because removing the connection may have changed the current
5390 // synchronization state.
5391 mLooper->wake();
5392 return OK;
5393}
5394
Garfield Tan15601662020-09-22 15:32:38 -07005395status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5396 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005397 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005398 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005399 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 return BAD_VALUE;
5401 }
5402
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005403 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005404
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005406 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005409 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
5411 nsecs_t currentTime = now();
5412 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5413
5414 connection->status = Connection::STATUS_ZOMBIE;
5415 return OK;
5416}
5417
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005418void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5419 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5420 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005421}
5422
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005423void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005424 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005425 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005426 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005427 std::vector<Monitor>& monitors = it->second;
5428 const size_t numMonitors = monitors.size();
5429 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005430 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005431 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5432 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005433 monitors.erase(monitors.begin() + i);
5434 break;
5435 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005436 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005437 if (monitors.empty()) {
5438 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005439 } else {
5440 ++it;
5441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 }
5443}
5444
Michael Wright3dd60e22019-03-27 22:06:44 +00005445status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5446 { // acquire lock
5447 std::scoped_lock _l(mLock);
5448 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5449
5450 if (!foundDisplayId) {
5451 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5452 return BAD_VALUE;
5453 }
5454 int32_t displayId = foundDisplayId.value();
5455
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005456 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5457 mTouchStatesByDisplay.find(displayId);
5458 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005459 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5460 return BAD_VALUE;
5461 }
5462
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005463 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005464 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005465 std::optional<int32_t> foundDeviceId;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07005466 for (const auto& monitor : state.gestureMonitors) {
5467 if (monitor.inputChannel->getConnectionToken() == token) {
5468 requestingChannel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005469 foundDeviceId = state.deviceId;
5470 }
5471 }
5472 if (!foundDeviceId || !state.down) {
5473 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005474 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005475 return BAD_VALUE;
5476 }
5477 int32_t deviceId = foundDeviceId.value();
5478
5479 // Send cancel events to all the input channels we're stealing from.
5480 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005481 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005482 options.deviceId = deviceId;
5483 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005484 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005485 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005486 std::shared_ptr<InputChannel> channel =
5487 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005488 if (channel != nullptr) {
5489 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005490 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005491 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005492 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005493 canceledWindows += "]";
5494 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5495 canceledWindows.c_str());
5496
Michael Wright3dd60e22019-03-27 22:06:44 +00005497 // Then clear the current touch state so we stop dispatching to them as well.
5498 state.filterNonMonitors();
5499 }
5500 return OK;
5501}
5502
Prabir Pradhan99987712020-11-10 18:43:05 -08005503void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5504 { // acquire lock
5505 std::scoped_lock _l(mLock);
5506 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005507 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005508 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5509 windowHandle != nullptr ? windowHandle->getName().c_str()
5510 : "token without window");
5511 }
5512
Vishnu Nairc519ff72021-01-21 08:23:08 -08005513 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005514 if (focusedToken != windowToken) {
5515 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5516 enabled ? "enable" : "disable");
5517 return;
5518 }
5519
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005520 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005521 ALOGW("Ignoring request to %s Pointer Capture: "
5522 "window has %s requested pointer capture.",
5523 enabled ? "enable" : "disable", enabled ? "already" : "not");
5524 return;
5525 }
5526
Prabir Pradhan99987712020-11-10 18:43:05 -08005527 setPointerCaptureLocked(enabled);
5528 } // release lock
5529
5530 // Wake the thread to process command entries.
5531 mLooper->wake();
5532}
5533
Michael Wright3dd60e22019-03-27 22:06:44 +00005534std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5535 const sp<IBinder>& token) {
5536 for (const auto& it : mGestureMonitorsByDisplay) {
5537 const std::vector<Monitor>& monitors = it.second;
5538 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005539 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005540 return it.first;
5541 }
5542 }
5543 }
5544 return std::nullopt;
5545}
5546
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005547std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5548 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5549 if (gesturePid.has_value()) {
5550 return gesturePid;
5551 }
5552 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5553}
5554
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005555sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005556 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005557 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005558 }
5559
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005560 for (const auto& [token, connection] : mConnectionsByToken) {
5561 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005562 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 }
5564 }
Robert Carr4e670e52018-08-15 13:26:12 -07005565
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005566 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567}
5568
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005569std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5570 sp<Connection> connection = getConnectionLocked(connectionToken);
5571 if (connection == nullptr) {
5572 return "<nullptr>";
5573 }
5574 return connection->getInputChannelName();
5575}
5576
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005577void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005578 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005579 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005580}
5581
Prabir Pradhancef936d2021-07-21 16:17:52 +00005582void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5583 const sp<Connection>& connection, uint32_t seq,
5584 bool handled, nsecs_t consumeTime) {
5585 // Handle post-event policy actions.
5586 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5587 if (dispatchEntryIt == connection->waitQueue.end()) {
5588 return;
5589 }
5590 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5591 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5592 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5593 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5594 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5595 }
5596 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5597 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5598 connection->inputChannel->getConnectionToken(),
5599 dispatchEntry->deliveryTime, consumeTime, finishTime);
5600 }
5601
5602 bool restartEvent;
5603 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5604 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5605 restartEvent =
5606 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5607 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5608 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5609 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5610 handled);
5611 } else {
5612 restartEvent = false;
5613 }
5614
5615 // Dequeue the event and start the next cycle.
5616 // Because the lock might have been released, it is possible that the
5617 // contents of the wait queue to have been drained, so we need to double-check
5618 // a few things.
5619 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5620 if (dispatchEntryIt != connection->waitQueue.end()) {
5621 dispatchEntry = *dispatchEntryIt;
5622 connection->waitQueue.erase(dispatchEntryIt);
5623 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5624 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5625 if (!connection->responsive) {
5626 connection->responsive = isConnectionResponsive(*connection);
5627 if (connection->responsive) {
5628 // The connection was unresponsive, and now it's responsive.
5629 processConnectionResponsiveLocked(*connection);
5630 }
5631 }
5632 traceWaitQueueLength(*connection);
5633 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5634 connection->outboundQueue.push_front(dispatchEntry);
5635 traceOutboundQueueLength(*connection);
5636 } else {
5637 releaseDispatchEntry(dispatchEntry);
5638 }
5639 }
5640
5641 // Start the next dispatch cycle for this connection.
5642 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643}
5644
Prabir Pradhancef936d2021-07-21 16:17:52 +00005645void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5646 const sp<IBinder>& newToken) {
5647 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5648 scoped_unlock unlock(mLock);
5649 mPolicy->notifyFocusChanged(oldToken, newToken);
5650 };
5651 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652}
5653
Prabir Pradhancef936d2021-07-21 16:17:52 +00005654void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5655 auto command = [this, token, x, y]() REQUIRES(mLock) {
5656 scoped_unlock unlock(mLock);
5657 mPolicy->notifyDropWindow(token, x, y);
5658 };
5659 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005660}
5661
Prabir Pradhancef936d2021-07-21 16:17:52 +00005662void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5663 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5664 scoped_unlock unlock(mLock);
5665 mPolicy->notifyUntrustedTouch(obscuringPackage);
5666 };
5667 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005668}
5669
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005670void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5671 if (connection == nullptr) {
5672 LOG_ALWAYS_FATAL("Caller must check for nullness");
5673 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005674 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5675 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005676 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005677 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005678 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005679 return;
5680 }
5681 /**
5682 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5683 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5684 * has changed. This could cause newer entries to time out before the already dispatched
5685 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5686 * processes the events linearly. So providing information about the oldest entry seems to be
5687 * most useful.
5688 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005689 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005690 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5691 std::string reason =
5692 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005693 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005694 ns2ms(currentWait),
5695 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005696 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005697 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005698
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005699 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5700
5701 // Stop waking up for events on this connection, it is already unresponsive
5702 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005703}
5704
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005705void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5706 std::string reason =
5707 StringPrintf("%s does not have a focused window", application->getName().c_str());
5708 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005709
Prabir Pradhancef936d2021-07-21 16:17:52 +00005710 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5711 scoped_unlock unlock(mLock);
5712 mPolicy->notifyNoFocusedWindowAnr(application);
5713 };
5714 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005715}
5716
chaviw98318de2021-05-19 16:45:23 -05005717void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005718 const std::string& reason) {
5719 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5720 updateLastAnrStateLocked(windowLabel, reason);
5721}
5722
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005723void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5724 const std::string& reason) {
5725 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005726 updateLastAnrStateLocked(windowLabel, reason);
5727}
5728
5729void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5730 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005732 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 struct tm tm;
5734 localtime_r(&t, &tm);
5735 char timestr[64];
5736 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005737 mLastAnrState.clear();
5738 mLastAnrState += INDENT "ANR:\n";
5739 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005740 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5741 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005742 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743}
5744
Prabir Pradhancef936d2021-07-21 16:17:52 +00005745void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5746 KeyEntry& entry) {
5747 const KeyEvent event = createKeyEvent(entry);
5748 nsecs_t delay = 0;
5749 { // release lock
5750 scoped_unlock unlock(mLock);
5751 android::base::Timer t;
5752 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5753 entry.policyFlags);
5754 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5755 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5756 std::to_string(t.duration().count()).c_str());
5757 }
5758 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759
5760 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005761 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005762 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005763 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005765 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5766 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768}
5769
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005770void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005771 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5772 scoped_unlock unlock(mLock);
5773 mPolicy->notifyMonitorUnresponsive(pid, reason);
5774 };
5775 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005776}
5777
Prabir Pradhancef936d2021-07-21 16:17:52 +00005778void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005779 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005780 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5781 scoped_unlock unlock(mLock);
5782 mPolicy->notifyWindowUnresponsive(token, reason);
5783 };
5784 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005785}
5786
5787void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005788 auto command = [this, pid]() REQUIRES(mLock) {
5789 scoped_unlock unlock(mLock);
5790 mPolicy->notifyMonitorResponsive(pid);
5791 };
5792 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005793}
5794
Prabir Pradhancef936d2021-07-21 16:17:52 +00005795void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5796 auto command = [this, connectionToken]() REQUIRES(mLock) {
5797 scoped_unlock unlock(mLock);
5798 mPolicy->notifyWindowResponsive(connectionToken);
5799 };
5800 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005801}
5802
5803/**
5804 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5805 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5806 * command entry to the command queue.
5807 */
5808void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5809 std::string reason) {
5810 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5811 if (connection.monitor) {
5812 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5813 reason.c_str());
5814 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5815 if (!pid.has_value()) {
5816 ALOGE("Could not find unresponsive monitor for connection %s",
5817 connection.inputChannel->getName().c_str());
5818 return;
5819 }
5820 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5821 return;
5822 }
5823 // If not a monitor, must be a window
5824 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5825 reason.c_str());
5826 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5827}
5828
5829/**
5830 * Tell the policy that a connection has become responsive so that it can stop ANR.
5831 */
5832void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5833 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5834 if (connection.monitor) {
5835 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5836 if (!pid.has_value()) {
5837 ALOGE("Could not find responsive monitor for connection %s",
5838 connection.inputChannel->getName().c_str());
5839 return;
5840 }
5841 sendMonitorResponsiveCommandLocked(pid.value());
5842 return;
5843 }
5844 // If not a monitor, must be a window
5845 sendWindowResponsiveCommandLocked(connectionToken);
5846}
5847
Prabir Pradhancef936d2021-07-21 16:17:52 +00005848bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005849 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005850 KeyEntry& keyEntry, bool handled) {
5851 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005852 if (!handled) {
5853 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005854 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005855 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005856 return false;
5857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005859 // Get the fallback key state.
5860 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005861 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005862 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005863 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005864 connection->inputState.removeFallbackKey(originalKeyCode);
5865 }
5866
5867 if (handled || !dispatchEntry->hasForegroundTarget()) {
5868 // If the application handles the original key for which we previously
5869 // generated a fallback or if the window is not a foreground window,
5870 // then cancel the associated fallback key, if any.
5871 if (fallbackKeyCode != -1) {
5872 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005873 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5874 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5875 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5876 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5877 keyEntry.policyFlags);
5878 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005879 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881
5882 mLock.unlock();
5883
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005884 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005885 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886
5887 mLock.lock();
5888
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889 // Cancel the fallback key.
5890 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005892 "application handled the original non-fallback key "
5893 "or is no longer a foreground target, "
5894 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895 options.keyCode = fallbackKeyCode;
5896 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005898 connection->inputState.removeFallbackKey(originalKeyCode);
5899 }
5900 } else {
5901 // If the application did not handle a non-fallback key, first check
5902 // that we are in a good state to perform unhandled key event processing
5903 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005904 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005905 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005906 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5907 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5908 "since this is not an initial down. "
5909 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5910 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5911 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 return false;
5913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005915 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005916 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5917 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5918 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5919 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5920 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005921 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922
5923 mLock.unlock();
5924
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005925 bool fallback =
5926 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005927 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005928
5929 mLock.lock();
5930
5931 if (connection->status != Connection::STATUS_NORMAL) {
5932 connection->inputState.removeFallbackKey(originalKeyCode);
5933 return false;
5934 }
5935
5936 // Latch the fallback keycode for this key on an initial down.
5937 // The fallback keycode cannot change at any other point in the lifecycle.
5938 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 fallbackKeyCode = event.getKeyCode();
5941 } else {
5942 fallbackKeyCode = AKEYCODE_UNKNOWN;
5943 }
5944 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5945 }
5946
5947 ALOG_ASSERT(fallbackKeyCode != -1);
5948
5949 // Cancel the fallback key if the policy decides not to send it anymore.
5950 // We will continue to dispatch the key to the policy but we will no
5951 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005952 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5953 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005954 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5955 if (fallback) {
5956 ALOGD("Unhandled key event: Policy requested to send key %d"
5957 "as a fallback for %d, but on the DOWN it had requested "
5958 "to send %d instead. Fallback canceled.",
5959 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5960 } else {
5961 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5962 "but on the DOWN it had requested to send %d. "
5963 "Fallback canceled.",
5964 originalKeyCode, fallbackKeyCode);
5965 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005966 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967
5968 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5969 "canceling fallback, policy no longer desires it");
5970 options.keyCode = fallbackKeyCode;
5971 synthesizeCancelationEventsForConnectionLocked(connection, options);
5972
5973 fallback = false;
5974 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005976 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005977 }
5978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005980 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5981 {
5982 std::string msg;
5983 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5984 connection->inputState.getFallbackKeys();
5985 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5986 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5987 }
5988 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5989 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005991 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005992
5993 if (fallback) {
5994 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005995 keyEntry.eventTime = event.getEventTime();
5996 keyEntry.deviceId = event.getDeviceId();
5997 keyEntry.source = event.getSource();
5998 keyEntry.displayId = event.getDisplayId();
5999 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6000 keyEntry.keyCode = fallbackKeyCode;
6001 keyEntry.scanCode = event.getScanCode();
6002 keyEntry.metaState = event.getMetaState();
6003 keyEntry.repeatCount = event.getRepeatCount();
6004 keyEntry.downTime = event.getDownTime();
6005 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006006
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006007 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6008 ALOGD("Unhandled key event: Dispatching fallback key. "
6009 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6010 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6011 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006012 return true; // restart the event
6013 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006014 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6015 ALOGD("Unhandled key event: No fallback key.");
6016 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006017
6018 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006019 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 }
6021 }
6022 return false;
6023}
6024
Prabir Pradhancef936d2021-07-21 16:17:52 +00006025bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006026 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006027 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 return false;
6029}
6030
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031void InputDispatcher::traceInboundQueueLengthLocked() {
6032 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006033 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034 }
6035}
6036
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006037void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 if (ATRACE_ENABLED()) {
6039 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006040 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6041 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 }
6043}
6044
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006045void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 if (ATRACE_ENABLED()) {
6047 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006048 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6049 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 }
6051}
6052
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006053void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006054 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006056 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 dumpDispatchStateLocked(dump);
6058
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006059 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006060 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006061 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006062 }
6063}
6064
6065void InputDispatcher::monitor() {
6066 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006067 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006069 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070}
6071
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006072/**
6073 * Wake up the dispatcher and wait until it processes all events and commands.
6074 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6075 * this method can be safely called from any thread, as long as you've ensured that
6076 * the work you are interested in completing has already been queued.
6077 */
6078bool InputDispatcher::waitForIdle() {
6079 /**
6080 * Timeout should represent the longest possible time that a device might spend processing
6081 * events and commands.
6082 */
6083 constexpr std::chrono::duration TIMEOUT = 100ms;
6084 std::unique_lock lock(mLock);
6085 mLooper->wake();
6086 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6087 return result == std::cv_status::no_timeout;
6088}
6089
Vishnu Naire798b472020-07-23 13:52:21 -07006090/**
6091 * Sets focus to the window identified by the token. This must be called
6092 * after updating any input window handles.
6093 *
6094 * Params:
6095 * request.token - input channel token used to identify the window that should gain focus.
6096 * request.focusedToken - the token that the caller expects currently to be focused. If the
6097 * specified token does not match the currently focused window, this request will be dropped.
6098 * If the specified focused token matches the currently focused window, the call will succeed.
6099 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6100 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6101 * when requesting the focus change. This determines which request gets
6102 * precedence if there is a focus change request from another source such as pointer down.
6103 */
Vishnu Nair958da932020-08-21 17:12:37 -07006104void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6105 { // acquire lock
6106 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006107 std::optional<FocusResolver::FocusChanges> changes =
6108 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6109 if (changes) {
6110 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006111 }
6112 } // release lock
6113 // Wake up poll loop since it may need to make new input dispatching choices.
6114 mLooper->wake();
6115}
6116
Vishnu Nairc519ff72021-01-21 08:23:08 -08006117void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6118 if (changes.oldFocus) {
6119 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006120 if (focusedInputChannel) {
6121 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6122 "focus left window");
6123 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006124 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006125 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006126 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006127 if (changes.newFocus) {
6128 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006129 }
6130
Prabir Pradhan99987712020-11-10 18:43:05 -08006131 // If a window has pointer capture, then it must have focus. We need to ensure that this
6132 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6133 // If the window loses focus before it loses pointer capture, then the window can be in a state
6134 // where it has pointer capture but not focus, violating the contract. Therefore we must
6135 // dispatch the pointer capture event before the focus event. Since focus events are added to
6136 // the front of the queue (above), we add the pointer capture event to the front of the queue
6137 // after the focus events are added. This ensures the pointer capture event ends up at the
6138 // front.
6139 disablePointerCaptureForcedLocked();
6140
Vishnu Nairc519ff72021-01-21 08:23:08 -08006141 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006142 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006143 }
6144}
Vishnu Nair958da932020-08-21 17:12:37 -07006145
Prabir Pradhan99987712020-11-10 18:43:05 -08006146void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006147 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006148 return;
6149 }
6150
6151 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6152
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006153 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006154 setPointerCaptureLocked(false);
6155 }
6156
6157 if (!mWindowTokenWithPointerCapture) {
6158 // No need to send capture changes because no window has capture.
6159 return;
6160 }
6161
6162 if (mPendingEvent != nullptr) {
6163 // Move the pending event to the front of the queue. This will give the chance
6164 // for the pending event to be dropped if it is a captured event.
6165 mInboundQueue.push_front(mPendingEvent);
6166 mPendingEvent = nullptr;
6167 }
6168
6169 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006170 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006171 mInboundQueue.push_front(std::move(entry));
6172}
6173
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006174void InputDispatcher::setPointerCaptureLocked(bool enable) {
6175 mCurrentPointerCaptureRequest.enable = enable;
6176 mCurrentPointerCaptureRequest.seq++;
6177 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006178 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006179 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006180 };
6181 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006182}
6183
Vishnu Nair599f1412021-06-21 10:39:58 -07006184void InputDispatcher::displayRemoved(int32_t displayId) {
6185 { // acquire lock
6186 std::scoped_lock _l(mLock);
6187 // Set an empty list to remove all handles from the specific display.
6188 setInputWindowsLocked(/* window handles */ {}, displayId);
6189 setFocusedApplicationLocked(displayId, nullptr);
6190 // Call focus resolver to clean up stale requests. This must be called after input windows
6191 // have been removed for the removed display.
6192 mFocusResolver.displayRemoved(displayId);
6193 } // release lock
6194
6195 // Wake up poll loop since it may need to make new input dispatching choices.
6196 mLooper->wake();
6197}
6198
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006199void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6200 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006201 // The listener sends the windows as a flattened array. Separate the windows by display for
6202 // more convenient parsing.
6203 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006204 for (const auto& info : windowInfos) {
6205 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6206 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6207 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006208
6209 { // acquire lock
6210 std::scoped_lock _l(mLock);
6211 mDisplayInfos.clear();
6212 for (const auto& displayInfo : displayInfos) {
6213 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6214 }
6215
6216 for (const auto& [displayId, handles] : handlesPerDisplay) {
6217 setInputWindowsLocked(handles, displayId);
6218 }
6219 }
6220 // Wake up poll loop since it may need to make new input dispatching choices.
6221 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006222}
6223
Vishnu Nair062a8672021-09-03 16:07:44 -07006224bool InputDispatcher::shouldDropInput(
6225 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6226 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6227 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6228 isWindowObscuredLocked(windowHandle))) {
6229 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6230 "%" PRId32 ".",
6231 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6232 windowHandle->getInfo()->inputFeatures.string().c_str(),
6233 windowHandle->getInfo()->displayId);
6234 return true;
6235 }
6236 return false;
6237}
6238
Garfield Tane84e6f92019-08-29 17:28:41 -07006239} // namespace android::inputdispatcher