blob: f094fee282fe367125c148c7c123ea813be4a118 [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 Pradhan81420cc2021-09-06 10:28:50 -0700527bool isFromSource(uint32_t source, uint32_t test) {
528 return (source & test) == test;
529}
530
531vec2 transformWithoutTranslation(const ui::Transform& transform, float x, float y) {
532 const vec2 transformedXy = transform.transform(x, y);
533 const vec2 transformedOrigin = transform.transform(0, 0);
534 return transformedXy - transformedOrigin;
535}
536
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000537} // namespace
538
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539// --- InputDispatcher ---
540
Garfield Tan00f511d2019-06-12 16:55:40 -0700541InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
542 : mPolicy(policy),
543 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700544 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800545 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700546 mAppSwitchSawKeyDown(false),
547 mAppSwitchDueTime(LONG_LONG_MAX),
548 mNextUnblockedEvent(nullptr),
549 mDispatchEnabled(false),
550 mDispatchFrozen(false),
551 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800552 // mInTouchMode will be initialized by the WindowManager to the default device config.
553 // To avoid leaking stack in case that call never comes, and for tests,
554 // initialize it here anyways.
555 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100556 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000557 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800558 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000559 mLatencyAggregator(),
560 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000561 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800563 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564
Yi Kong9b14ac62018-07-17 13:48:38 -0700565 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566
567 policy->getDispatcherConfiguration(&mConfig);
568}
569
570InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000571 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Prabir Pradhancef936d2021-07-21 16:17:52 +0000573 resetKeyRepeatLocked();
574 releasePendingEventLocked();
575 drainInboundQueueLocked();
576 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000578 while (!mConnectionsByToken.empty()) {
579 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000580 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
581 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582 }
583}
584
chaviw15fab6f2021-06-07 14:15:52 -0500585void InputDispatcher::onFirstRef() {
586 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
587}
588
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700589status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700590 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591 return ALREADY_EXISTS;
592 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700593 mThread = std::make_unique<InputThread>(
594 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
595 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596}
597
598status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700599 if (mThread && mThread->isCallingThread()) {
600 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700601 return INVALID_OPERATION;
602 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700603 mThread.reset();
604 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700605}
606
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607void InputDispatcher::dispatchOnce() {
608 nsecs_t nextWakeupTime = LONG_LONG_MAX;
609 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800610 std::scoped_lock _l(mLock);
611 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612
613 // Run a dispatch loop if there are no pending commands.
614 // The dispatch loop might enqueue commands to run afterwards.
615 if (!haveCommandsLocked()) {
616 dispatchOnceInnerLocked(&nextWakeupTime);
617 }
618
619 // Run all pending commands if there are any.
620 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000621 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 nextWakeupTime = LONG_LONG_MIN;
623 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800624
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700625 // If we are still waiting for ack on some events,
626 // we might have to wake up earlier to check if an app is anr'ing.
627 const nsecs_t nextAnrCheck = processAnrsLocked();
628 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
629
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800630 // We are about to enter an infinitely long sleep, because we have no commands or
631 // pending or queued events
632 if (nextWakeupTime == LONG_LONG_MAX) {
633 mDispatcherEnteredIdle.notify_all();
634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 } // release lock
636
637 // Wait for callback or timeout or wake. (make sure we round up, not down)
638 nsecs_t currentTime = now();
639 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
640 mLooper->pollOnce(timeoutMillis);
641}
642
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500644 * Raise ANR if there is no focused window.
645 * Before the ANR is raised, do a final state check:
646 * 1. The currently focused application must be the same one we are waiting for.
647 * 2. Ensure we still don't have a focused window.
648 */
649void InputDispatcher::processNoFocusedWindowAnrLocked() {
650 // Check if the application that we are waiting for is still focused.
651 std::shared_ptr<InputApplicationHandle> focusedApplication =
652 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
653 if (focusedApplication == nullptr ||
654 focusedApplication->getApplicationToken() !=
655 mAwaitedFocusedApplication->getApplicationToken()) {
656 // Unexpected because we should have reset the ANR timer when focused application changed
657 ALOGE("Waited for a focused window, but focused application has already changed to %s",
658 focusedApplication->getName().c_str());
659 return; // The focused application has changed.
660 }
661
chaviw98318de2021-05-19 16:45:23 -0500662 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500663 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
664 if (focusedWindowHandle != nullptr) {
665 return; // We now have a focused window. No need for ANR.
666 }
667 onAnrLocked(mAwaitedFocusedApplication);
668}
669
670/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 * Check if any of the connections' wait queues have events that are too old.
672 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
673 * Return the time at which we should wake up next.
674 */
675nsecs_t InputDispatcher::processAnrsLocked() {
676 const nsecs_t currentTime = now();
677 nsecs_t nextAnrCheck = LONG_LONG_MAX;
678 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
679 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
680 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500681 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700682 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700684 return LONG_LONG_MIN;
685 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500686 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700687 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
688 }
689 }
690
691 // Check if any connection ANRs are due
692 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
693 if (currentTime < nextAnrCheck) { // most likely scenario
694 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
695 }
696
697 // If we reached here, we have an unresponsive connection.
698 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
699 if (connection == nullptr) {
700 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
701 return nextAnrCheck;
702 }
703 connection->responsive = false;
704 // Stop waking up for this unresponsive connection
705 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000706 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 return LONG_LONG_MIN;
708}
709
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500710std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500711 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500713 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500715 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716}
717
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
719 nsecs_t currentTime = now();
720
Jeff Browndc5992e2014-04-11 01:27:26 -0700721 // Reset the key repeat timer whenever normal dispatch is suspended while the
722 // device is in a non-interactive state. This is to ensure that we abort a key
723 // repeat if the device is just coming out of sleep.
724 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 resetKeyRepeatLocked();
726 }
727
728 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
729 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100730 if (DEBUG_FOCUS) {
731 ALOGD("Dispatch frozen. Waiting some more.");
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 return;
734 }
735
736 // Optimize latency of app switches.
737 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
738 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
739 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
740 if (mAppSwitchDueTime < *nextWakeupTime) {
741 *nextWakeupTime = mAppSwitchDueTime;
742 }
743
744 // Ready to start a new event.
745 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700747 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 if (isAppSwitchDue) {
749 // The inbound queue is empty so the app switch key we were waiting
750 // for will never arrive. Stop waiting for it.
751 resetPendingAppSwitchLocked(false);
752 isAppSwitchDue = false;
753 }
754
755 // Synthesize a key repeat if appropriate.
756 if (mKeyRepeatState.lastKeyEntry) {
757 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
758 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
759 } else {
760 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
761 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
762 }
763 }
764 }
765
766 // Nothing to do if there is no pending event.
767 if (!mPendingEvent) {
768 return;
769 }
770 } else {
771 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 mPendingEvent = mInboundQueue.front();
773 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 traceInboundQueueLengthLocked();
775 }
776
777 // Poke user activity for this event.
778 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700779 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
782
783 // Now we have an event to dispatch.
784 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700787 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700791 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700795 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700799 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700800 const ConfigurationChangedEntry& typedEntry =
801 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700807 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 const DeviceResetEntry& typedEntry =
809 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700810 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 break;
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100815 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 std::shared_ptr<FocusEntry> typedEntry =
817 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100818 dispatchFocusLocked(currentTime, typedEntry);
819 done = true;
820 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
821 break;
822 }
823
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700824 case EventEntry::Type::TOUCH_MODE_CHANGED: {
825 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
826 dispatchTouchModeChangeLocked(currentTime, typedEntry);
827 done = true;
828 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
829 break;
830 }
831
Prabir Pradhan99987712020-11-10 18:43:05 -0800832 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
833 const auto typedEntry =
834 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
835 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
836 done = true;
837 break;
838 }
839
arthurhungb89ccb02020-12-30 16:19:01 +0800840 case EventEntry::Type::DRAG: {
841 std::shared_ptr<DragEntry> typedEntry =
842 std::static_pointer_cast<DragEntry>(mPendingEvent);
843 dispatchDragLocked(currentTime, typedEntry);
844 done = true;
845 break;
846 }
847
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700848 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700851 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 resetPendingAppSwitchLocked(true);
853 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700854 } else if (dropReason == DropReason::NOT_DROPPED) {
855 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 }
857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
862 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700864 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 break;
866 }
867
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700868 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 std::shared_ptr<MotionEntry> motionEntry =
870 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
872 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
878 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 }
Chris Yef59a2f42020-10-16 12:55:26 -0700883
884 case EventEntry::Type::SENSOR: {
885 std::shared_ptr<SensorEntry> sensorEntry =
886 std::static_pointer_cast<SensorEntry>(mPendingEvent);
887 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
888 dropReason = DropReason::APP_SWITCH;
889 }
890 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
891 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
892 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
893 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
894 dropReason = DropReason::STALE;
895 }
896 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
897 done = true;
898 break;
899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901
902 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Michael Wright3a981722015-06-10 15:26:13 +0100906 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
908 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
911}
912
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700913/**
914 * Return true if the events preceding this incoming motion event should be dropped
915 * Return false otherwise (the default behaviour)
916 */
917bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700918 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700919 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700920
921 // Optimize case where the current application is unresponsive and the user
922 // decides to touch a window in a different application.
923 // If the application takes too long to catch up then we drop all events preceding
924 // the touch into the other window.
925 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 int32_t displayId = motionEntry.displayId;
927 int32_t x = static_cast<int32_t>(
928 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
929 int32_t y = static_cast<int32_t>(
930 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500931 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700932 findTouchedWindowAtLocked(displayId, x, y, nullptr);
933 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 touchedWindowHandle->getApplicationToken() !=
935 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700936 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937 ALOGI("Pruning input queue because user touched a different application while waiting "
938 "for %s",
939 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700940 return true;
941 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942
943 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700944 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700946 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000947 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948 // This monitor could take more input. Drop all events preceding this
949 // event, so that gesture monitor could get a chance to receive the stream
950 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
951 "responsive gesture monitor that may handle the event",
952 mAwaitedFocusedApplication->getName().c_str());
953 return true;
954 }
955 }
956 }
957
958 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
959 // yet been processed by some connections, the dispatcher will wait for these motion
960 // events to be processed before dispatching the key event. This is because these motion events
961 // may cause a new window to be launched, which the user might expect to receive focus.
962 // To prevent waiting forever for such events, just send the key to the currently focused window
963 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
964 ALOGD("Received a new pointer down event, stop waiting for events to process and "
965 "just send the pending key event to the focused window.");
966 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700967 }
968 return false;
969}
970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700971bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700972 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700973 mInboundQueue.push_back(std::move(newEntry));
974 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 traceInboundQueueLengthLocked();
976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700978 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 // Optimize app switch latency.
980 // If the application takes too long to catch up then we drop all events preceding
981 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700984 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700986 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000988 if (DEBUG_APP_SWITCH) {
989 ALOGD("App switch is pending!");
990 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700991 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 mAppSwitchSawKeyDown = false;
993 needWake = true;
994 }
995 }
996 }
997 break;
998 }
999
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001000 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001001 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1002 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001003 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001005 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001007 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001008 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1009 break;
1010 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001011 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001012 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001013 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001014 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001015 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1016 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001017 // nothing to do
1018 break;
1019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 }
1021
1022 return needWake;
1023}
1024
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001025void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001026 // Do not store sensor event in recent queue to avoid flooding the queue.
1027 if (entry->type != EventEntry::Type::SENSOR) {
1028 mRecentQueue.push_back(entry);
1029 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001030 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001031 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
1033}
1034
chaviw98318de2021-05-19 16:45:23 -05001035sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1036 int32_t y, TouchState* touchState,
1037 bool addOutsideTargets,
1038 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001039 if (addOutsideTargets && touchState == nullptr) {
1040 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001043 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1044 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001045 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001046 continue;
1047 }
chaviw98318de2021-05-19 16:45:23 -05001048 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001050 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051
1052 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001053 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1054 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1055 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1057 // Found window.
1058 return windowHandle;
1059 }
1060 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001061
chaviw98318de2021-05-19 16:45:23 -05001062 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001063 touchState->addOrUpdateWindow(windowHandle,
1064 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1065 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071}
1072
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001073void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 const char* reason;
1075 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001077 if (DEBUG_INBOUND_EVENT_DETAILS) {
1078 ALOGD("Dropped event because policy consumed it.");
1079 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 reason = "inbound event was dropped because the policy consumed it";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::DISABLED:
1083 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 ALOGI("Dropped event because input dispatch is disabled.");
1085 }
1086 reason = "inbound event was dropped because input dispatch is disabled";
1087 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because of pending overdue app switch.");
1090 reason = "inbound event was dropped because of pending overdue app switch";
1091 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001092 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 ALOGI("Dropped event because the current application is not responding and the user "
1094 "has started interacting with a different application.");
1095 reason = "inbound event was dropped because the current application is not responding "
1096 "and the user has started interacting with a different application";
1097 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001098 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 ALOGI("Dropped event because it is stale.");
1100 reason = "inbound event was dropped because it is stale";
1101 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001102 case DropReason::NO_POINTER_CAPTURE:
1103 ALOGI("Dropped event because there is no window with Pointer Capture.");
1104 reason = "inbound event was dropped because there is no window with Pointer Capture";
1105 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001106 case DropReason::NOT_DROPPED: {
1107 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 }
1111
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001112 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001113 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1115 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001118 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001119 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1120 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1122 synthesizeCancelationEventsForAllConnectionsLocked(options);
1123 } else {
1124 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1125 synthesizeCancelationEventsForAllConnectionsLocked(options);
1126 }
1127 break;
1128 }
Chris Yef59a2f42020-10-16 12:55:26 -07001129 case EventEntry::Type::SENSOR: {
1130 break;
1131 }
arthurhungb89ccb02020-12-30 16:19:01 +08001132 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1133 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001134 break;
1135 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001136 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001137 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001138 case EventEntry::Type::CONFIGURATION_CHANGED:
1139 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001140 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001141 break;
1142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144}
1145
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001146static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1148 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149}
1150
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001151bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1152 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1153 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1154 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155}
1156
1157bool InputDispatcher::isAppSwitchPendingLocked() {
1158 return mAppSwitchDueTime != LONG_LONG_MAX;
1159}
1160
1161void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1162 mAppSwitchDueTime = LONG_LONG_MAX;
1163
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001164 if (DEBUG_APP_SWITCH) {
1165 if (handled) {
1166 ALOGD("App switch has arrived.");
1167 } else {
1168 ALOGD("App switch was abandoned.");
1169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171}
1172
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001174 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175}
1176
Prabir Pradhancef936d2021-07-21 16:17:52 +00001177bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001178 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 return false;
1180 }
1181
1182 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001183 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001184 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001185 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1186 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001187 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 return true;
1189}
1190
Prabir Pradhancef936d2021-07-21 16:17:52 +00001191void InputDispatcher::postCommandLocked(Command&& command) {
1192 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193}
1194
1195void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001196 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001198 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 releaseInboundEventLocked(entry);
1200 }
1201 traceInboundQueueLengthLocked();
1202}
1203
1204void InputDispatcher::releasePendingEventLocked() {
1205 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001207 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
1209}
1210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001213 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001214 if (DEBUG_DISPATCH_CYCLE) {
1215 ALOGD("Injected inbound event was dropped.");
1216 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
1219 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001220 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 }
1222 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223}
1224
1225void InputDispatcher::resetKeyRepeatLocked() {
1226 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001227 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229}
1230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1232 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233
Michael Wright2e732952014-09-24 13:26:59 -07001234 uint32_t policyFlags = entry->policyFlags &
1235 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 std::shared_ptr<KeyEntry> newEntry =
1238 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1239 entry->source, entry->displayId, policyFlags, entry->action,
1240 entry->flags, entry->keyCode, entry->scanCode,
1241 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 newEntry->syntheticRepeat = true;
1244 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247}
1248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001251 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1252 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
1255 // Reset key repeating in case a keyboard device was added or removed or something.
1256 resetKeyRepeatLocked();
1257
1258 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001259 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1260 scoped_unlock unlock(mLock);
1261 mPolicy->notifyConfigurationChanged(eventTime);
1262 };
1263 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 return true;
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1268 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001269 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1270 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1271 entry.deviceId);
1272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
liushenxiang42232912021-05-21 20:24:09 +08001274 // Reset key repeating in case a keyboard device was disabled or enabled.
1275 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1276 resetKeyRepeatLocked();
1277 }
1278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001279 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 synthesizeCancelationEventsForAllConnectionsLocked(options);
1282 return true;
1283}
1284
Vishnu Nairad321cd2020-08-20 16:40:21 -07001285void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001286 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001287 if (mPendingEvent != nullptr) {
1288 // Move the pending event to the front of the queue. This will give the chance
1289 // for the pending event to get dispatched to the newly focused window
1290 mInboundQueue.push_front(mPendingEvent);
1291 mPendingEvent = nullptr;
1292 }
1293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 std::unique_ptr<FocusEntry> focusEntry =
1295 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1296 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001297
1298 // This event should go to the front of the queue, but behind all other focus events
1299 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001301 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302 [](const std::shared_ptr<EventEntry>& event) {
1303 return event->type == EventEntry::Type::FOCUS;
1304 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001305
1306 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001308}
1309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001310void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001311 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001312 if (channel == nullptr) {
1313 return; // Window has gone away
1314 }
1315 InputTarget target;
1316 target.inputChannel = channel;
1317 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1318 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001319 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1320 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001321 std::string reason = std::string("reason=").append(entry->reason);
1322 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001323 dispatchEventLocked(currentTime, entry, {target});
1324}
1325
Prabir Pradhan99987712020-11-10 18:43:05 -08001326void InputDispatcher::dispatchPointerCaptureChangedLocked(
1327 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1328 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001329 dropReason = DropReason::NOT_DROPPED;
1330
Prabir Pradhan99987712020-11-10 18:43:05 -08001331 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001333
1334 if (entry->pointerCaptureRequest.enable) {
1335 // Enable Pointer Capture.
1336 if (haveWindowWithPointerCapture &&
1337 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1338 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1339 "to the window.");
1340 }
1341 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 // This can happen if a window requests capture and immediately releases capture.
1343 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001344 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 return;
1346 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001347 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1348 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1349 return;
1350 }
1351
Vishnu Nairc519ff72021-01-21 08:23:08 -08001352 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001353 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1354 mWindowTokenWithPointerCapture = token;
1355 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001356 // Disable Pointer Capture.
1357 // We do not check if the sequence number matches for requests to disable Pointer Capture
1358 // for two reasons:
1359 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1360 // to disable capture with the same sequence number: one generated by
1361 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1362 // Capture being disabled in InputReader.
1363 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1364 // actual Pointer Capture state that affects events being generated by input devices is
1365 // in InputReader.
1366 if (!haveWindowWithPointerCapture) {
1367 // Pointer capture was already forcefully disabled because of focus change.
1368 dropReason = DropReason::NOT_DROPPED;
1369 return;
1370 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001371 token = mWindowTokenWithPointerCapture;
1372 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001373 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001374 setPointerCaptureLocked(false);
1375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 }
1377
1378 auto channel = getInputChannelLocked(token);
1379 if (channel == nullptr) {
1380 // Window has gone away, clean up Pointer Capture state.
1381 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001382 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001383 setPointerCaptureLocked(false);
1384 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001385 return;
1386 }
1387 InputTarget target;
1388 target.inputChannel = channel;
1389 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1390 entry->dispatchInProgress = true;
1391 dispatchEventLocked(currentTime, entry, {target});
1392
1393 dropReason = DropReason::NOT_DROPPED;
1394}
1395
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001396void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1397 const std::shared_ptr<TouchModeEntry>& entry) {
1398 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1399 getWindowHandlesLocked(mFocusedDisplayId);
1400 if (windowHandles.empty()) {
1401 return;
1402 }
1403 const std::vector<InputTarget> inputTargets =
1404 getInputTargetsFromWindowHandlesLocked(windowHandles);
1405 if (inputTargets.empty()) {
1406 return;
1407 }
1408 entry->dispatchInProgress = true;
1409 dispatchEventLocked(currentTime, entry, inputTargets);
1410}
1411
1412std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1413 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1414 std::vector<InputTarget> inputTargets;
1415 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1416 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1417 const sp<IBinder>& token = handle->getToken();
1418 if (token == nullptr) {
1419 continue;
1420 }
1421 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1422 if (channel == nullptr) {
1423 continue; // Window has gone away
1424 }
1425 InputTarget target;
1426 target.inputChannel = channel;
1427 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1428 inputTargets.push_back(target);
1429 }
1430 return inputTargets;
1431}
1432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001436 if (!entry->dispatchInProgress) {
1437 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1438 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1439 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1440 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001441 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 // We have seen two identical key downs in a row which indicates that the device
1443 // driver is automatically generating key repeats itself. We take note of the
1444 // repeat here, but we disable our own next key repeat timer since it is clear that
1445 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001446 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1447 // Make sure we don't get key down from a different device. If a different
1448 // device Id has same key pressed down, the new device Id will replace the
1449 // current one to hold the key repeat with repeat count reset.
1450 // In the future when got a KEY_UP on the device id, drop it and do not
1451 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1453 resetKeyRepeatLocked();
1454 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1455 } else {
1456 // Not a repeat. Save key down state in case we do see a repeat later.
1457 resetKeyRepeatLocked();
1458 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1459 }
1460 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001461 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1462 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001463 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001464 if (DEBUG_INBOUND_EVENT_DETAILS) {
1465 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1466 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 resetKeyRepeatLocked();
1469 }
1470
1471 if (entry->repeatCount == 1) {
1472 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1473 } else {
1474 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1475 }
1476
1477 entry->dispatchInProgress = true;
1478
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481
1482 // Handle case where the policy asked us to try again later last time.
1483 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1484 if (currentTime < entry->interceptKeyWakeupTime) {
1485 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1486 *nextWakeupTime = entry->interceptKeyWakeupTime;
1487 }
1488 return false; // wait until next wakeup
1489 }
1490 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1491 entry->interceptKeyWakeupTime = 0;
1492 }
1493
1494 // Give the policy a chance to intercept the key.
1495 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1496 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001497 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001499
1500 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1501 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1502 };
1503 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 return false; // wait for the command to run
1505 } else {
1506 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1507 }
1508 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001509 if (*dropReason == DropReason::NOT_DROPPED) {
1510 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512 }
1513
1514 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001515 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001517 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1518 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001519 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 return true;
1521 }
1522
1523 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001524 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001525 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001527 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 return false;
1529 }
1530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 return true;
1534 }
1535
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001536 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001537 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538
1539 // Dispatch the key.
1540 dispatchEventLocked(currentTime, entry, inputTargets);
1541 return true;
1542}
1543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001545 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1546 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1547 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1548 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1549 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1550 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1551 entry.metaState, entry.repeatCount, entry.downTime);
1552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553}
1554
Prabir Pradhancef936d2021-07-21 16:17:52 +00001555void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1556 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001557 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001558 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1559 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1560 "source=0x%x, sensorType=%s",
1561 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001562 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001563 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001564 auto command = [this, entry]() REQUIRES(mLock) {
1565 scoped_unlock unlock(mLock);
1566
1567 if (entry->accuracyChanged) {
1568 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1569 }
1570 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1571 entry->hwTimestamp, entry->values);
1572 };
1573 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001574}
1575
1576bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001577 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1578 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001579 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001580 }
Chris Yef59a2f42020-10-16 12:55:26 -07001581 { // acquire lock
1582 std::scoped_lock _l(mLock);
1583
1584 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1585 std::shared_ptr<EventEntry> entry = *it;
1586 if (entry->type == EventEntry::Type::SENSOR) {
1587 it = mInboundQueue.erase(it);
1588 releaseInboundEventLocked(entry);
1589 }
1590 }
1591 }
1592 return true;
1593}
1594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001596 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001597 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001599 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 entry->dispatchInProgress = true;
1601
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001602 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 }
1604
1605 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001606 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001607 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001608 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1609 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 return true;
1611 }
1612
1613 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1614
1615 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001616 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617
1618 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001619 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 if (isPointerEvent) {
1621 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001622 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001624 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 } else {
1626 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001628 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001630 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 return false;
1632 }
1633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001634 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001635 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001636 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1637 return true;
1638 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001639 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001640 CancelationOptions::Mode mode(isPointerEvent
1641 ? CancelationOptions::CANCEL_POINTER_EVENTS
1642 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1643 CancelationOptions options(mode, "input event injection failed");
1644 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 return true;
1646 }
1647
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001648 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650
1651 // Dispatch the motion.
1652 if (conflictingPointerActions) {
1653 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001654 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 synthesizeCancelationEventsForAllConnectionsLocked(options);
1656 }
1657 dispatchEventLocked(currentTime, entry, inputTargets);
1658 return true;
1659}
1660
chaviw98318de2021-05-19 16:45:23 -05001661void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001662 bool isExiting, const MotionEntry& motionEntry) {
1663 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1664 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1665 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1666 PointerCoords pointerCoords;
1667 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1668 pointerCoords.transform(windowHandle->getInfo()->transform);
1669
1670 std::unique_ptr<DragEntry> dragEntry =
1671 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1672 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1673 pointerCoords.getY());
1674
1675 enqueueInboundEventLocked(std::move(dragEntry));
1676}
1677
1678void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1679 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1680 if (channel == nullptr) {
1681 return; // Window has gone away
1682 }
1683 InputTarget target;
1684 target.inputChannel = channel;
1685 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1686 entry->dispatchInProgress = true;
1687 dispatchEventLocked(currentTime, entry, {target});
1688}
1689
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001690void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001691 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1692 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1693 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001694 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001695 "metaState=0x%x, buttonState=0x%x,"
1696 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1697 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001698 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1699 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1700 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001702 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1703 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1704 "x=%f, y=%f, pressure=%f, size=%f, "
1705 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1706 "orientation=%f",
1707 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1708 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1709 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1710 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1711 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1712 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1713 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1714 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719}
1720
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001721void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1722 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001723 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001724 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001725 if (DEBUG_DISPATCH_CYCLE) {
1726 ALOGD("dispatchEventToCurrentInputTargets");
1727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001729 updateInteractionTokensLocked(*eventEntry, inputTargets);
1730
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1732
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001735 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001736 sp<Connection> connection =
1737 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001738 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001739 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001741 if (DEBUG_FOCUS) {
1742 ALOGD("Dropping event delivery to target with channel '%s' because it "
1743 "is no longer registered with the input dispatcher.",
1744 inputTarget.inputChannel->getName().c_str());
1745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 }
1747 }
1748}
1749
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001750void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1751 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1752 // If the policy decides to close the app, we will get a channel removal event via
1753 // unregisterInputChannel, and will clean up the connection that way. We are already not
1754 // sending new pointers to the connection when it blocked, but focused events will continue to
1755 // pile up.
1756 ALOGW("Canceling events for %s because it is unresponsive",
1757 connection->inputChannel->getName().c_str());
1758 if (connection->status == Connection::STATUS_NORMAL) {
1759 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1760 "application not responding");
1761 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 }
1763}
1764
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001766 if (DEBUG_FOCUS) {
1767 ALOGD("Resetting ANR timeouts.");
1768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769
1770 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001771 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001772 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773}
1774
Tiger Huang721e26f2018-07-24 22:26:19 +08001775/**
1776 * Get the display id that the given event should go to. If this event specifies a valid display id,
1777 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1778 * Focused display is the display that the user most recently interacted with.
1779 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001780int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001781 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001782 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001783 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001784 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1785 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 break;
1787 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001788 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1790 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 break;
1792 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001793 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001794 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001795 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001796 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001797 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001798 case EventEntry::Type::SENSOR:
1799 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001800 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 return ADISPLAY_ID_NONE;
1802 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001803 }
1804 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1805}
1806
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001807bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1808 const char* focusedWindowName) {
1809 if (mAnrTracker.empty()) {
1810 // already processed all events that we waited for
1811 mKeyIsWaitingForEventsTimeout = std::nullopt;
1812 return false;
1813 }
1814
1815 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1816 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001817 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001818 mKeyIsWaitingForEventsTimeout = currentTime +
1819 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1820 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821 return true;
1822 }
1823
1824 // We still have pending events, and already started the timer
1825 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1826 return true; // Still waiting
1827 }
1828
1829 // Waited too long, and some connection still hasn't processed all motions
1830 // Just send the key to the focused window
1831 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1832 focusedWindowName);
1833 mKeyIsWaitingForEventsTimeout = std::nullopt;
1834 return false;
1835}
1836
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1838 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1839 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001840 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841
Tiger Huang721e26f2018-07-24 22:26:19 +08001842 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001843 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001844 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001845 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1846
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 // If there is no currently focused window and no focused application
1848 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1850 ALOGI("Dropping %s event because there is no focused window or focused application in "
1851 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001852 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001853 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 }
1855
Vishnu Nair062a8672021-09-03 16:07:44 -07001856 // Drop key events if requested by input feature
1857 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1858 return InputEventInjectionResult::FAILED;
1859 }
1860
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001861 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1862 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1863 // start interacting with another application via touch (app switch). This code can be removed
1864 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1865 // an app is expected to have a focused window.
1866 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1867 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1868 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001869 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1870 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1871 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001872 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001873 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001874 ALOGW("Waiting because no window has focus but %s may eventually add a "
1875 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001876 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001877 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1880 // Already raised ANR. Drop the event
1881 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001882 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001883 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 } else {
1885 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887 }
1888 }
1889
1890 // we have a valid, non-null focused window
1891 resetNoFocusedWindowTimeoutLocked();
1892
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001894 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 }
1897
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 if (focusedWindowHandle->getInfo()->paused) {
1899 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001901 }
1902
1903 // If the event is a key event, then we must wait for all previous events to
1904 // complete before delivering it because previous events may have the
1905 // side-effect of transferring focus to a different window and we want to
1906 // ensure that the following keys are sent to the new window.
1907 //
1908 // Suppose the user touches a button in a window then immediately presses "A".
1909 // If the button causes a pop-up window to appear then we want to ensure that
1910 // the "A" key is delivered to the new pop-up window. This is because users
1911 // often anticipate pending UI changes when typing on a keyboard.
1912 // To obtain this behavior, we must serialize key events with respect to all
1913 // prior input events.
1914 if (entry.type == EventEntry::Type::KEY) {
1915 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1916 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 }
1920
1921 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001922 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001923 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1924 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925
1926 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928}
1929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930/**
1931 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1932 * that are currently unresponsive.
1933 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001934std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1935 const std::vector<Monitor>& monitors) const {
1936 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001937 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001938 [this](const Monitor& monitor) REQUIRES(mLock) {
1939 sp<Connection> connection =
1940 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 if (connection == nullptr) {
1942 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001943 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 return false;
1945 }
1946 if (!connection->responsive) {
1947 ALOGW("Unresponsive monitor %s will not get the new gesture",
1948 connection->inputChannel->getName().c_str());
1949 return false;
1950 }
1951 return true;
1952 });
1953 return responsiveMonitors;
1954}
1955
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001956InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1957 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1958 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 enum InjectionPermission {
1961 INJECTION_PERMISSION_UNKNOWN,
1962 INJECTION_PERMISSION_GRANTED,
1963 INJECTION_PERMISSION_DENIED
1964 };
1965
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 // For security reasons, we defer updating the touch state until we are sure that
1967 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001968 int32_t displayId = entry.displayId;
1969 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1971
1972 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001975 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1976 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001978 // Copy current touch state into tempTouchState.
1979 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1980 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001981 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001982 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001983 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1984 mTouchStatesByDisplay.find(displayId);
1985 if (oldStateIt != mTouchStatesByDisplay.end()) {
1986 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001987 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001988 }
1989
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001990 bool isSplit = tempTouchState.split;
1991 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1992 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1993 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001994 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1995 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1996 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1997 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1998 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001999 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 bool wrongDevice = false;
2001 if (newGesture) {
2002 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002004 ALOGI("Dropping event because a pointer for a different device is already down "
2005 "in display %" PRId32,
2006 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002007 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002008 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 switchedDevice = false;
2010 wrongDevice = true;
2011 goto Failed;
2012 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 tempTouchState.reset();
2014 tempTouchState.down = down;
2015 tempTouchState.deviceId = entry.deviceId;
2016 tempTouchState.source = entry.source;
2017 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002019 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002020 ALOGI("Dropping move event because a pointer for a different device is already active "
2021 "in display %" PRId32,
2022 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002023 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002024 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002025 switchedDevice = false;
2026 wrongDevice = true;
2027 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 }
2029
2030 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2031 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2032
Garfield Tan00f511d2019-06-12 16:55:40 -07002033 int32_t x;
2034 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002036 // Always dispatch mouse events to cursor position.
2037 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002038 x = int32_t(entry.xCursorPosition);
2039 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002040 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002041 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2042 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002043 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002044 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002045 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2046 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002047
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002049 if (newTouchedWindowHandle != nullptr &&
2050 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002051 // New window supports splitting, but we should never split mouse events.
2052 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 } else if (isSplit) {
2054 // New window does not support splitting but we have already split events.
2055 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002056 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058
2059 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002060 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002062 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 }
2064
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002065 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2066 ALOGI("Not sending touch event to %s because it is paused",
2067 newTouchedWindowHandle->getName().c_str());
2068 newTouchedWindowHandle = nullptr;
2069 }
2070
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002071 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002073 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2074 if (!isResponsive) {
2075 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002076 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2077 newTouchedWindowHandle = nullptr;
2078 }
2079 }
2080
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002081 // Drop events that can't be trusted due to occlusion
2082 if (newTouchedWindowHandle != nullptr &&
2083 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2084 TouchOcclusionInfo occlusionInfo =
2085 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002086 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002087 if (DEBUG_TOUCH_OCCLUSION) {
2088 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2089 for (const auto& log : occlusionInfo.debugInfo) {
2090 ALOGD("%s", log.c_str());
2091 }
2092 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002093 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002094 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2095 ALOGW("Dropping untrusted touch event due to %s/%d",
2096 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2097 newTouchedWindowHandle = nullptr;
2098 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002099 }
2100 }
2101
Vishnu Nair062a8672021-09-03 16:07:44 -07002102 // Drop touch events if requested by input feature
2103 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2104 newTouchedWindowHandle = nullptr;
2105 }
2106
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002107 const std::vector<Monitor> newGestureMonitors = isDown
2108 ? selectResponsiveMonitorsLocked(
2109 getValueByKey(mGestureMonitorsByDisplay, displayId))
2110 : std::vector<Monitor>{};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111
Michael Wright3dd60e22019-03-27 22:06:44 +00002112 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2113 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002114 "(%d, %d) in display %" PRId32 ".",
2115 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002116 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002117 goto Failed;
2118 }
2119
2120 if (newTouchedWindowHandle != nullptr) {
2121 // Set target flags.
2122 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2123 if (isSplit) {
2124 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002126 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2127 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2128 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2129 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2130 }
2131
2132 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002133 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2134 newHoverWindowHandle = nullptr;
2135 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002136 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002137 }
2138
2139 // Update the temporary touch state.
2140 BitSet32 pointerIds;
2141 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002142 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 pointerIds.markBit(pointerId);
2144 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002145 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 }
2147
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 } else {
2150 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2151
2152 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002154 if (DEBUG_FOCUS) {
2155 ALOGD("Dropping event because the pointer is not down or we previously "
2156 "dropped the pointer down event in display %" PRId32,
2157 displayId);
2158 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002159 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 goto Failed;
2161 }
2162
arthurhung6d4bed92021-03-17 11:59:33 +08002163 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002164
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002166 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002167 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002168 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2169 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170
chaviw98318de2021-05-19 16:45:23 -05002171 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002172 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002173 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002174
2175 // Drop touch events if requested by input feature
2176 if (newTouchedWindowHandle != nullptr &&
2177 shouldDropInput(entry, newTouchedWindowHandle)) {
2178 newTouchedWindowHandle = nullptr;
2179 }
2180
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2182 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002183 if (DEBUG_FOCUS) {
2184 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2185 oldTouchedWindowHandle->getName().c_str(),
2186 newTouchedWindowHandle->getName().c_str(), displayId);
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2190 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2191 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192
2193 // Make a slippery entrance into the new window.
2194 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2195 isSplit = true;
2196 }
2197
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 int32_t targetFlags =
2199 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 if (isSplit) {
2201 targetFlags |= InputTarget::FLAG_SPLIT;
2202 }
2203 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2204 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002205 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2206 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
2208
2209 BitSet32 pointerIds;
2210 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002211 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 }
2215 }
2216 }
2217
2218 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002219 // Let the previous window know that the hover sequence is over, unless we already did it
2220 // when dispatching it as is to newTouchedWindowHandle.
2221 if (mLastHoverWindowHandle != nullptr &&
2222 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2223 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002224 if (DEBUG_HOVER) {
2225 ALOGD("Sending hover exit event to window %s.",
2226 mLastHoverWindowHandle->getName().c_str());
2227 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002228 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2229 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
Garfield Tandf26e862020-07-01 20:18:19 -07002232 // Let the new window know that the hover sequence is starting, unless we already did it
2233 // when dispatching it as is to newTouchedWindowHandle.
2234 if (newHoverWindowHandle != nullptr &&
2235 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2236 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002237 if (DEBUG_HOVER) {
2238 ALOGD("Sending hover enter event to window %s.",
2239 newHoverWindowHandle->getName().c_str());
2240 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002241 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2242 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2243 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
2245 }
2246
2247 // Check permission to inject into all touched foreground windows and ensure there
2248 // is at least one touched foreground window.
2249 {
2250 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2253 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002254 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002255 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 injectionPermission = INJECTION_PERMISSION_DENIED;
2257 goto Failed;
2258 }
2259 }
2260 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002261 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002262 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002263 ALOGI("Dropping event because there is no touched foreground window in display "
2264 "%" PRId32 " or gesture monitor to receive it.",
2265 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002266 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 goto Failed;
2268 }
2269
2270 // Permission granted to injection into all touched foreground windows.
2271 injectionPermission = INJECTION_PERMISSION_GRANTED;
2272 }
2273
2274 // Check whether windows listening for outside touches are owned by the same UID. If it is
2275 // set the policy flag that we will not reveal coordinate information to this window.
2276 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002277 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 if (foregroundWindowHandle) {
2280 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002283 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2284 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2285 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002286 InputTarget::FLAG_ZERO_COORDS,
2287 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290 }
2291 }
2292 }
2293
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 // If this is the first pointer going down and the touched window has a wallpaper
2295 // then also add the touched wallpaper windows so they are locked in for the duration
2296 // of the touch gesture.
2297 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2298 // engine only supports touch events. We would need to add a mechanism similar
2299 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2300 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002301 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002302 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002304 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002305 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002306 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2307 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002309 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002310 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311 .addOrUpdateWindow(windowHandle,
2312 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2313 InputTarget::
2314 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2315 InputTarget::FLAG_DISPATCH_AS_IS,
2316 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318 }
2319 }
2320 }
2321
2322 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002323 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002325 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 }
2329
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002330 for (const auto& monitor : tempTouchState.gestureMonitors) {
2331 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 // Drop the outside or hover touch windows since we will not care about them
2335 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
2338Failed:
2339 // Check injection permission once and for all.
2340 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002341 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 injectionPermission = INJECTION_PERMISSION_GRANTED;
2343 } else {
2344 injectionPermission = INJECTION_PERMISSION_DENIED;
2345 }
2346 }
2347
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002348 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2349 return injectionResult;
2350 }
2351
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 if (!wrongDevice) {
2354 if (switchedDevice) {
2355 if (DEBUG_FOCUS) {
2356 ALOGD("Conflicting pointer actions: Switched to a different device.");
2357 }
2358 *outConflictingPointerActions = true;
2359 }
2360
2361 if (isHoverAction) {
2362 // Started hovering, therefore no longer down.
2363 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002364 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002365 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2366 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 *outConflictingPointerActions = true;
2369 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002370 tempTouchState.reset();
2371 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2372 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2373 tempTouchState.deviceId = entry.deviceId;
2374 tempTouchState.source = entry.source;
2375 tempTouchState.displayId = displayId;
2376 }
2377 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2378 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2379 // All pointers up or canceled.
2380 tempTouchState.reset();
2381 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2382 // First pointer went down.
2383 if (oldState && oldState->down) {
2384 if (DEBUG_FOCUS) {
2385 ALOGD("Conflicting pointer actions: Down received while already down.");
2386 }
2387 *outConflictingPointerActions = true;
2388 }
2389 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2390 // One pointer went up.
2391 if (isSplit) {
2392 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2393 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002395 for (size_t i = 0; i < tempTouchState.windows.size();) {
2396 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2397 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2398 touchedWindow.pointerIds.clearBit(pointerId);
2399 if (touchedWindow.pointerIds.isEmpty()) {
2400 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2401 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002404 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002406 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002407 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002408
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002409 // Save changes unless the action was scroll in which case the temporary touch
2410 // state was only valid for this one action.
2411 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2412 if (tempTouchState.displayId >= 0) {
2413 mTouchStatesByDisplay[displayId] = tempTouchState;
2414 } else {
2415 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002419 // Update hover state.
2420 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 return injectionResult;
2424}
2425
arthurhung6d4bed92021-03-17 11:59:33 +08002426void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002427 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002428 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002429 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002430 if (dropWindow) {
2431 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002432 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002433 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002434 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002435 }
2436 mDragState.reset();
2437}
2438
2439void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2440 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002441 return;
2442 }
2443
arthurhung6d4bed92021-03-17 11:59:33 +08002444 if (!mDragState->isStartDrag) {
2445 mDragState->isStartDrag = true;
2446 mDragState->isStylusButtonDownAtStart =
2447 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2448 }
2449
arthurhungb89ccb02020-12-30 16:19:01 +08002450 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2451 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2452 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2453 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002454 // Handle the special case : stylus button no longer pressed.
2455 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2456 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2457 finishDragAndDrop(entry.displayId, x, y);
2458 return;
2459 }
2460
chaviw98318de2021-05-19 16:45:23 -05002461 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002462 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002463 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002464 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002465 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2466 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2467 if (mDragState->dragHoverWindowHandle != nullptr) {
2468 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2469 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002470 }
arthurhung6d4bed92021-03-17 11:59:33 +08002471 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002472 }
2473 // enqueue drag location if needed.
2474 if (hoverWindowHandle != nullptr) {
2475 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2476 }
arthurhung6d4bed92021-03-17 11:59:33 +08002477 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2478 finishDragAndDrop(entry.displayId, x, y);
2479 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002480 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002481 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002482 }
2483}
2484
chaviw98318de2021-05-19 16:45:23 -05002485void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486 int32_t targetFlags, BitSet32 pointerIds,
2487 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002488 std::vector<InputTarget>::iterator it =
2489 std::find_if(inputTargets.begin(), inputTargets.end(),
2490 [&windowHandle](const InputTarget& inputTarget) {
2491 return inputTarget.inputChannel->getConnectionToken() ==
2492 windowHandle->getToken();
2493 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002494
chaviw98318de2021-05-19 16:45:23 -05002495 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002496
2497 if (it == inputTargets.end()) {
2498 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002499 std::shared_ptr<InputChannel> inputChannel =
2500 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002501 if (inputChannel == nullptr) {
2502 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2503 return;
2504 }
2505 inputTarget.inputChannel = inputChannel;
2506 inputTarget.flags = targetFlags;
2507 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002508 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2509 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002510 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002511 } else {
2512 ALOGI_IF(isPerWindowInputRotationEnabled(),
2513 "DisplayInfo not found for window on display: %d", windowInfo->displayId);
2514 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002515 inputTargets.push_back(inputTarget);
2516 it = inputTargets.end() - 1;
2517 }
2518
2519 ALOG_ASSERT(it->flags == targetFlags);
2520 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2521
chaviw1ff3d1e2020-07-01 15:53:47 -07002522 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523}
2524
Michael Wright3dd60e22019-03-27 22:06:44 +00002525void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002526 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002527 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2528 mGlobalMonitorsByDisplay.find(displayId);
2529
2530 if (it != mGlobalMonitorsByDisplay.end()) {
2531 const std::vector<Monitor>& monitors = it->second;
2532 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002533 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536}
2537
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002538void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002540 InputTarget target;
2541 target.inputChannel = monitor.inputChannel;
2542 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002543 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002544 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2545 // Input monitors always get un-rotated display coordinates. We undo the display
2546 // rotation that is present in the display transform so that display rotation is not
2547 // applied to these input targets.
2548 const auto& displayInfo = it->second;
2549 int32_t width = displayInfo.logicalWidth;
2550 int32_t height = displayInfo.logicalHeight;
2551 const auto orientation = displayInfo.transform.getOrientation();
2552 uint32_t inverseOrientation = orientation;
2553 if (orientation == ui::Transform::ROT_90) {
2554 inverseOrientation = ui::Transform::ROT_270;
2555 std::swap(width, height);
2556 } else if (orientation == ui::Transform::ROT_270) {
2557 inverseOrientation = ui::Transform::ROT_90;
2558 std::swap(width, height);
2559 }
2560 target.displayTransform =
2561 ui::Transform(inverseOrientation, width, height) * displayInfo.transform;
2562 t = t * target.displayTransform;
2563 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002564 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002565 inputTargets.push_back(target);
2566}
2567
chaviw98318de2021-05-19 16:45:23 -05002568bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 const InjectionState* injectionState) {
2570 if (injectionState &&
2571 (windowHandle == nullptr ||
2572 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2573 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002574 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 "owned by uid %d",
2577 injectionState->injectorPid, injectionState->injectorUid,
2578 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 } else {
2580 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
2583 return false;
2584 }
2585 return true;
2586}
2587
Robert Carrc9bf1d32020-04-13 17:21:08 -07002588/**
2589 * Indicate whether one window handle should be considered as obscuring
2590 * another window handle. We only check a few preconditions. Actually
2591 * checking the bounds is left to the caller.
2592 */
chaviw98318de2021-05-19 16:45:23 -05002593static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2594 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002595 // Compare by token so cloned layers aren't counted
2596 if (haveSameToken(windowHandle, otherHandle)) {
2597 return false;
2598 }
2599 auto info = windowHandle->getInfo();
2600 auto otherInfo = otherHandle->getInfo();
2601 if (!otherInfo->visible) {
2602 return false;
chaviw98318de2021-05-19 16:45:23 -05002603 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002604 // Those act as if they were invisible, so we don't need to flag them.
2605 // We do want to potentially flag touchable windows even if they have 0
2606 // opacity, since they can consume touches and alter the effects of the
2607 // user interaction (eg. apps that rely on
2608 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2609 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2610 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002611 } else if (info->ownerUid == otherInfo->ownerUid) {
2612 // If ownerUid is the same we don't generate occlusion events as there
2613 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002614 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002615 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002616 return false;
2617 } else if (otherInfo->displayId != info->displayId) {
2618 return false;
2619 }
2620 return true;
2621}
2622
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002623/**
2624 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2625 * untrusted, one should check:
2626 *
2627 * 1. If result.hasBlockingOcclusion is true.
2628 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2629 * BLOCK_UNTRUSTED.
2630 *
2631 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2632 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2633 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2634 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2635 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2636 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2637 *
2638 * If neither of those is true, then it means the touch can be allowed.
2639 */
2640InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002641 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2642 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002643 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002644 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002645 TouchOcclusionInfo info;
2646 info.hasBlockingOcclusion = false;
2647 info.obscuringOpacity = 0;
2648 info.obscuringUid = -1;
2649 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002650 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002651 if (windowHandle == otherHandle) {
2652 break; // All future windows are below us. Exit early.
2653 }
chaviw98318de2021-05-19 16:45:23 -05002654 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002655 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2656 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002657 if (DEBUG_TOUCH_OCCLUSION) {
2658 info.debugInfo.push_back(
2659 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2660 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002661 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2662 // we perform the checks below to see if the touch can be propagated or not based on the
2663 // window's touch occlusion mode
2664 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2665 info.hasBlockingOcclusion = true;
2666 info.obscuringUid = otherInfo->ownerUid;
2667 info.obscuringPackage = otherInfo->packageName;
2668 break;
2669 }
2670 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2671 uint32_t uid = otherInfo->ownerUid;
2672 float opacity =
2673 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2674 // Given windows A and B:
2675 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2676 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2677 opacityByUid[uid] = opacity;
2678 if (opacity > info.obscuringOpacity) {
2679 info.obscuringOpacity = opacity;
2680 info.obscuringUid = uid;
2681 info.obscuringPackage = otherInfo->packageName;
2682 }
2683 }
2684 }
2685 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002686 if (DEBUG_TOUCH_OCCLUSION) {
2687 info.debugInfo.push_back(
2688 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2689 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002690 return info;
2691}
2692
chaviw98318de2021-05-19 16:45:23 -05002693std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002694 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002695 return StringPrintf(INDENT2
2696 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2697 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2698 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2699 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002700 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002701 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002702 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2703 info->frameTop, info->frameRight, info->frameBottom,
2704 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002705 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2706 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2707 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002708}
2709
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002710bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2711 if (occlusionInfo.hasBlockingOcclusion) {
2712 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2713 occlusionInfo.obscuringUid);
2714 return false;
2715 }
2716 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2717 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2718 "%.2f, maximum allowed = %.2f)",
2719 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2720 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2721 return false;
2722 }
2723 return true;
2724}
2725
chaviw98318de2021-05-19 16:45:23 -05002726bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002729 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2730 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002731 if (windowHandle == otherHandle) {
2732 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
chaviw98318de2021-05-19 16:45:23 -05002734 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002735 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002736 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 return true;
2738 }
2739 }
2740 return false;
2741}
2742
chaviw98318de2021-05-19 16:45:23 -05002743bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002744 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002745 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2746 const WindowInfo* windowInfo = windowHandle->getInfo();
2747 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002748 if (windowHandle == otherHandle) {
2749 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002750 }
chaviw98318de2021-05-19 16:45:23 -05002751 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002752 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002753 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002754 return true;
2755 }
2756 }
2757 return false;
2758}
2759
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002760std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002761 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002762 if (applicationHandle != nullptr) {
2763 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002764 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 } else {
2766 return applicationHandle->getName();
2767 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002768 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002769 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002771 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 }
2773}
2774
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002775void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002776 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002777 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2778 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002779 // Focus or pointer capture changed events are passed to apps, but do not represent user
2780 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002781 return;
2782 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002783 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002784 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002785 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002786 const WindowInfo* info = focusedWindowHandle->getInfo();
2787 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002788 if (DEBUG_DISPATCH_CYCLE) {
2789 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 return;
2792 }
2793 }
2794
2795 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002796 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002797 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002798 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2799 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002800 return;
2801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002803 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 eventType = USER_ACTIVITY_EVENT_TOUCH;
2805 }
2806 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002808 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002809 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2810 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811 return;
2812 }
2813 eventType = USER_ACTIVITY_EVENT_BUTTON;
2814 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07002816 case EventEntry::Type::TOUCH_MODE_CHANGED: {
2817 break;
2818 }
2819
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002820 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002821 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002822 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002823 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002824 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2825 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002826 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002827 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002828 break;
2829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 }
2831
Prabir Pradhancef936d2021-07-21 16:17:52 +00002832 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2833 REQUIRES(mLock) {
2834 scoped_unlock unlock(mLock);
2835 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2836 };
2837 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838}
2839
2840void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002842 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002843 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002844 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002846 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002847 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002848 ATRACE_NAME(message.c_str());
2849 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002850 if (DEBUG_DISPATCH_CYCLE) {
2851 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2852 "globalScaleFactor=%f, pointerIds=0x%x %s",
2853 connection->getInputChannelName().c_str(), inputTarget.flags,
2854 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2855 inputTarget.getPointerInfoString().c_str());
2856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857
2858 // Skip this event if the connection status is not normal.
2859 // We don't want to enqueue additional outbound events if the connection is broken.
2860 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002861 if (DEBUG_DISPATCH_CYCLE) {
2862 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2863 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 return;
2866 }
2867
2868 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002869 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2870 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2871 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002872 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002874 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002875 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002877 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 if (!splitMotionEntry) {
2879 return; // split event was dropped
2880 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002881 if (DEBUG_FOCUS) {
2882 ALOGD("channel '%s' ~ Split motion event.",
2883 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002885 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002886 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2887 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 return;
2889 }
2890 }
2891
2892 // Not splitting. Enqueue dispatch entries for the event as is.
2893 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2894}
2895
2896void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002898 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002899 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002900 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002902 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002903 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002904 ATRACE_NAME(message.c_str());
2905 }
2906
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002907 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
2909 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002910 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002912 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002914 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002916 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002918 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002920 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
2923 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002924 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 startDispatchCycleLocked(currentTime, connection);
2926 }
2927}
2928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002931 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002933 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2935 connection->getInputChannelName().c_str(),
2936 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002937 ATRACE_NAME(message.c_str());
2938 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002939 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 if (!(inputTargetFlags & dispatchMode)) {
2941 return;
2942 }
2943 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2944
2945 // This is a new event.
2946 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002947 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002948 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002950 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2951 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002955 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002956 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002957 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 dispatchEntry->resolvedAction = keyEntry.action;
2959 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2962 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002963 if (DEBUG_DISPATCH_CYCLE) {
2964 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2965 "event",
2966 connection->getInputChannelName().c_str());
2967 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 return; // skip the inconsistent event
2969 }
2970 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002973 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002974 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002975 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2976 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2977 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2978 static_cast<int32_t>(IdGenerator::Source::OTHER);
2979 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2981 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2982 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2984 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2985 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2986 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2987 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2988 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2989 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2990 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002991 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002992 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 }
2994 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2996 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002997 if (DEBUG_DISPATCH_CYCLE) {
2998 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2999 "enter event",
3000 connection->getInputChannelName().c_str());
3001 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003002 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3003 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003007 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3009 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3010 }
3011 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3012 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3016 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003017 if (DEBUG_DISPATCH_CYCLE) {
3018 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3019 "event",
3020 connection->getInputChannelName().c_str());
3021 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003022 return; // skip the inconsistent event
3023 }
3024
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003025 dispatchEntry->resolvedEventId =
3026 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3027 ? mIdGenerator.nextId()
3028 : motionEntry.id;
3029 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3030 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3031 ") to MotionEvent(id=0x%" PRIx32 ").",
3032 motionEntry.id, dispatchEntry->resolvedEventId);
3033 ATRACE_NAME(message.c_str());
3034 }
3035
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003036 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3037 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3038 // Skip reporting pointer down outside focus to the policy.
3039 break;
3040 }
3041
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003043 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044
3045 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003047 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003048 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003049 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3050 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003051 break;
3052 }
Chris Yef59a2f42020-10-16 12:55:26 -07003053 case EventEntry::Type::SENSOR: {
3054 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3055 break;
3056 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003057 case EventEntry::Type::CONFIGURATION_CHANGED:
3058 case EventEntry::Type::DEVICE_RESET: {
3059 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003060 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003061 break;
3062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 }
3064
3065 // Remember that we are waiting for this dispatch to complete.
3066 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003067 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069
3070 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003071 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003072 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003073}
3074
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003075/**
3076 * This function is purely for debugging. It helps us understand where the user interaction
3077 * was taking place. For example, if user is touching launcher, we will see a log that user
3078 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3079 * We will see both launcher and wallpaper in that list.
3080 * Once the interaction with a particular set of connections starts, no new logs will be printed
3081 * until the set of interacted connections changes.
3082 *
3083 * The following items are skipped, to reduce the logspam:
3084 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3085 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3086 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3087 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3088 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003089 */
3090void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3091 const std::vector<InputTarget>& targets) {
3092 // Skip ACTION_UP events, and all events other than keys and motions
3093 if (entry.type == EventEntry::Type::KEY) {
3094 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3095 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3096 return;
3097 }
3098 } else if (entry.type == EventEntry::Type::MOTION) {
3099 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3100 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3101 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3102 return;
3103 }
3104 } else {
3105 return; // Not a key or a motion
3106 }
3107
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003108 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003109 std::vector<sp<Connection>> newConnections;
3110 for (const InputTarget& target : targets) {
3111 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3112 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3113 continue; // Skip windows that receive ACTION_OUTSIDE
3114 }
3115
3116 sp<IBinder> token = target.inputChannel->getConnectionToken();
3117 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003118 if (connection == nullptr) {
3119 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003120 }
3121 newConnectionTokens.insert(std::move(token));
3122 newConnections.emplace_back(connection);
3123 }
3124 if (newConnectionTokens == mInteractionConnectionTokens) {
3125 return; // no change
3126 }
3127 mInteractionConnectionTokens = newConnectionTokens;
3128
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003129 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003130 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003131 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003132 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003133 std::string message = "Interaction with: " + targetList;
3134 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003135 message += "<none>";
3136 }
3137 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3138}
3139
chaviwfd6d3512019-03-25 13:23:49 -07003140void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003141 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003142 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003143 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3144 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003145 return;
3146 }
3147
Vishnu Nairc519ff72021-01-21 08:23:08 -08003148 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003149 if (focusedToken == token) {
3150 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003151 return;
3152 }
3153
Prabir Pradhancef936d2021-07-21 16:17:52 +00003154 auto command = [this, token]() REQUIRES(mLock) {
3155 scoped_unlock unlock(mLock);
3156 mPolicy->onPointerDownOutsideFocus(token);
3157 };
3158 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159}
3160
3161void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003163 if (ATRACE_ENABLED()) {
3164 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003166 ATRACE_NAME(message.c_str());
3167 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003168 if (DEBUG_DISPATCH_CYCLE) {
3169 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003172 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3173 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003175 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003176 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003177 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
3179 // Publish the event.
3180 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003183 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003184 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3185 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 status = connection->inputPublisher
3189 .publishKeyEvent(dispatchEntry->seq,
3190 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3191 keyEntry.source, keyEntry.displayId,
3192 std::move(hmac), dispatchEntry->resolvedAction,
3193 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3194 keyEntry.scanCode, keyEntry.metaState,
3195 keyEntry.repeatCount, keyEntry.downTime,
3196 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003200 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003201 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205
chaviw82357092020-01-28 13:13:06 -08003206 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003207 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3209 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003210 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003211 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3212 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003213 // Don't apply window scale here since we don't want scale to affect raw
3214 // coordinates. The scale will be sent back to the client and applied
3215 // later when requesting relative coordinates.
3216 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3217 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 }
3219 usingCoords = scaledCoords;
3220 }
3221 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 // We don't want the dispatch target to know.
3223 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003224 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 scaledCoords[i].clear();
3226 }
3227 usingCoords = scaledCoords;
3228 }
3229 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003231 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232
3233 // Publish the motion event.
3234 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003235 .publishMotionEvent(dispatchEntry->seq,
3236 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 motionEntry.deviceId, motionEntry.source,
3238 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003239 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003242 motionEntry.edgeFlags, motionEntry.metaState,
3243 motionEntry.buttonState,
3244 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003245 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003246 motionEntry.xPrecision, motionEntry.yPrecision,
3247 motionEntry.xCursorPosition,
3248 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003249 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 motionEntry.downTime, motionEntry.eventTime,
3251 motionEntry.pointerCount,
3252 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 break;
3254 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003255
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003256 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003258 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003259 focusEntry.id,
3260 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003261 mInTouchMode);
3262 break;
3263 }
3264
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003265 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3266 const TouchModeEntry& touchModeEntry =
3267 static_cast<const TouchModeEntry&>(eventEntry);
3268 status = connection->inputPublisher
3269 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3270 touchModeEntry.inTouchMode);
3271
3272 break;
3273 }
3274
Prabir Pradhan99987712020-11-10 18:43:05 -08003275 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3276 const auto& captureEntry =
3277 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3278 status = connection->inputPublisher
3279 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003280 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003281 break;
3282 }
3283
arthurhungb89ccb02020-12-30 16:19:01 +08003284 case EventEntry::Type::DRAG: {
3285 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3286 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3287 dragEntry.id, dragEntry.x,
3288 dragEntry.y,
3289 dragEntry.isExiting);
3290 break;
3291 }
3292
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003293 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003294 case EventEntry::Type::DEVICE_RESET:
3295 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003296 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003297 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 }
3301
3302 // Check the result.
3303 if (status) {
3304 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003305 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 "This is unexpected because the wait queue is empty, so the pipe "
3308 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003309 "event to it, status=%s(%d)",
3310 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3311 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3313 } else {
3314 // Pipe is full and we are waiting for the app to finish process some events
3315 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003316 if (DEBUG_DISPATCH_CYCLE) {
3317 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3318 "waiting for the application to catch up",
3319 connection->getInputChannelName().c_str());
3320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
3322 } else {
3323 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003324 "status=%s(%d)",
3325 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3326 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3328 }
3329 return;
3330 }
3331
3332 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3334 connection->outboundQueue.end(),
3335 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003336 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003337 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003338 if (connection->responsive) {
3339 mAnrTracker.insert(dispatchEntry->timeoutTime,
3340 connection->inputChannel->getConnectionToken());
3341 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003342 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
3344}
3345
chaviw09c8d2d2020-08-24 15:48:26 -07003346std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3347 size_t size;
3348 switch (event.type) {
3349 case VerifiedInputEvent::Type::KEY: {
3350 size = sizeof(VerifiedKeyEvent);
3351 break;
3352 }
3353 case VerifiedInputEvent::Type::MOTION: {
3354 size = sizeof(VerifiedMotionEvent);
3355 break;
3356 }
3357 }
3358 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3359 return mHmacKeyManager.sign(start, size);
3360}
3361
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003362const std::array<uint8_t, 32> InputDispatcher::getSignature(
3363 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3364 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3365 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3366 // Only sign events up and down events as the purely move events
3367 // are tied to their up/down counterparts so signing would be redundant.
3368 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3369 verifiedEvent.actionMasked = actionMasked;
3370 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003371 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003372 }
3373 return INVALID_HMAC;
3374}
3375
3376const std::array<uint8_t, 32> InputDispatcher::getSignature(
3377 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3378 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3379 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3380 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003381 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003382}
3383
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003386 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003387 if (DEBUG_DISPATCH_CYCLE) {
3388 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3389 connection->getInputChannelName().c_str(), seq, toString(handled));
3390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392 if (connection->status == Connection::STATUS_BROKEN ||
3393 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 return;
3395 }
3396
3397 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003398 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3399 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3400 };
3401 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402}
3403
3404void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 const sp<Connection>& connection,
3406 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003407 if (DEBUG_DISPATCH_CYCLE) {
3408 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3409 connection->getInputChannelName().c_str(), toString(notify));
3410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
3412 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003413 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417
3418 // The connection appears to be unrecoverably broken.
3419 // Ignore already broken or zombie connections.
3420 if (connection->status == Connection::STATUS_NORMAL) {
3421 connection->status = Connection::STATUS_BROKEN;
3422
3423 if (notify) {
3424 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003425 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3426 connection->getInputChannelName().c_str());
3427
3428 auto command = [this, connection]() REQUIRES(mLock) {
3429 if (connection->status == Connection::STATUS_ZOMBIE) return;
3430 scoped_unlock unlock(mLock);
3431 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3432 };
3433 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 }
3435 }
3436}
3437
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003438void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3439 while (!queue.empty()) {
3440 DispatchEntry* dispatchEntry = queue.front();
3441 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003442 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
3444}
3445
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003446void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003448 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450 delete dispatchEntry;
3451}
3452
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003453int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3454 std::scoped_lock _l(mLock);
3455 sp<Connection> connection = getConnectionLocked(connectionToken);
3456 if (connection == nullptr) {
3457 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3458 connectionToken.get(), events);
3459 return 0; // remove the callback
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003462 bool notify;
3463 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3464 if (!(events & ALOOPER_EVENT_INPUT)) {
3465 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3466 "events=0x%x",
3467 connection->getInputChannelName().c_str(), events);
3468 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 }
3470
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003471 nsecs_t currentTime = now();
3472 bool gotOne = false;
3473 status_t status = OK;
3474 for (;;) {
3475 Result<InputPublisher::ConsumerResponse> result =
3476 connection->inputPublisher.receiveConsumerResponse();
3477 if (!result.ok()) {
3478 status = result.error().code();
3479 break;
3480 }
3481
3482 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3483 const InputPublisher::Finished& finish =
3484 std::get<InputPublisher::Finished>(*result);
3485 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3486 finish.consumeTime);
3487 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003488 if (shouldReportMetricsForConnection(*connection)) {
3489 const InputPublisher::Timeline& timeline =
3490 std::get<InputPublisher::Timeline>(*result);
3491 mLatencyTracker
3492 .trackGraphicsLatency(timeline.inputEventId,
3493 connection->inputChannel->getConnectionToken(),
3494 std::move(timeline.graphicsTimeline));
3495 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003496 }
3497 gotOne = true;
3498 }
3499 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003500 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003501 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 return 1;
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 }
3505
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003506 notify = status != DEAD_OBJECT || !connection->monitor;
3507 if (notify) {
3508 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3509 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3510 status);
3511 }
3512 } else {
3513 // Monitor channels are never explicitly unregistered.
3514 // We do it automatically when the remote endpoint is closed so don't warn about them.
3515 const bool stillHaveWindowHandle =
3516 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3517 notify = !connection->monitor && stillHaveWindowHandle;
3518 if (notify) {
3519 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3520 connection->getInputChannelName().c_str(), events);
3521 }
3522 }
3523
3524 // Remove the channel.
3525 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3526 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527}
3528
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003531 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003532 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534}
3535
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003536void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003537 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003538 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3539 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3540}
3541
3542void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3543 const CancelationOptions& options,
3544 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3545 for (const auto& it : monitorsByDisplay) {
3546 const std::vector<Monitor>& monitors = it.second;
3547 for (const Monitor& monitor : monitors) {
3548 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003549 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003550 }
3551}
3552
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003554 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003555 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003556 if (connection == nullptr) {
3557 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003559
3560 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561}
3562
3563void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3564 const sp<Connection>& connection, const CancelationOptions& options) {
3565 if (connection->status == Connection::STATUS_BROKEN) {
3566 return;
3567 }
3568
3569 nsecs_t currentTime = now();
3570
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003571 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003572 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003574 if (cancelationEvents.empty()) {
3575 return;
3576 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003577 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3578 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3579 "with reality: %s, mode=%d.",
3580 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3581 options.mode);
3582 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003583
3584 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003585 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003586 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3587 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003588 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003589 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003590 target.globalScaleFactor = windowInfo->globalScaleFactor;
3591 }
3592 target.inputChannel = connection->inputChannel;
3593 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3594
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003595 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003596 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003597 switch (cancelationEventEntry->type) {
3598 case EventEntry::Type::KEY: {
3599 logOutboundKeyDetails("cancel - ",
3600 static_cast<const KeyEntry&>(*cancelationEventEntry));
3601 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003603 case EventEntry::Type::MOTION: {
3604 logOutboundMotionDetails("cancel - ",
3605 static_cast<const MotionEntry&>(*cancelationEventEntry));
3606 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003608 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003609 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003610 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3611 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003612 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003613 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003614 break;
3615 }
3616 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003617 case EventEntry::Type::DEVICE_RESET:
3618 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003619 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003620 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003621 break;
3622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003625 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3626 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003628
3629 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630}
3631
Svet Ganov5d3bc372020-01-26 23:11:07 -08003632void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3633 const sp<Connection>& connection) {
3634 if (connection->status == Connection::STATUS_BROKEN) {
3635 return;
3636 }
3637
3638 nsecs_t currentTime = now();
3639
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003640 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003641 connection->inputState.synthesizePointerDownEvents(currentTime);
3642
3643 if (downEvents.empty()) {
3644 return;
3645 }
3646
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003647 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003648 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3649 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003650 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003651
3652 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003653 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3655 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003656 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003657 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003658 target.globalScaleFactor = windowInfo->globalScaleFactor;
3659 }
3660 target.inputChannel = connection->inputChannel;
3661 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3662
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003663 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664 switch (downEventEntry->type) {
3665 case EventEntry::Type::MOTION: {
3666 logOutboundMotionDetails("down - ",
3667 static_cast<const MotionEntry&>(*downEventEntry));
3668 break;
3669 }
3670
3671 case EventEntry::Type::KEY:
3672 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003673 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003674 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003675 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003676 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003677 case EventEntry::Type::SENSOR:
3678 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003680 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003681 break;
3682 }
3683 }
3684
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003685 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3686 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003687 }
3688
3689 startDispatchCycleLocked(currentTime, connection);
3690}
3691
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003692std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3693 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 ALOG_ASSERT(pointerIds.value != 0);
3695
3696 uint32_t splitPointerIndexMap[MAX_POINTERS];
3697 PointerProperties splitPointerProperties[MAX_POINTERS];
3698 PointerCoords splitPointerCoords[MAX_POINTERS];
3699
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003700 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 uint32_t splitPointerCount = 0;
3702
3703 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003704 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003706 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 uint32_t pointerId = uint32_t(pointerProperties.id);
3708 if (pointerIds.hasBit(pointerId)) {
3709 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3710 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3711 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003712 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 splitPointerCount += 1;
3714 }
3715 }
3716
3717 if (splitPointerCount != pointerIds.count()) {
3718 // This is bad. We are missing some of the pointers that we expected to deliver.
3719 // Most likely this indicates that we received an ACTION_MOVE events that has
3720 // different pointer ids than we expected based on the previous ACTION_DOWN
3721 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3722 // in this way.
3723 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 "we expected there to be %d pointers. This probably means we received "
3725 "a broken sequence of pointer ids from the input device.",
3726 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003727 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 }
3729
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003730 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3733 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3735 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003736 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 uint32_t pointerId = uint32_t(pointerProperties.id);
3738 if (pointerIds.hasBit(pointerId)) {
3739 if (pointerIds.count() == 1) {
3740 // The first/last pointer went down/up.
3741 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003742 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003743 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3744 ? AMOTION_EVENT_ACTION_CANCEL
3745 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 } else {
3747 // A secondary pointer went down/up.
3748 uint32_t splitPointerIndex = 0;
3749 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3750 splitPointerIndex += 1;
3751 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003752 action = maskedAction |
3753 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 }
3755 } else {
3756 // An unrelated pointer changed.
3757 action = AMOTION_EVENT_ACTION_MOVE;
3758 }
3759 }
3760
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003761 int32_t newId = mIdGenerator.nextId();
3762 if (ATRACE_ENABLED()) {
3763 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3764 ") to MotionEvent(id=0x%" PRIx32 ").",
3765 originalMotionEntry.id, newId);
3766 ATRACE_NAME(message.c_str());
3767 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003768 std::unique_ptr<MotionEntry> splitMotionEntry =
3769 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3770 originalMotionEntry.deviceId, originalMotionEntry.source,
3771 originalMotionEntry.displayId,
3772 originalMotionEntry.policyFlags, action,
3773 originalMotionEntry.actionButton,
3774 originalMotionEntry.flags, originalMotionEntry.metaState,
3775 originalMotionEntry.buttonState,
3776 originalMotionEntry.classification,
3777 originalMotionEntry.edgeFlags,
3778 originalMotionEntry.xPrecision,
3779 originalMotionEntry.yPrecision,
3780 originalMotionEntry.xCursorPosition,
3781 originalMotionEntry.yCursorPosition,
3782 originalMotionEntry.downTime, splitPointerCount,
3783 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003785 if (originalMotionEntry.injectionState) {
3786 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 splitMotionEntry->injectionState->refCount += 1;
3788 }
3789
3790 return splitMotionEntry;
3791}
3792
3793void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003794 if (DEBUG_INBOUND_EVENT_DETAILS) {
3795 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797
3798 bool needWake;
3799 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003800 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003802 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3803 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3804 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 } // release lock
3806
3807 if (needWake) {
3808 mLooper->wake();
3809 }
3810}
3811
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003812/**
3813 * If one of the meta shortcuts is detected, process them here:
3814 * Meta + Backspace -> generate BACK
3815 * Meta + Enter -> generate HOME
3816 * This will potentially overwrite keyCode and metaState.
3817 */
3818void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003820 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3821 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3822 if (keyCode == AKEYCODE_DEL) {
3823 newKeyCode = AKEYCODE_BACK;
3824 } else if (keyCode == AKEYCODE_ENTER) {
3825 newKeyCode = AKEYCODE_HOME;
3826 }
3827 if (newKeyCode != AKEYCODE_UNKNOWN) {
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 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003831 keyCode = newKeyCode;
3832 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3833 }
3834 } else if (action == AKEY_EVENT_ACTION_UP) {
3835 // In order to maintain a consistent stream of up and down events, check to see if the key
3836 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3837 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003838 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003839 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003840 auto replacementIt = mReplacedKeys.find(replacement);
3841 if (replacementIt != mReplacedKeys.end()) {
3842 keyCode = replacementIt->second;
3843 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003844 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3845 }
3846 }
3847}
3848
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003850 if (DEBUG_INBOUND_EVENT_DETAILS) {
3851 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3852 "policyFlags=0x%x, action=0x%x, "
3853 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3854 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3855 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3856 args->downTime);
3857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 if (!validateKeyEvent(args->action)) {
3859 return;
3860 }
3861
3862 uint32_t policyFlags = args->policyFlags;
3863 int32_t flags = args->flags;
3864 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003865 // InputDispatcher tracks and generates key repeats on behalf of
3866 // whatever notifies it, so repeatCount should always be set to 0
3867 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3869 policyFlags |= POLICY_FLAG_VIRTUAL;
3870 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 if (policyFlags & POLICY_FLAG_FUNCTION) {
3873 metaState |= AMETA_FUNCTION_ON;
3874 }
3875
3876 policyFlags |= POLICY_FLAG_TRUSTED;
3877
Michael Wright78f24442014-08-06 15:55:28 -07003878 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003879 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003880
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003882 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003883 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3884 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
Michael Wright2b3c3302018-03-02 17:19:13 +00003886 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003888 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3889 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003890 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 bool needWake;
3894 { // acquire lock
3895 mLock.lock();
3896
3897 if (shouldSendKeyToInputFilterLocked(args)) {
3898 mLock.unlock();
3899
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003900 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3902 return; // event was consumed by the filter
3903 }
3904
3905 mLock.lock();
3906 }
3907
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003908 std::unique_ptr<KeyEntry> newEntry =
3909 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3910 args->displayId, policyFlags, args->action, flags,
3911 keyCode, args->scanCode, metaState, repeatCount,
3912 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003914 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 mLock.unlock();
3916 } // release lock
3917
3918 if (needWake) {
3919 mLooper->wake();
3920 }
3921}
3922
3923bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3924 return mInputFilterEnabled;
3925}
3926
3927void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003928 if (DEBUG_INBOUND_EVENT_DETAILS) {
3929 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3930 "displayId=%" PRId32 ", policyFlags=0x%x, "
3931 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3932 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3933 "yCursorPosition=%f, downTime=%" PRId64,
3934 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3935 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3936 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3937 args->xCursorPosition, args->yCursorPosition, args->downTime);
3938 for (uint32_t i = 0; i < args->pointerCount; i++) {
3939 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3940 "x=%f, y=%f, pressure=%f, size=%f, "
3941 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3942 "orientation=%f",
3943 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3944 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3945 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3946 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3948 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3949 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3950 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3951 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3952 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003955 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3956 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 return;
3958 }
3959
3960 uint32_t policyFlags = args->policyFlags;
3961 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003962
3963 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003964 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003965 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3966 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
3970 bool needWake;
3971 { // acquire lock
3972 mLock.lock();
3973
3974 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003975 ui::Transform displayTransform;
3976 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3977 displayTransform = it->second.transform;
3978 }
3979
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 mLock.unlock();
3981
3982 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003983 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3984 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003985 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003986 displayTransform, args->xPrecision, args->yPrecision,
3987 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003988 args->downTime, args->eventTime, args->pointerCount,
3989 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990
3991 policyFlags |= POLICY_FLAG_FILTERED;
3992 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3993 return; // event was consumed by the filter
3994 }
3995
3996 mLock.lock();
3997 }
3998
3999 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004000 std::unique_ptr<MotionEntry> newEntry =
4001 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4002 args->source, args->displayId, policyFlags,
4003 args->action, args->actionButton, args->flags,
4004 args->metaState, args->buttonState,
4005 args->classification, args->edgeFlags,
4006 args->xPrecision, args->yPrecision,
4007 args->xCursorPosition, args->yCursorPosition,
4008 args->downTime, args->pointerCount,
4009 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004011 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4012 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4013 !mInputFilterEnabled) {
4014 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4015 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4016 }
4017
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004018 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 mLock.unlock();
4020 } // release lock
4021
4022 if (needWake) {
4023 mLooper->wake();
4024 }
4025}
4026
Chris Yef59a2f42020-10-16 12:55:26 -07004027void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 if (DEBUG_INBOUND_EVENT_DETAILS) {
4029 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4030 " sensorType=%s",
4031 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004032 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004033 }
Chris Yef59a2f42020-10-16 12:55:26 -07004034
4035 bool needWake;
4036 { // acquire lock
4037 mLock.lock();
4038
4039 // Just enqueue a new sensor event.
4040 std::unique_ptr<SensorEntry> newEntry =
4041 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4042 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4043 args->sensorType, args->accuracy,
4044 args->accuracyChanged, args->values);
4045
4046 needWake = enqueueInboundEventLocked(std::move(newEntry));
4047 mLock.unlock();
4048 } // release lock
4049
4050 if (needWake) {
4051 mLooper->wake();
4052 }
4053}
4054
Chris Yefb552902021-02-03 17:18:37 -08004055void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004056 if (DEBUG_INBOUND_EVENT_DETAILS) {
4057 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4058 args->deviceId, args->isOn);
4059 }
Chris Yefb552902021-02-03 17:18:37 -08004060 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4061}
4062
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004064 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065}
4066
4067void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004068 if (DEBUG_INBOUND_EVENT_DETAILS) {
4069 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4070 "switchMask=0x%08x",
4071 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
4074 uint32_t policyFlags = args->policyFlags;
4075 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004076 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077}
4078
4079void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004080 if (DEBUG_INBOUND_EVENT_DETAILS) {
4081 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4082 args->deviceId);
4083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
4085 bool needWake;
4086 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004087 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004089 std::unique_ptr<DeviceResetEntry> newEntry =
4090 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4091 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 } // release lock
4093
4094 if (needWake) {
4095 mLooper->wake();
4096 }
4097}
4098
Prabir Pradhan7e186182020-11-10 13:56:45 -08004099void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004100 if (DEBUG_INBOUND_EVENT_DETAILS) {
4101 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004102 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004103 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004104
Prabir Pradhan99987712020-11-10 18:43:05 -08004105 bool needWake;
4106 { // acquire lock
4107 std::scoped_lock _l(mLock);
4108 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004109 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004110 needWake = enqueueInboundEventLocked(std::move(entry));
4111 } // release lock
4112
4113 if (needWake) {
4114 mLooper->wake();
4115 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004116}
4117
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004118InputEventInjectionResult InputDispatcher::injectInputEvent(
4119 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4120 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004121 if (DEBUG_INBOUND_EVENT_DETAILS) {
4122 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4123 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4124 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4125 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004126 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127
4128 policyFlags |= POLICY_FLAG_INJECTED;
4129 if (hasInjectionPermission(injectorPid, injectorUid)) {
4130 policyFlags |= POLICY_FLAG_TRUSTED;
4131 }
4132
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004133 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004134 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4135 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4136 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4137 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4138 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004139 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004140 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004141 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142 }
4143
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004144 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004146 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004147 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4148 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004153 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004154 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4155 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4156 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004157 int32_t keyCode = incomingKey.getKeyCode();
4158 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004159 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004161 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004162 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004163 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4164 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4165 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4168 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004169 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170
4171 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4172 android::base::Timer t;
4173 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4174 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4175 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4176 std::to_string(t.duration().count()).c_str());
4177 }
4178 }
4179
4180 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 std::unique_ptr<KeyEntry> injectedEntry =
4182 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004184 incomingKey.getDisplayId(), policyFlags, action,
4185 flags, keyCode, incomingKey.getScanCode(), metaState,
4186 incomingKey.getRepeatCount(),
4187 incomingKey.getDownTime());
4188 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004189 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 }
4191
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004193 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4194 int32_t action = motionEvent.getAction();
4195 size_t pointerCount = motionEvent.getPointerCount();
4196 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4197 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004198 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 }
4203
4204 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004205 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 android::base::Timer t;
4207 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4208 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4209 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4210 std::to_string(t.duration().count()).c_str());
4211 }
4212 }
4213
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004214 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4215 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4216 }
4217
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004218 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004219 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4220 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004221 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004222 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4223 resolvedDeviceId, motionEvent.getSource(),
4224 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004225 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004226 motionEvent.getButtonState(),
4227 motionEvent.getClassification(),
4228 motionEvent.getEdgeFlags(),
4229 motionEvent.getXPrecision(),
4230 motionEvent.getYPrecision(),
4231 motionEvent.getRawXCursorPosition(),
4232 motionEvent.getRawYCursorPosition(),
4233 motionEvent.getDownTime(), uint32_t(pointerCount),
4234 pointerProperties, samplePointerCoords,
4235 motionEvent.getXOffset(),
4236 motionEvent.getYOffset());
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004237 transformMotionEntryForInjectionLocked(*injectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 sampleEventTimes += 1;
4241 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004242 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4244 resolvedDeviceId, motionEvent.getSource(),
4245 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004246 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 motionEvent.getMetaState(),
4248 motionEvent.getButtonState(),
4249 motionEvent.getClassification(),
4250 motionEvent.getEdgeFlags(),
4251 motionEvent.getXPrecision(),
4252 motionEvent.getYPrecision(),
4253 motionEvent.getRawXCursorPosition(),
4254 motionEvent.getRawYCursorPosition(),
4255 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004256 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004257 samplePointerCoords, motionEvent.getXOffset(),
4258 motionEvent.getYOffset());
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004259 transformMotionEntryForInjectionLocked(*nextInjectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004260 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 }
4262 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004266 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004267 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 }
4269
4270 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004271 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 injectionState->injectionIsAsync = true;
4273 }
4274
4275 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004276 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277
4278 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004279 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004280 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004281 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 }
4283
4284 mLock.unlock();
4285
4286 if (needWake) {
4287 mLooper->wake();
4288 }
4289
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004290 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004292 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004294 if (syncMode == InputEventInjectionSync::NONE) {
4295 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 } else {
4297 for (;;) {
4298 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004299 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 break;
4301 }
4302
4303 nsecs_t remainingTimeout = endTime - now();
4304 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004305 if (DEBUG_INJECTION) {
4306 ALOGD("injectInputEvent - Timed out waiting for injection result "
4307 "to become available.");
4308 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 break;
4311 }
4312
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004313 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
4315
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004316 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4317 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 if (DEBUG_INJECTION) {
4320 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4321 injectionState->pendingForegroundDispatches);
4322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 nsecs_t remainingTimeout = endTime - now();
4324 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004325 if (DEBUG_INJECTION) {
4326 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4327 "dispatches to finish.");
4328 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 break;
4331 }
4332
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004333 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
4335 }
4336 }
4337
4338 injectionState->release();
4339 } // release lock
4340
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004341 if (DEBUG_INJECTION) {
4342 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4343 injectionResult, injectorPid, injectorUid);
4344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345
4346 return injectionResult;
4347}
4348
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004349std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004350 std::array<uint8_t, 32> calculatedHmac;
4351 std::unique_ptr<VerifiedInputEvent> result;
4352 switch (event.getType()) {
4353 case AINPUT_EVENT_TYPE_KEY: {
4354 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4355 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4356 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004357 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004358 break;
4359 }
4360 case AINPUT_EVENT_TYPE_MOTION: {
4361 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4362 VerifiedMotionEvent verifiedMotionEvent =
4363 verifiedMotionEventFromMotionEvent(motionEvent);
4364 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004365 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004366 break;
4367 }
4368 default: {
4369 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4370 return nullptr;
4371 }
4372 }
4373 if (calculatedHmac == INVALID_HMAC) {
4374 return nullptr;
4375 }
4376 if (calculatedHmac != event.getHmac()) {
4377 return nullptr;
4378 }
4379 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004380}
4381
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 return injectorUid == 0 ||
4384 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385}
4386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004387void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004389 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004391 if (DEBUG_INJECTION) {
4392 ALOGD("Setting input event injection result to %d. "
4393 "injectorPid=%d, injectorUid=%d",
4394 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004397 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 // Log the outcome since the injector did not wait for the injection result.
4399 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 ALOGV("Asynchronous input event injection succeeded.");
4402 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 ALOGW("Asynchronous input event injection failed.");
4405 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 ALOGW("Asynchronous input event injection permission denied.");
4408 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004409 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 ALOGW("Asynchronous input event injection timed out.");
4411 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 case InputEventInjectionResult::PENDING:
4413 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 }
4416 }
4417
4418 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004419 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 }
4421}
4422
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004423void InputDispatcher::transformMotionEntryForInjectionLocked(MotionEntry& entry) const {
4424 const bool isRelativeMouseEvent = isFromSource(entry.source, AINPUT_SOURCE_MOUSE_RELATIVE);
4425 if (!isRelativeMouseEvent && !isFromSource(entry.source, AINPUT_SOURCE_CLASS_POINTER)) {
4426 return;
4427 }
4428
4429 // Input injection works in the logical display coordinate space, but the input pipeline works
4430 // display space, so we need to transform the injected events accordingly.
4431 const auto it = mDisplayInfos.find(entry.displayId);
4432 if (it == mDisplayInfos.end()) return;
4433 const auto& transformToDisplay = it->second.transform.inverse();
4434
4435 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4436 PointerCoords& pc = entry.pointerCoords[i];
4437 const auto xy = isRelativeMouseEvent
4438 ? transformWithoutTranslation(transformToDisplay, pc.getX(), pc.getY())
4439 : transformToDisplay.transform(pc.getXYValue());
4440 pc.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
4441 pc.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
4442
4443 // Axes with relative values never represent points on a screen, so they should never have
4444 // translation applied. If a device does not report relative values, these values are always
4445 // 0, and will remain unaffected by the following operation.
4446 const auto rel =
4447 transformWithoutTranslation(transformToDisplay,
4448 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
4449 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4450 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, rel.x);
4451 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, rel.y);
4452 }
4453}
4454
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004455void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4456 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 if (injectionState) {
4458 injectionState->pendingForegroundDispatches += 1;
4459 }
4460}
4461
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004462void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4463 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 if (injectionState) {
4465 injectionState->pendingForegroundDispatches -= 1;
4466
4467 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004468 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 }
4470 }
4471}
4472
chaviw98318de2021-05-19 16:45:23 -05004473const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004474 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004475 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004476 auto it = mWindowHandlesByDisplay.find(displayId);
4477 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004478}
4479
chaviw98318de2021-05-19 16:45:23 -05004480sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004481 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004482 if (windowHandleToken == nullptr) {
4483 return nullptr;
4484 }
4485
Arthur Hungb92218b2018-08-14 12:00:21 +08004486 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004487 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4488 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004489 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004490 return windowHandle;
4491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 }
4493 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004494 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495}
4496
chaviw98318de2021-05-19 16:45:23 -05004497sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4498 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004499 if (windowHandleToken == nullptr) {
4500 return nullptr;
4501 }
4502
chaviw98318de2021-05-19 16:45:23 -05004503 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004504 if (windowHandle->getToken() == windowHandleToken) {
4505 return windowHandle;
4506 }
4507 }
4508 return nullptr;
4509}
4510
chaviw98318de2021-05-19 16:45:23 -05004511sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4512 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004513 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004514 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4515 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004516 if (handle->getId() == windowHandle->getId() &&
4517 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004518 if (windowHandle->getInfo()->displayId != it.first) {
4519 ALOGE("Found window %s in display %" PRId32
4520 ", but it should belong to display %" PRId32,
4521 windowHandle->getName().c_str(), it.first,
4522 windowHandle->getInfo()->displayId);
4523 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004524 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 }
4527 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004528 return nullptr;
4529}
4530
chaviw98318de2021-05-19 16:45:23 -05004531sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004532 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4533 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534}
4535
chaviw98318de2021-05-19 16:45:23 -05004536bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004537 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4538 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004539 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004540 if (connection != nullptr && noInputChannel) {
4541 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4542 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4543 return false;
4544 }
4545
4546 if (connection == nullptr) {
4547 if (!noInputChannel) {
4548 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4549 }
4550 return false;
4551 }
4552 if (!connection->responsive) {
4553 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4554 return false;
4555 }
4556 return true;
4557}
4558
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004559std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4560 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004561 auto connectionIt = mConnectionsByToken.find(token);
4562 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004563 return nullptr;
4564 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004565 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004566}
4567
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004568void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004569 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4570 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004571 // Remove all handles on a display if there are no windows left.
4572 mWindowHandlesByDisplay.erase(displayId);
4573 return;
4574 }
4575
4576 // Since we compare the pointer of input window handles across window updates, we need
4577 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004578 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4579 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4580 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004581 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004582 }
4583
chaviw98318de2021-05-19 16:45:23 -05004584 std::vector<sp<WindowInfoHandle>> newHandles;
4585 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004586 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004587 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004588 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004589 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4590 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4591 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004592 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004593 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004594 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004595 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004596 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004597 }
4598
4599 if (info->displayId != displayId) {
4600 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4601 handle->getName().c_str(), displayId, info->displayId);
4602 continue;
4603 }
4604
Robert Carredd13602020-04-13 17:24:34 -07004605 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4606 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004607 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004608 oldHandle->updateFrom(handle);
4609 newHandles.push_back(oldHandle);
4610 } else {
4611 newHandles.push_back(handle);
4612 }
4613 }
4614
4615 // Insert or replace
4616 mWindowHandlesByDisplay[displayId] = newHandles;
4617}
4618
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004620 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004621 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004622 { // acquire lock
4623 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004624 for (const auto& [displayId, handles] : handlesPerDisplay) {
4625 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004626 }
4627 }
4628 // Wake up poll loop since it may need to make new input dispatching choices.
4629 mLooper->wake();
4630}
4631
Arthur Hungb92218b2018-08-14 12:00:21 +08004632/**
4633 * Called from InputManagerService, update window handle list by displayId that can receive input.
4634 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4635 * If set an empty list, remove all handles from the specific display.
4636 * For focused handle, check if need to change and send a cancel event to previous one.
4637 * For removed handle, check if need to send a cancel event if already in touch.
4638 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004639void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004640 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004641 if (DEBUG_FOCUS) {
4642 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004643 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004644 windowList += iwh->getName() + " ";
4645 }
4646 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004649 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004650 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004651 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004652 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004653 if (noInputWindow && window->getToken() != nullptr) {
4654 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4655 window->getName().c_str());
4656 window->releaseChannel();
4657 }
4658 }
4659
Arthur Hung72d8dc32020-03-28 00:48:39 +00004660 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004661 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004663 // Save the old windows' orientation by ID before it gets updated.
4664 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004665 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004666 oldWindowOrientations.emplace(handle->getId(),
4667 handle->getInfo()->transform.getOrientation());
4668 }
4669
chaviw98318de2021-05-19 16:45:23 -05004670 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004671
chaviw98318de2021-05-19 16:45:23 -05004672 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004673 if (mLastHoverWindowHandle &&
4674 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4675 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004676 mLastHoverWindowHandle = nullptr;
4677 }
4678
Vishnu Nairc519ff72021-01-21 08:23:08 -08004679 std::optional<FocusResolver::FocusChanges> changes =
4680 mFocusResolver.setInputWindows(displayId, windowHandles);
4681 if (changes) {
4682 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004685 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4686 mTouchStatesByDisplay.find(displayId);
4687 if (stateIt != mTouchStatesByDisplay.end()) {
4688 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004689 for (size_t i = 0; i < state.windows.size();) {
4690 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004691 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004692 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004693 ALOGD("Touched window was removed: %s in display %" PRId32,
4694 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004695 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004696 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4698 if (touchedInputChannel != nullptr) {
4699 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4700 "touched window was removed");
4701 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004702 // Since we are about to drop the touch, cancel the events for the wallpaper as
4703 // well.
4704 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4705 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4706 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4707 if (wallpaper != nullptr) {
4708 sp<Connection> wallpaperConnection =
4709 getConnectionLocked(wallpaper->getToken());
4710 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4711 options);
4712 }
4713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004715 state.windows.erase(state.windows.begin() + i);
4716 } else {
4717 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 }
4719 }
arthurhungb89ccb02020-12-30 16:19:01 +08004720
arthurhung6d4bed92021-03-17 11:59:33 +08004721 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004722 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004723 if (mDragState &&
4724 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004725 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004726 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004727 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004729
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004730 if (isPerWindowInputRotationEnabled()) {
4731 // Determine if the orientation of any of the input windows have changed, and cancel all
4732 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004733 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4734 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004735 if (newWindowHandle != nullptr &&
4736 newWindowHandle->getInfo()->transform.getOrientation() !=
4737 oldWindowOrientations[oldWindowHandle->getId()]) {
4738 std::shared_ptr<InputChannel> inputChannel =
4739 getInputChannelLocked(newWindowHandle->getToken());
4740 if (inputChannel != nullptr) {
4741 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4742 "touched window's orientation changed");
4743 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4744 }
4745 }
4746 }
4747 }
4748
Arthur Hung72d8dc32020-03-28 00:48:39 +00004749 // Release information for windows that are no longer present.
4750 // This ensures that unused input channels are released promptly.
4751 // Otherwise, they might stick around until the window handle is destroyed
4752 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004753 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004754 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004755 if (DEBUG_FOCUS) {
4756 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004757 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004758 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004759 // To avoid making too many calls into the compat framework, only
4760 // check for window flags when windows are going away.
4761 // TODO(b/157929241) : delete this. This is only needed temporarily
4762 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004763 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004764 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4765 oldWindowHandle->getName().c_str());
4766 if (mCompatService != nullptr) {
4767 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4768 oldWindowHandle->getInfo()->ownerUid);
4769 }
4770 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004771 }
chaviw291d88a2019-02-14 10:33:58 -08004772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773}
4774
4775void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004776 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004777 if (DEBUG_FOCUS) {
4778 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4779 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4780 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004781 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004782 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004783 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 } // release lock
4785
4786 // Wake up poll loop since it may need to make new input dispatching choices.
4787 mLooper->wake();
4788}
4789
Vishnu Nair599f1412021-06-21 10:39:58 -07004790void InputDispatcher::setFocusedApplicationLocked(
4791 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4792 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4793 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4794
4795 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4796 return; // This application is already focused. No need to wake up or change anything.
4797 }
4798
4799 // Set the new application handle.
4800 if (inputApplicationHandle != nullptr) {
4801 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4802 } else {
4803 mFocusedApplicationHandlesByDisplay.erase(displayId);
4804 }
4805
4806 // No matter what the old focused application was, stop waiting on it because it is
4807 // no longer focused.
4808 resetNoFocusedWindowTimeoutLocked();
4809}
4810
Tiger Huang721e26f2018-07-24 22:26:19 +08004811/**
4812 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4813 * the display not specified.
4814 *
4815 * We track any unreleased events for each window. If a window loses the ability to receive the
4816 * released event, we will send a cancel event to it. So when the focused display is changed, we
4817 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4818 * display. The display-specified events won't be affected.
4819 */
4820void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004821 if (DEBUG_FOCUS) {
4822 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4823 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004824 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004825 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004826
4827 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004828 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004829 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004830 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004831 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004832 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004833 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004834 CancelationOptions
4835 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4836 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004837 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004838 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4839 }
4840 }
4841 mFocusedDisplayId = displayId;
4842
Chris Ye3c2d6f52020-08-09 10:39:48 -07004843 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004844 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004845 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004846
Vishnu Nairad321cd2020-08-20 16:40:21 -07004847 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004848 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004849 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004850 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004851 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004852 }
4853 }
4854 }
4855
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004856 if (DEBUG_FOCUS) {
4857 logDispatchStateLocked();
4858 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004859 } // release lock
4860
4861 // Wake up poll loop since it may need to make new input dispatching choices.
4862 mLooper->wake();
4863}
4864
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004866 if (DEBUG_FOCUS) {
4867 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869
4870 bool changed;
4871 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873
4874 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4875 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
4878
4879 if (mDispatchEnabled && !enabled) {
4880 resetAndDropEverythingLocked("dispatcher is being disabled");
4881 }
4882
4883 mDispatchEnabled = enabled;
4884 mDispatchFrozen = frozen;
4885 changed = true;
4886 } else {
4887 changed = false;
4888 }
4889
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004890 if (DEBUG_FOCUS) {
4891 logDispatchStateLocked();
4892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 } // release lock
4894
4895 if (changed) {
4896 // Wake up poll loop since it may need to make new input dispatching choices.
4897 mLooper->wake();
4898 }
4899}
4900
4901void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004902 if (DEBUG_FOCUS) {
4903 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
4906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
4909 if (mInputFilterEnabled == enabled) {
4910 return;
4911 }
4912
4913 mInputFilterEnabled = enabled;
4914 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4915 } // release lock
4916
4917 // Wake up poll loop since there might be work to do to drop everything.
4918 mLooper->wake();
4919}
4920
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004921void InputDispatcher::setInTouchMode(bool inTouchMode) {
4922 std::scoped_lock lock(mLock);
4923 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004924 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004925}
4926
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004927void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4928 if (opacity < 0 || opacity > 1) {
4929 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4930 return;
4931 }
4932
4933 std::scoped_lock lock(mLock);
4934 mMaximumObscuringOpacityForTouch = opacity;
4935}
4936
4937void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4938 std::scoped_lock lock(mLock);
4939 mBlockUntrustedTouchesMode = mode;
4940}
4941
Arthur Hungabbb9d82021-09-01 14:52:30 +00004942std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4943 const sp<IBinder>& token) {
4944 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4945 for (TouchedWindow& w : state.windows) {
4946 if (w.windowHandle->getToken() == token) {
4947 return std::make_pair(&state, &w);
4948 }
4949 }
4950 }
4951 return std::make_pair(nullptr, nullptr);
4952}
4953
arthurhungb89ccb02020-12-30 16:19:01 +08004954bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4955 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004956 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004957 if (DEBUG_FOCUS) {
4958 ALOGD("Trivial transfer to same window.");
4959 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004960 return true;
4961 }
4962
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004964 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
Arthur Hungabbb9d82021-09-01 14:52:30 +00004966 // Find the target touch state and touched window by fromToken.
4967 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4968 if (state == nullptr || touchedWindow == nullptr) {
4969 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 return false;
4971 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004972
4973 const int32_t displayId = state->displayId;
4974 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4975 if (toWindowHandle == nullptr) {
4976 ALOGW("Cannot transfer focus because to window not found.");
4977 return false;
4978 }
4979
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004980 if (DEBUG_FOCUS) {
4981 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004982 touchedWindow->windowHandle->getName().c_str(),
4983 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984 }
4985
Arthur Hungabbb9d82021-09-01 14:52:30 +00004986 // Erase old window.
4987 int32_t oldTargetFlags = touchedWindow->targetFlags;
4988 BitSet32 pointerIds = touchedWindow->pointerIds;
4989 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
Arthur Hungabbb9d82021-09-01 14:52:30 +00004991 // Add new window.
4992 int32_t newTargetFlags = oldTargetFlags &
4993 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4994 InputTarget::FLAG_DISPATCH_AS_IS);
4995 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996
Arthur Hungabbb9d82021-09-01 14:52:30 +00004997 // Store the dragging window.
4998 if (isDragDrop) {
4999 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 }
5001
Arthur Hungabbb9d82021-09-01 14:52:30 +00005002 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005003 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5004 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005005 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005006 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 CancelationOptions
5008 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5009 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005011 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012 }
5013
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005014 if (DEBUG_FOCUS) {
5015 logDispatchStateLocked();
5016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 } // release lock
5018
5019 // Wake up poll loop since it may need to make new input dispatching choices.
5020 mLooper->wake();
5021 return true;
5022}
5023
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005024// Binder call
5025bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5026 sp<IBinder> fromToken;
5027 { // acquire lock
5028 std::scoped_lock _l(mLock);
5029
Arthur Hungabbb9d82021-09-01 14:52:30 +00005030 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5031 [](const auto& pair) { return pair.second.windows.size() == 1; });
5032 if (it == mTouchStatesByDisplay.end()) {
5033 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5034 return false;
5035 }
5036 const int32_t displayId = it->first;
5037 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005038 if (toWindowHandle == nullptr) {
5039 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5040 return false;
5041 }
5042
Arthur Hungabbb9d82021-09-01 14:52:30 +00005043 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005044 const TouchedWindow& touchedWindow = state.windows[0];
5045 fromToken = touchedWindow.windowHandle->getToken();
5046 } // release lock
5047
5048 return transferTouchFocus(fromToken, destChannelToken);
5049}
5050
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005052 if (DEBUG_FOCUS) {
5053 ALOGD("Resetting and dropping all events (%s).", reason);
5054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055
5056 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5057 synthesizeCancelationEventsForAllConnectionsLocked(options);
5058
5059 resetKeyRepeatLocked();
5060 releasePendingEventLocked();
5061 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005062 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005064 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005065 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005067 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068}
5069
5070void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005071 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072 dumpDispatchStateLocked(dump);
5073
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005074 std::istringstream stream(dump);
5075 std::string line;
5076
5077 while (std::getline(stream, line, '\n')) {
5078 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 }
5080}
5081
Prabir Pradhan99987712020-11-10 18:43:05 -08005082std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5083 std::string dump;
5084
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005085 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5086 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005087
5088 std::string windowName = "None";
5089 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005090 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005091 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5092 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5093 : "token has capture without window";
5094 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005095 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005096
5097 return dump;
5098}
5099
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005100void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005101 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5102 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5103 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005104 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105
Tiger Huang721e26f2018-07-24 22:26:19 +08005106 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5107 dump += StringPrintf(INDENT "FocusedApplications:\n");
5108 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5109 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005110 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005111 const std::chrono::duration timeout =
5112 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005113 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005114 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005115 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005118 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005120
Vishnu Nairc519ff72021-01-21 08:23:08 -08005121 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005122 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005124 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005125 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005126 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5127 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005128 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005129 state.displayId, toString(state.down), toString(state.split),
5130 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005131 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005132 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005133 for (size_t i = 0; i < state.windows.size(); i++) {
5134 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005135 dump += StringPrintf(INDENT4
5136 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5137 i, touchedWindow.windowHandle->getName().c_str(),
5138 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005139 }
5140 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005141 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005145 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147
arthurhung6d4bed92021-03-17 11:59:33 +08005148 if (mDragState) {
5149 dump += StringPrintf(INDENT "DragState:\n");
5150 mDragState->dump(dump, INDENT2);
5151 }
5152
Arthur Hungb92218b2018-08-14 12:00:21 +08005153 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005154 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5155 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5156 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5157 const auto& displayInfo = it->second;
5158 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5159 displayInfo.logicalHeight);
5160 displayInfo.transform.dump(dump, "transform", INDENT4);
5161 } else {
5162 dump += INDENT2 "No DisplayInfo found!\n";
5163 }
5164
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005165 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005166 dump += INDENT2 "Windows:\n";
5167 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005168 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5169 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005171 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005172 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005173 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005174 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005175 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005176 "applicationInfo.name=%s, "
5177 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005178 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005179 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005180 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005181 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005182 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005183 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005184 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005185 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005186 windowInfo->frameLeft, windowInfo->frameTop,
5187 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005188 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005189 windowInfo->applicationInfo.name.c_str(),
5190 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005191 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005192 dump += StringPrintf(", inputFeatures=%s",
5193 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005194 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005195 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005196 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005197 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005198 millis(windowInfo->dispatchingTimeout),
5199 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005200 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005201 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005202 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005203 }
5204 } else {
5205 dump += INDENT2 "Windows: <none>\n";
5206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207 }
5208 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005209 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210 }
5211
Michael Wright3dd60e22019-03-27 22:06:44 +00005212 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005213 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005214 const std::vector<Monitor>& monitors = it.second;
5215 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5216 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005217 }
5218 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005219 const std::vector<Monitor>& monitors = it.second;
5220 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5221 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005224 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 }
5226
5227 nsecs_t currentTime = now();
5228
5229 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005230 if (!mRecentQueue.empty()) {
5231 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005232 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005233 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005234 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005235 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 }
5237 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005238 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 }
5240
5241 // Dump event currently being dispatched.
5242 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005243 dump += INDENT "PendingEvent:\n";
5244 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005245 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005246 dump += StringPrintf(", age=%" PRId64 "ms\n",
5247 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005249 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 }
5251
5252 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005253 if (!mInboundQueue.empty()) {
5254 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005255 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005256 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005257 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005258 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 }
5260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005261 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
5263
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005264 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005265 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005266 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5267 const KeyReplacement& replacement = pair.first;
5268 int32_t newKeyCode = pair.second;
5269 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005270 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005271 }
5272 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005273 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005274 }
5275
Prabir Pradhancef936d2021-07-21 16:17:52 +00005276 if (!mCommandQueue.empty()) {
5277 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5278 } else {
5279 dump += INDENT "CommandQueue: <empty>\n";
5280 }
5281
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005282 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005283 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005284 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005285 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005286 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005287 connection->inputChannel->getFd().get(),
5288 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005289 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005290 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005292 if (!connection->outboundQueue.empty()) {
5293 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5294 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005295 dump += dumpQueue(connection->outboundQueue, currentTime);
5296
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005298 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 }
5300
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005301 if (!connection->waitQueue.empty()) {
5302 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5303 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005304 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 }
5308 }
5309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005310 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
5312
5313 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005314 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5315 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005317 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 }
5319
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005320 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005321 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5322 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5323 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005324 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005325 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326}
5327
Michael Wright3dd60e22019-03-27 22:06:44 +00005328void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5329 const size_t numMonitors = monitors.size();
5330 for (size_t i = 0; i < numMonitors; i++) {
5331 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005332 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005333 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5334 dump += "\n";
5335 }
5336}
5337
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005338class LooperEventCallback : public LooperCallback {
5339public:
5340 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5341 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5342
5343private:
5344 std::function<int(int events)> mCallback;
5345};
5346
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005347Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005348 if (DEBUG_CHANNEL_CREATION) {
5349 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005352 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005353 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005354 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005355
5356 if (result) {
5357 return base::Error(result) << "Failed to open input channel pair with name " << name;
5358 }
5359
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005361 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005362 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005363 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005364 sp<Connection> connection =
5365 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005367 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5368 ALOGE("Created a new connection, but the token %p is already known", token.get());
5369 }
5370 mConnectionsByToken.emplace(token, connection);
5371
5372 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5373 this, std::placeholders::_1, token);
5374
5375 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 } // release lock
5377
5378 // Wake the looper because some connections have changed.
5379 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005380 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381}
5382
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005383Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5384 bool isGestureMonitor,
5385 const std::string& name,
5386 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005387 std::shared_ptr<InputChannel> serverChannel;
5388 std::unique_ptr<InputChannel> clientChannel;
5389 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5390 if (result) {
5391 return base::Error(result) << "Failed to open input channel pair with name " << name;
5392 }
5393
Michael Wright3dd60e22019-03-27 22:06:44 +00005394 { // acquire lock
5395 std::scoped_lock _l(mLock);
5396
5397 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005398 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5399 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005400 }
5401
Garfield Tan15601662020-09-22 15:32:38 -07005402 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005403 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005404 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005405
5406 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5407 ALOGE("Created a new connection, but the token %p is already known", token.get());
5408 }
5409 mConnectionsByToken.emplace(token, connection);
5410 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5411 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005412
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005413 auto& monitorsByDisplay =
5414 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005415 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005416
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005417 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005418 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5419 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005420 }
Garfield Tan15601662020-09-22 15:32:38 -07005421
Michael Wright3dd60e22019-03-27 22:06:44 +00005422 // Wake the looper because some connections have changed.
5423 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005424 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005425}
5426
Garfield Tan15601662020-09-22 15:32:38 -07005427status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005429 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430
Garfield Tan15601662020-09-22 15:32:38 -07005431 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 if (status) {
5433 return status;
5434 }
5435 } // release lock
5436
5437 // Wake the poll loop because removing the connection may have changed the current
5438 // synchronization state.
5439 mLooper->wake();
5440 return OK;
5441}
5442
Garfield Tan15601662020-09-22 15:32:38 -07005443status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5444 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005445 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005446 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005447 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 return BAD_VALUE;
5449 }
5450
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005451 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005452
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005454 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 }
5456
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005457 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
5459 nsecs_t currentTime = now();
5460 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5461
5462 connection->status = Connection::STATUS_ZOMBIE;
5463 return OK;
5464}
5465
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005466void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5467 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5468 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005469}
5470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005471void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005472 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005473 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005474 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005475 std::vector<Monitor>& monitors = it->second;
5476 const size_t numMonitors = monitors.size();
5477 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005478 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005479 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5480 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005481 monitors.erase(monitors.begin() + i);
5482 break;
5483 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005484 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005485 if (monitors.empty()) {
5486 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005487 } else {
5488 ++it;
5489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 }
5491}
5492
Michael Wright3dd60e22019-03-27 22:06:44 +00005493status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5494 { // acquire lock
5495 std::scoped_lock _l(mLock);
5496 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5497
5498 if (!foundDisplayId) {
5499 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5500 return BAD_VALUE;
5501 }
5502 int32_t displayId = foundDisplayId.value();
5503
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005504 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5505 mTouchStatesByDisplay.find(displayId);
5506 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005507 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5508 return BAD_VALUE;
5509 }
5510
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005511 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005512 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005513 std::optional<int32_t> foundDeviceId;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07005514 for (const auto& monitor : state.gestureMonitors) {
5515 if (monitor.inputChannel->getConnectionToken() == token) {
5516 requestingChannel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005517 foundDeviceId = state.deviceId;
5518 }
5519 }
5520 if (!foundDeviceId || !state.down) {
5521 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005522 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005523 return BAD_VALUE;
5524 }
5525 int32_t deviceId = foundDeviceId.value();
5526
5527 // Send cancel events to all the input channels we're stealing from.
5528 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005529 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005530 options.deviceId = deviceId;
5531 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005532 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005533 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005534 std::shared_ptr<InputChannel> channel =
5535 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005536 if (channel != nullptr) {
5537 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005538 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005539 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005540 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005541 canceledWindows += "]";
5542 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5543 canceledWindows.c_str());
5544
Michael Wright3dd60e22019-03-27 22:06:44 +00005545 // Then clear the current touch state so we stop dispatching to them as well.
5546 state.filterNonMonitors();
5547 }
5548 return OK;
5549}
5550
Prabir Pradhan99987712020-11-10 18:43:05 -08005551void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5552 { // acquire lock
5553 std::scoped_lock _l(mLock);
5554 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005555 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005556 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5557 windowHandle != nullptr ? windowHandle->getName().c_str()
5558 : "token without window");
5559 }
5560
Vishnu Nairc519ff72021-01-21 08:23:08 -08005561 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005562 if (focusedToken != windowToken) {
5563 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5564 enabled ? "enable" : "disable");
5565 return;
5566 }
5567
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005568 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005569 ALOGW("Ignoring request to %s Pointer Capture: "
5570 "window has %s requested pointer capture.",
5571 enabled ? "enable" : "disable", enabled ? "already" : "not");
5572 return;
5573 }
5574
Prabir Pradhan99987712020-11-10 18:43:05 -08005575 setPointerCaptureLocked(enabled);
5576 } // release lock
5577
5578 // Wake the thread to process command entries.
5579 mLooper->wake();
5580}
5581
Michael Wright3dd60e22019-03-27 22:06:44 +00005582std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5583 const sp<IBinder>& token) {
5584 for (const auto& it : mGestureMonitorsByDisplay) {
5585 const std::vector<Monitor>& monitors = it.second;
5586 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005587 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005588 return it.first;
5589 }
5590 }
5591 }
5592 return std::nullopt;
5593}
5594
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005595std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5596 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5597 if (gesturePid.has_value()) {
5598 return gesturePid;
5599 }
5600 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5601}
5602
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005603sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005604 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005605 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005606 }
5607
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005608 for (const auto& [token, connection] : mConnectionsByToken) {
5609 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005610 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 }
5612 }
Robert Carr4e670e52018-08-15 13:26:12 -07005613
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005614 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615}
5616
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005617std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5618 sp<Connection> connection = getConnectionLocked(connectionToken);
5619 if (connection == nullptr) {
5620 return "<nullptr>";
5621 }
5622 return connection->getInputChannelName();
5623}
5624
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005625void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005626 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005627 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005628}
5629
Prabir Pradhancef936d2021-07-21 16:17:52 +00005630void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5631 const sp<Connection>& connection, uint32_t seq,
5632 bool handled, nsecs_t consumeTime) {
5633 // Handle post-event policy actions.
5634 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5635 if (dispatchEntryIt == connection->waitQueue.end()) {
5636 return;
5637 }
5638 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5639 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5640 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5641 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5642 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5643 }
5644 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5645 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5646 connection->inputChannel->getConnectionToken(),
5647 dispatchEntry->deliveryTime, consumeTime, finishTime);
5648 }
5649
5650 bool restartEvent;
5651 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5652 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5653 restartEvent =
5654 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5655 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5656 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5657 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5658 handled);
5659 } else {
5660 restartEvent = false;
5661 }
5662
5663 // Dequeue the event and start the next cycle.
5664 // Because the lock might have been released, it is possible that the
5665 // contents of the wait queue to have been drained, so we need to double-check
5666 // a few things.
5667 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5668 if (dispatchEntryIt != connection->waitQueue.end()) {
5669 dispatchEntry = *dispatchEntryIt;
5670 connection->waitQueue.erase(dispatchEntryIt);
5671 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5672 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5673 if (!connection->responsive) {
5674 connection->responsive = isConnectionResponsive(*connection);
5675 if (connection->responsive) {
5676 // The connection was unresponsive, and now it's responsive.
5677 processConnectionResponsiveLocked(*connection);
5678 }
5679 }
5680 traceWaitQueueLength(*connection);
5681 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5682 connection->outboundQueue.push_front(dispatchEntry);
5683 traceOutboundQueueLength(*connection);
5684 } else {
5685 releaseDispatchEntry(dispatchEntry);
5686 }
5687 }
5688
5689 // Start the next dispatch cycle for this connection.
5690 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691}
5692
Prabir Pradhancef936d2021-07-21 16:17:52 +00005693void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5694 const sp<IBinder>& newToken) {
5695 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5696 scoped_unlock unlock(mLock);
5697 mPolicy->notifyFocusChanged(oldToken, newToken);
5698 };
5699 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700}
5701
Prabir Pradhancef936d2021-07-21 16:17:52 +00005702void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5703 auto command = [this, token, x, y]() REQUIRES(mLock) {
5704 scoped_unlock unlock(mLock);
5705 mPolicy->notifyDropWindow(token, x, y);
5706 };
5707 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005708}
5709
Prabir Pradhancef936d2021-07-21 16:17:52 +00005710void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5711 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5712 scoped_unlock unlock(mLock);
5713 mPolicy->notifyUntrustedTouch(obscuringPackage);
5714 };
5715 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005716}
5717
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005718void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5719 if (connection == nullptr) {
5720 LOG_ALWAYS_FATAL("Caller must check for nullness");
5721 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5723 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005724 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005726 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005727 return;
5728 }
5729 /**
5730 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5731 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5732 * has changed. This could cause newer entries to time out before the already dispatched
5733 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5734 * processes the events linearly. So providing information about the oldest entry seems to be
5735 * most useful.
5736 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005737 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005738 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5739 std::string reason =
5740 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005741 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005742 ns2ms(currentWait),
5743 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005744 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005745 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005746
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005747 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5748
5749 // Stop waking up for events on this connection, it is already unresponsive
5750 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005751}
5752
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005753void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5754 std::string reason =
5755 StringPrintf("%s does not have a focused window", application->getName().c_str());
5756 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005757
Prabir Pradhancef936d2021-07-21 16:17:52 +00005758 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5759 scoped_unlock unlock(mLock);
5760 mPolicy->notifyNoFocusedWindowAnr(application);
5761 };
5762 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005763}
5764
chaviw98318de2021-05-19 16:45:23 -05005765void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005766 const std::string& reason) {
5767 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5768 updateLastAnrStateLocked(windowLabel, reason);
5769}
5770
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005771void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5772 const std::string& reason) {
5773 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005774 updateLastAnrStateLocked(windowLabel, reason);
5775}
5776
5777void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5778 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005780 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 struct tm tm;
5782 localtime_r(&t, &tm);
5783 char timestr[64];
5784 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005785 mLastAnrState.clear();
5786 mLastAnrState += INDENT "ANR:\n";
5787 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005788 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5789 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005790 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791}
5792
Prabir Pradhancef936d2021-07-21 16:17:52 +00005793void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5794 KeyEntry& entry) {
5795 const KeyEvent event = createKeyEvent(entry);
5796 nsecs_t delay = 0;
5797 { // release lock
5798 scoped_unlock unlock(mLock);
5799 android::base::Timer t;
5800 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5801 entry.policyFlags);
5802 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5803 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5804 std::to_string(t.duration().count()).c_str());
5805 }
5806 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807
5808 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005809 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005810 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005811 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005813 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5814 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816}
5817
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005818void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005819 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5820 scoped_unlock unlock(mLock);
5821 mPolicy->notifyMonitorUnresponsive(pid, reason);
5822 };
5823 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005824}
5825
Prabir Pradhancef936d2021-07-21 16:17:52 +00005826void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005827 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005828 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5829 scoped_unlock unlock(mLock);
5830 mPolicy->notifyWindowUnresponsive(token, reason);
5831 };
5832 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005833}
5834
5835void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005836 auto command = [this, pid]() REQUIRES(mLock) {
5837 scoped_unlock unlock(mLock);
5838 mPolicy->notifyMonitorResponsive(pid);
5839 };
5840 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005841}
5842
Prabir Pradhancef936d2021-07-21 16:17:52 +00005843void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5844 auto command = [this, connectionToken]() REQUIRES(mLock) {
5845 scoped_unlock unlock(mLock);
5846 mPolicy->notifyWindowResponsive(connectionToken);
5847 };
5848 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005849}
5850
5851/**
5852 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5853 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5854 * command entry to the command queue.
5855 */
5856void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5857 std::string reason) {
5858 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5859 if (connection.monitor) {
5860 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5861 reason.c_str());
5862 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5863 if (!pid.has_value()) {
5864 ALOGE("Could not find unresponsive monitor for connection %s",
5865 connection.inputChannel->getName().c_str());
5866 return;
5867 }
5868 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5869 return;
5870 }
5871 // If not a monitor, must be a window
5872 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5873 reason.c_str());
5874 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5875}
5876
5877/**
5878 * Tell the policy that a connection has become responsive so that it can stop ANR.
5879 */
5880void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5881 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5882 if (connection.monitor) {
5883 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5884 if (!pid.has_value()) {
5885 ALOGE("Could not find responsive monitor for connection %s",
5886 connection.inputChannel->getName().c_str());
5887 return;
5888 }
5889 sendMonitorResponsiveCommandLocked(pid.value());
5890 return;
5891 }
5892 // If not a monitor, must be a window
5893 sendWindowResponsiveCommandLocked(connectionToken);
5894}
5895
Prabir Pradhancef936d2021-07-21 16:17:52 +00005896bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005897 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005898 KeyEntry& keyEntry, bool handled) {
5899 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005900 if (!handled) {
5901 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005902 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005903 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005904 return false;
5905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907 // Get the fallback key state.
5908 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005909 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005910 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 connection->inputState.removeFallbackKey(originalKeyCode);
5913 }
5914
5915 if (handled || !dispatchEntry->hasForegroundTarget()) {
5916 // If the application handles the original key for which we previously
5917 // generated a fallback or if the window is not a foreground window,
5918 // then cancel the associated fallback key, if any.
5919 if (fallbackKeyCode != -1) {
5920 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005921 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5922 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5923 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5924 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5925 keyEntry.policyFlags);
5926 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005927 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005928 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929
5930 mLock.unlock();
5931
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005932 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005933 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934
5935 mLock.lock();
5936
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005937 // Cancel the fallback key.
5938 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 "application handled the original non-fallback key "
5941 "or is no longer a foreground target, "
5942 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 options.keyCode = fallbackKeyCode;
5944 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005946 connection->inputState.removeFallbackKey(originalKeyCode);
5947 }
5948 } else {
5949 // If the application did not handle a non-fallback key, first check
5950 // that we are in a good state to perform unhandled key event processing
5951 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005952 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005953 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005954 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5955 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5956 "since this is not an initial down. "
5957 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5958 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5959 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005960 return false;
5961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005963 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005964 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5965 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5966 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5967 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5968 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005969 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005970
5971 mLock.unlock();
5972
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005973 bool fallback =
5974 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976
5977 mLock.lock();
5978
5979 if (connection->status != Connection::STATUS_NORMAL) {
5980 connection->inputState.removeFallbackKey(originalKeyCode);
5981 return false;
5982 }
5983
5984 // Latch the fallback keycode for this key on an initial down.
5985 // The fallback keycode cannot change at any other point in the lifecycle.
5986 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988 fallbackKeyCode = event.getKeyCode();
5989 } else {
5990 fallbackKeyCode = AKEYCODE_UNKNOWN;
5991 }
5992 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5993 }
5994
5995 ALOG_ASSERT(fallbackKeyCode != -1);
5996
5997 // Cancel the fallback key if the policy decides not to send it anymore.
5998 // We will continue to dispatch the key to the policy but we will no
5999 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006000 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6001 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006002 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6003 if (fallback) {
6004 ALOGD("Unhandled key event: Policy requested to send key %d"
6005 "as a fallback for %d, but on the DOWN it had requested "
6006 "to send %d instead. Fallback canceled.",
6007 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6008 } else {
6009 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6010 "but on the DOWN it had requested to send %d. "
6011 "Fallback canceled.",
6012 originalKeyCode, fallbackKeyCode);
6013 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006014 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006015
6016 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6017 "canceling fallback, policy no longer desires it");
6018 options.keyCode = fallbackKeyCode;
6019 synthesizeCancelationEventsForConnectionLocked(connection, options);
6020
6021 fallback = false;
6022 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006023 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006024 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006025 }
6026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006028 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6029 {
6030 std::string msg;
6031 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6032 connection->inputState.getFallbackKeys();
6033 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6034 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6035 }
6036 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6037 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040
6041 if (fallback) {
6042 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006043 keyEntry.eventTime = event.getEventTime();
6044 keyEntry.deviceId = event.getDeviceId();
6045 keyEntry.source = event.getSource();
6046 keyEntry.displayId = event.getDisplayId();
6047 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6048 keyEntry.keyCode = fallbackKeyCode;
6049 keyEntry.scanCode = event.getScanCode();
6050 keyEntry.metaState = event.getMetaState();
6051 keyEntry.repeatCount = event.getRepeatCount();
6052 keyEntry.downTime = event.getDownTime();
6053 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006055 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6056 ALOGD("Unhandled key event: Dispatching fallback key. "
6057 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6058 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6059 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006060 return true; // restart the event
6061 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006062 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6063 ALOGD("Unhandled key event: No fallback key.");
6064 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006065
6066 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006067 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 }
6069 }
6070 return false;
6071}
6072
Prabir Pradhancef936d2021-07-21 16:17:52 +00006073bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006074 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006075 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 return false;
6077}
6078
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079void InputDispatcher::traceInboundQueueLengthLocked() {
6080 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006081 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082 }
6083}
6084
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006085void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 if (ATRACE_ENABLED()) {
6087 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006088 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6089 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 }
6091}
6092
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006093void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094 if (ATRACE_ENABLED()) {
6095 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006096 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6097 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 }
6099}
6100
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006101void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006102 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006104 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 dumpDispatchStateLocked(dump);
6106
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006107 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006108 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006109 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 }
6111}
6112
6113void InputDispatcher::monitor() {
6114 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006115 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006117 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118}
6119
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006120/**
6121 * Wake up the dispatcher and wait until it processes all events and commands.
6122 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6123 * this method can be safely called from any thread, as long as you've ensured that
6124 * the work you are interested in completing has already been queued.
6125 */
6126bool InputDispatcher::waitForIdle() {
6127 /**
6128 * Timeout should represent the longest possible time that a device might spend processing
6129 * events and commands.
6130 */
6131 constexpr std::chrono::duration TIMEOUT = 100ms;
6132 std::unique_lock lock(mLock);
6133 mLooper->wake();
6134 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6135 return result == std::cv_status::no_timeout;
6136}
6137
Vishnu Naire798b472020-07-23 13:52:21 -07006138/**
6139 * Sets focus to the window identified by the token. This must be called
6140 * after updating any input window handles.
6141 *
6142 * Params:
6143 * request.token - input channel token used to identify the window that should gain focus.
6144 * request.focusedToken - the token that the caller expects currently to be focused. If the
6145 * specified token does not match the currently focused window, this request will be dropped.
6146 * If the specified focused token matches the currently focused window, the call will succeed.
6147 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6148 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6149 * when requesting the focus change. This determines which request gets
6150 * precedence if there is a focus change request from another source such as pointer down.
6151 */
Vishnu Nair958da932020-08-21 17:12:37 -07006152void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6153 { // acquire lock
6154 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006155 std::optional<FocusResolver::FocusChanges> changes =
6156 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6157 if (changes) {
6158 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006159 }
6160 } // release lock
6161 // Wake up poll loop since it may need to make new input dispatching choices.
6162 mLooper->wake();
6163}
6164
Vishnu Nairc519ff72021-01-21 08:23:08 -08006165void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6166 if (changes.oldFocus) {
6167 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006168 if (focusedInputChannel) {
6169 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6170 "focus left window");
6171 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006172 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006173 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006174 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006175 if (changes.newFocus) {
6176 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006177 }
6178
Prabir Pradhan99987712020-11-10 18:43:05 -08006179 // If a window has pointer capture, then it must have focus. We need to ensure that this
6180 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6181 // If the window loses focus before it loses pointer capture, then the window can be in a state
6182 // where it has pointer capture but not focus, violating the contract. Therefore we must
6183 // dispatch the pointer capture event before the focus event. Since focus events are added to
6184 // the front of the queue (above), we add the pointer capture event to the front of the queue
6185 // after the focus events are added. This ensures the pointer capture event ends up at the
6186 // front.
6187 disablePointerCaptureForcedLocked();
6188
Vishnu Nairc519ff72021-01-21 08:23:08 -08006189 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006190 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006191 }
6192}
Vishnu Nair958da932020-08-21 17:12:37 -07006193
Prabir Pradhan99987712020-11-10 18:43:05 -08006194void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006195 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006196 return;
6197 }
6198
6199 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6200
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006201 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006202 setPointerCaptureLocked(false);
6203 }
6204
6205 if (!mWindowTokenWithPointerCapture) {
6206 // No need to send capture changes because no window has capture.
6207 return;
6208 }
6209
6210 if (mPendingEvent != nullptr) {
6211 // Move the pending event to the front of the queue. This will give the chance
6212 // for the pending event to be dropped if it is a captured event.
6213 mInboundQueue.push_front(mPendingEvent);
6214 mPendingEvent = nullptr;
6215 }
6216
6217 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006218 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006219 mInboundQueue.push_front(std::move(entry));
6220}
6221
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006222void InputDispatcher::setPointerCaptureLocked(bool enable) {
6223 mCurrentPointerCaptureRequest.enable = enable;
6224 mCurrentPointerCaptureRequest.seq++;
6225 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006226 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006227 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006228 };
6229 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006230}
6231
Vishnu Nair599f1412021-06-21 10:39:58 -07006232void InputDispatcher::displayRemoved(int32_t displayId) {
6233 { // acquire lock
6234 std::scoped_lock _l(mLock);
6235 // Set an empty list to remove all handles from the specific display.
6236 setInputWindowsLocked(/* window handles */ {}, displayId);
6237 setFocusedApplicationLocked(displayId, nullptr);
6238 // Call focus resolver to clean up stale requests. This must be called after input windows
6239 // have been removed for the removed display.
6240 mFocusResolver.displayRemoved(displayId);
6241 } // release lock
6242
6243 // Wake up poll loop since it may need to make new input dispatching choices.
6244 mLooper->wake();
6245}
6246
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006247void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6248 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006249 // The listener sends the windows as a flattened array. Separate the windows by display for
6250 // more convenient parsing.
6251 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006252 for (const auto& info : windowInfos) {
6253 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6254 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6255 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006256
6257 { // acquire lock
6258 std::scoped_lock _l(mLock);
6259 mDisplayInfos.clear();
6260 for (const auto& displayInfo : displayInfos) {
6261 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6262 }
6263
6264 for (const auto& [displayId, handles] : handlesPerDisplay) {
6265 setInputWindowsLocked(handles, displayId);
6266 }
6267 }
6268 // Wake up poll loop since it may need to make new input dispatching choices.
6269 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006270}
6271
Vishnu Nair062a8672021-09-03 16:07:44 -07006272bool InputDispatcher::shouldDropInput(
6273 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6274 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6275 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6276 isWindowObscuredLocked(windowHandle))) {
6277 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6278 "%" PRId32 ".",
6279 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6280 windowHandle->getInfo()->inputFeatures.string().c_str(),
6281 windowHandle->getInfo()->displayId);
6282 return true;
6283 }
6284 return false;
6285}
6286
Garfield Tane84e6f92019-08-29 17:28:41 -07006287} // namespace android::inputdispatcher