blob: 9da71925ce4cd77ee3fd452797e12d90d9929c08 [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;
chaviw98318de2021-05-19 16:45:23 -050058using android::gui::FocusRequest;
59using android::gui::TouchOcclusionMode;
60using android::gui::WindowInfo;
61using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100063using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080064using android::os::InputEventInjectionResult;
65using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100066using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067
Garfield Tane84e6f92019-08-29 17:28:41 -070068namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
Prabir Pradhancef936d2021-07-21 16:17:52 +000070namespace {
71
Prabir Pradhan61a5d242021-07-26 16:41:09 +000072// Log detailed debug messages about each inbound event notification to the dispatcher.
73constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
74
75// Log detailed debug messages about each outbound event processed by the dispatcher.
76constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
77
78// Log debug messages about the dispatch cycle.
79constexpr bool DEBUG_DISPATCH_CYCLE = false;
80
81// Log debug messages about channel creation
82constexpr bool DEBUG_CHANNEL_CREATION = false;
83
84// Log debug messages about input event injection.
85constexpr bool DEBUG_INJECTION = false;
86
87// Log debug messages about input focus tracking.
88constexpr bool DEBUG_FOCUS = false;
89
90// Log debug messages about touch occlusion
91// STOPSHIP(b/169067926): Set to false
92constexpr bool DEBUG_TOUCH_OCCLUSION = true;
93
94// Log debug messages about the app switch latency optimization.
95constexpr bool DEBUG_APP_SWITCH = false;
96
97// Log debug messages about hover events.
98constexpr bool DEBUG_HOVER = false;
99
Prabir Pradhancef936d2021-07-21 16:17:52 +0000100// Temporarily releases a held mutex for the lifetime of the instance.
101// Named to match std::scoped_lock
102class scoped_unlock {
103public:
104 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
105 ~scoped_unlock() { mMutex.lock(); }
106
107private:
108 std::mutex& mMutex;
109};
110
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700111// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
112// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000113bool isPerWindowInputRotationEnabled() {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700114 static const bool PER_WINDOW_INPUT_ROTATION =
Vadim Tryshev7719c7d2021-08-27 17:28:43 +0000115 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700116
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700117 return PER_WINDOW_INPUT_ROTATION;
118}
119
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120// Default input dispatching timeout if there is no focused application or paused window
121// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800122const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
123 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
124 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
126// Amount of time to allow for all pending events to be processed when an app switch
127// key is on the way. This is used to preempt input dispatch and drop input events
128// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000129constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130
131// Amount of time to allow for an event to be dispatched (measured since its eventTime)
132// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000133constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135// 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 +0000136constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
137
138// Log a warning when an interception call takes longer than this to process.
139constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700141// Additional key latency in case a connection is still processing some motion events.
142// This will help with the case when a user touched a button that opens a new window,
143// and gives us the chance to dispatch the key to this new window.
144constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
145
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000147constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
148
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000149// Event log tags. See EventLogTags.logtags for reference
150constexpr int LOGTAG_INPUT_INTERACTION = 62000;
151constexpr int LOGTAG_INPUT_FOCUS = 62001;
152
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000153inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 return systemTime(SYSTEM_TIME_MONOTONIC);
155}
156
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000157inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800158 return value ? "true" : "false";
159}
160
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000161inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000162 if (binder == nullptr) {
163 return "<null>";
164 }
165 return StringPrintf("%p", binder.get());
166}
167
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000168inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
170 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171}
172
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000173bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 case AKEY_EVENT_ACTION_DOWN:
176 case AKEY_EVENT_ACTION_UP:
177 return true;
178 default:
179 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 }
181}
182
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000183bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Key event has invalid action code 0x%x", action);
186 return false;
187 }
188 return true;
189}
190
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000191bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 case AMOTION_EVENT_ACTION_DOWN:
194 case AMOTION_EVENT_ACTION_UP:
195 case AMOTION_EVENT_ACTION_CANCEL:
196 case AMOTION_EVENT_ACTION_MOVE:
197 case AMOTION_EVENT_ACTION_OUTSIDE:
198 case AMOTION_EVENT_ACTION_HOVER_ENTER:
199 case AMOTION_EVENT_ACTION_HOVER_MOVE:
200 case AMOTION_EVENT_ACTION_HOVER_EXIT:
201 case AMOTION_EVENT_ACTION_SCROLL:
202 return true;
203 case AMOTION_EVENT_ACTION_POINTER_DOWN:
204 case AMOTION_EVENT_ACTION_POINTER_UP: {
205 int32_t index = getMotionEventActionPointerIndex(action);
206 return index >= 0 && index < pointerCount;
207 }
208 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
209 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
210 return actionButton != 0;
211 default:
212 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214}
215
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000216int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500217 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
218}
219
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000220bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
221 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700222 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 ALOGE("Motion event has invalid action code 0x%x", action);
224 return false;
225 }
226 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000227 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700228 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 return false;
230 }
231 BitSet32 pointerIdBits;
232 for (size_t i = 0; i < pointerCount; i++) {
233 int32_t id = pointerProperties[i].id;
234 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700235 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
236 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 return false;
238 }
239 if (pointerIdBits.hasBit(id)) {
240 ALOGE("Motion event has duplicate pointer id %d", id);
241 return false;
242 }
243 pointerIdBits.markBit(id);
244 }
245 return true;
246}
247
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000248std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000250 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 }
252
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000253 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 bool first = true;
255 Region::const_iterator cur = region.begin();
256 Region::const_iterator const tail = region.end();
257 while (cur != tail) {
258 if (first) {
259 first = false;
260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800261 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800263 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 cur++;
265 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000266 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267}
268
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500270 constexpr size_t maxEntries = 50; // max events to print
271 constexpr size_t skipBegin = maxEntries / 2;
272 const size_t skipEnd = queue.size() - maxEntries / 2;
273 // skip from maxEntries / 2 ... size() - maxEntries/2
274 // only print from 0 .. skipBegin and then from skipEnd .. size()
275
276 std::string dump;
277 for (size_t i = 0; i < queue.size(); i++) {
278 const DispatchEntry& entry = *queue[i];
279 if (i >= skipBegin && i < skipEnd) {
280 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
281 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
282 continue;
283 }
284 dump.append(INDENT4);
285 dump += entry.eventEntry->getDescription();
286 dump += StringPrintf(", seq=%" PRIu32
287 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
288 entry.seq, entry.targetFlags, entry.resolvedAction,
289 ns2ms(currentTime - entry.eventEntry->eventTime));
290 if (entry.deliveryTime != 0) {
291 // This entry was delivered, so add information on how long we've been waiting
292 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
293 }
294 dump.append("\n");
295 }
296 return dump;
297}
298
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700299/**
300 * Find the entry in std::unordered_map by key, and return it.
301 * If the entry is not found, return a default constructed entry.
302 *
303 * Useful when the entries are vectors, since an empty vector will be returned
304 * if the entry is not found.
305 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
306 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700307template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000308V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700309 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700310 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800311}
312
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700314 if (first == second) {
315 return true;
316 }
317
318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321
322 return first->getToken() == second->getToken();
323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329 return first->applicationInfo.token != nullptr &&
330 first->applicationInfo.token == second->applicationInfo.token;
331}
332
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000333bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800334 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
335}
336
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000337std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
338 std::shared_ptr<EventEntry> eventEntry,
339 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900340 if (eventEntry->type == EventEntry::Type::MOTION) {
341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700342 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
343 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900344 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700345 // Use identity transform for joystick and position-based (touchpad) events because they
346 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900347 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700348 1.0f /*globalScaleFactor*/,
Evan Rosky09576692021-07-01 12:22:09 -0700349 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700350 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900351 }
352 }
353
chaviw1ff3d1e2020-07-01 15:53:47 -0700354 if (inputTarget.useDefaultPointerTransform()) {
355 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700356 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700357 inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700358 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700359 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360 }
361
362 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700365 std::vector<PointerCoords> pointerCoords;
366 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 // Use the first pointer information to normalize all other pointers. This could be any pointer
369 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // uses the transform for the normalized pointer.
371 const ui::Transform& firstPointerTransform =
372 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
373 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374
375 // Iterate through all pointers in the event to normalize against the first.
376 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
377 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
378 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 // First, apply the current pointer's transform to update the coordinates into
383 // window space.
384 pointerCoords[pointerIndex].transform(currTransform);
385 // Next, apply the inverse transform of the normalized coordinates so the
386 // current coordinates are transformed into the normalized coordinate space.
387 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388 }
389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700390 std::unique_ptr<MotionEntry> combinedMotionEntry =
391 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
392 motionEntry.deviceId, motionEntry.source,
393 motionEntry.displayId, motionEntry.policyFlags,
394 motionEntry.action, motionEntry.actionButton,
395 motionEntry.flags, motionEntry.metaState,
396 motionEntry.buttonState, motionEntry.classification,
397 motionEntry.edgeFlags, motionEntry.xPrecision,
398 motionEntry.yPrecision, motionEntry.xCursorPosition,
399 motionEntry.yCursorPosition, motionEntry.downTime,
400 motionEntry.pointerCount, motionEntry.pointerProperties,
401 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000402
403 if (motionEntry.injectionState) {
404 combinedMotionEntry->injectionState = motionEntry.injectionState;
405 combinedMotionEntry->injectionState->refCount += 1;
406 }
407
408 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700409 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700410 firstPointerTransform, inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700411 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700412 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000413 return dispatchEntry;
414}
415
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000416void addGestureMonitors(const std::vector<Monitor>& monitors,
417 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
418 float yOffset = 0) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700419 if (monitors.empty()) {
420 return;
421 }
422 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
423 for (const Monitor& monitor : monitors) {
424 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
425 }
426}
427
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000428status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
429 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700430 std::unique_ptr<InputChannel> uniqueServerChannel;
431 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
432
433 serverChannel = std::move(uniqueServerChannel);
434 return result;
435}
436
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500437template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000438bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500439 if (lhs == nullptr && rhs == nullptr) {
440 return true;
441 }
442 if (lhs == nullptr || rhs == nullptr) {
443 return false;
444 }
445 return *lhs == *rhs;
446}
447
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000448sp<IPlatformCompatNative> getCompatService() {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000449 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
450 if (service == nullptr) {
451 ALOGE("Failed to link to compat service");
452 return nullptr;
453 }
454 return interface_cast<IPlatformCompatNative>(service);
455}
456
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000457KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000458 KeyEvent event;
459 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
460 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
461 entry.repeatCount, entry.downTime, entry.eventTime);
462 return event;
463}
464
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000465std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000466 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
467 const sp<IBinder>& token) {
468 for (const auto& it : monitorsByDisplay) {
469 const std::vector<Monitor>& monitors = it.second;
470 for (const Monitor& monitor : monitors) {
471 if (monitor.inputChannel->getConnectionToken() == token) {
472 return monitor.pid;
473 }
474 }
475 }
476 return std::nullopt;
477}
478
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000479bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000480 // Do not keep track of gesture monitors. They receive every event and would disproportionately
481 // affect the statistics.
482 if (connection.monitor) {
483 return false;
484 }
485 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
486 if (!connection.responsive) {
487 return false;
488 }
489 return true;
490}
491
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000492bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000493 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
494 const int32_t& inputEventId = eventEntry.id;
495 if (inputEventId != dispatchEntry.resolvedEventId) {
496 // Event was transmuted
497 return false;
498 }
499 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
500 return false;
501 }
502 // Only track latency for events that originated from hardware
503 if (eventEntry.isSynthesized()) {
504 return false;
505 }
506 const EventEntry::Type& inputEventEntryType = eventEntry.type;
507 if (inputEventEntryType == EventEntry::Type::KEY) {
508 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
509 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
510 return false;
511 }
512 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
513 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
514 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
515 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
516 return false;
517 }
518 } else {
519 // Not a key or a motion
520 return false;
521 }
522 if (!shouldReportMetricsForConnection(connection)) {
523 return false;
524 }
525 return true;
526}
527
Prabir Pradhancef936d2021-07-21 16:17:52 +0000528/**
529 * Connection is responsive if it has no events in the waitQueue that are older than the
530 * current time.
531 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000532bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000533 const nsecs_t currentTime = now();
534 for (const DispatchEntry* entry : connection.waitQueue) {
535 if (entry->timeoutTime < currentTime) {
536 return false;
537 }
538 }
539 return true;
540}
541
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000542} // namespace
543
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544// --- InputDispatcher ---
545
Garfield Tan00f511d2019-06-12 16:55:40 -0700546InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
547 : mPolicy(policy),
548 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700549 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800550 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700551 mAppSwitchSawKeyDown(false),
552 mAppSwitchDueTime(LONG_LONG_MAX),
553 mNextUnblockedEvent(nullptr),
554 mDispatchEnabled(false),
555 mDispatchFrozen(false),
556 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800557 // mInTouchMode will be initialized by the WindowManager to the default device config.
558 // To avoid leaking stack in case that call never comes, and for tests,
559 // initialize it here anyways.
560 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100561 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000562 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800563 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000564 mLatencyAggregator(),
565 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000566 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800568 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569
Yi Kong9b14ac62018-07-17 13:48:38 -0700570 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571
572 policy->getDispatcherConfiguration(&mConfig);
573}
574
575InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000576 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
Prabir Pradhancef936d2021-07-21 16:17:52 +0000578 resetKeyRepeatLocked();
579 releasePendingEventLocked();
580 drainInboundQueueLocked();
581 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000583 while (!mConnectionsByToken.empty()) {
584 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000585 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
586 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 }
588}
589
chaviw15fab6f2021-06-07 14:15:52 -0500590void InputDispatcher::onFirstRef() {
591 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
592}
593
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700594status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700595 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596 return ALREADY_EXISTS;
597 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700598 mThread = std::make_unique<InputThread>(
599 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
600 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700601}
602
603status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700604 if (mThread && mThread->isCallingThread()) {
605 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700606 return INVALID_OPERATION;
607 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700608 mThread.reset();
609 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700610}
611
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612void InputDispatcher::dispatchOnce() {
613 nsecs_t nextWakeupTime = LONG_LONG_MAX;
614 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800615 std::scoped_lock _l(mLock);
616 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617
618 // Run a dispatch loop if there are no pending commands.
619 // The dispatch loop might enqueue commands to run afterwards.
620 if (!haveCommandsLocked()) {
621 dispatchOnceInnerLocked(&nextWakeupTime);
622 }
623
624 // Run all pending commands if there are any.
625 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000626 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 nextWakeupTime = LONG_LONG_MIN;
628 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800629
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700630 // If we are still waiting for ack on some events,
631 // we might have to wake up earlier to check if an app is anr'ing.
632 const nsecs_t nextAnrCheck = processAnrsLocked();
633 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
634
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800635 // We are about to enter an infinitely long sleep, because we have no commands or
636 // pending or queued events
637 if (nextWakeupTime == LONG_LONG_MAX) {
638 mDispatcherEnteredIdle.notify_all();
639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 } // release lock
641
642 // Wait for callback or timeout or wake. (make sure we round up, not down)
643 nsecs_t currentTime = now();
644 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
645 mLooper->pollOnce(timeoutMillis);
646}
647
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500649 * Raise ANR if there is no focused window.
650 * Before the ANR is raised, do a final state check:
651 * 1. The currently focused application must be the same one we are waiting for.
652 * 2. Ensure we still don't have a focused window.
653 */
654void InputDispatcher::processNoFocusedWindowAnrLocked() {
655 // Check if the application that we are waiting for is still focused.
656 std::shared_ptr<InputApplicationHandle> focusedApplication =
657 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
658 if (focusedApplication == nullptr ||
659 focusedApplication->getApplicationToken() !=
660 mAwaitedFocusedApplication->getApplicationToken()) {
661 // Unexpected because we should have reset the ANR timer when focused application changed
662 ALOGE("Waited for a focused window, but focused application has already changed to %s",
663 focusedApplication->getName().c_str());
664 return; // The focused application has changed.
665 }
666
chaviw98318de2021-05-19 16:45:23 -0500667 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500668 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
669 if (focusedWindowHandle != nullptr) {
670 return; // We now have a focused window. No need for ANR.
671 }
672 onAnrLocked(mAwaitedFocusedApplication);
673}
674
675/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700676 * Check if any of the connections' wait queues have events that are too old.
677 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
678 * Return the time at which we should wake up next.
679 */
680nsecs_t InputDispatcher::processAnrsLocked() {
681 const nsecs_t currentTime = now();
682 nsecs_t nextAnrCheck = LONG_LONG_MAX;
683 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
684 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
685 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500686 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700687 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500688 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 return LONG_LONG_MIN;
690 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500691 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700692 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
693 }
694 }
695
696 // Check if any connection ANRs are due
697 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
698 if (currentTime < nextAnrCheck) { // most likely scenario
699 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
700 }
701
702 // If we reached here, we have an unresponsive connection.
703 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
704 if (connection == nullptr) {
705 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
706 return nextAnrCheck;
707 }
708 connection->responsive = false;
709 // Stop waking up for this unresponsive connection
710 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000711 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 return LONG_LONG_MIN;
713}
714
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500715std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500716 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700717 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500718 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500720 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721}
722
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
724 nsecs_t currentTime = now();
725
Jeff Browndc5992e2014-04-11 01:27:26 -0700726 // Reset the key repeat timer whenever normal dispatch is suspended while the
727 // device is in a non-interactive state. This is to ensure that we abort a key
728 // repeat if the device is just coming out of sleep.
729 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 resetKeyRepeatLocked();
731 }
732
733 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
734 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100735 if (DEBUG_FOCUS) {
736 ALOGD("Dispatch frozen. Waiting some more.");
737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 return;
739 }
740
741 // Optimize latency of app switches.
742 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
743 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
744 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
745 if (mAppSwitchDueTime < *nextWakeupTime) {
746 *nextWakeupTime = mAppSwitchDueTime;
747 }
748
749 // Ready to start a new event.
750 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700751 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700752 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 if (isAppSwitchDue) {
754 // The inbound queue is empty so the app switch key we were waiting
755 // for will never arrive. Stop waiting for it.
756 resetPendingAppSwitchLocked(false);
757 isAppSwitchDue = false;
758 }
759
760 // Synthesize a key repeat if appropriate.
761 if (mKeyRepeatState.lastKeyEntry) {
762 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
763 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
764 } else {
765 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
766 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
767 }
768 }
769 }
770
771 // Nothing to do if there is no pending event.
772 if (!mPendingEvent) {
773 return;
774 }
775 } else {
776 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700777 mPendingEvent = mInboundQueue.front();
778 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 traceInboundQueueLengthLocked();
780 }
781
782 // Poke user activity for this event.
783 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700784 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787
788 // Now we have an event to dispatch.
789 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700790 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700792 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 }
798
799 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700800 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802
803 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700804 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700805 const ConfigurationChangedEntry& typedEntry =
806 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700808 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 break;
810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700812 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700813 const DeviceResetEntry& typedEntry =
814 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 break;
818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100820 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700821 std::shared_ptr<FocusEntry> typedEntry =
822 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100823 dispatchFocusLocked(currentTime, typedEntry);
824 done = true;
825 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
826 break;
827 }
828
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700829 case EventEntry::Type::TOUCH_MODE_CHANGED: {
830 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
831 dispatchTouchModeChangeLocked(currentTime, typedEntry);
832 done = true;
833 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
834 break;
835 }
836
Prabir Pradhan99987712020-11-10 18:43:05 -0800837 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
838 const auto typedEntry =
839 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
840 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
841 done = true;
842 break;
843 }
844
arthurhungb89ccb02020-12-30 16:19:01 +0800845 case EventEntry::Type::DRAG: {
846 std::shared_ptr<DragEntry> typedEntry =
847 std::static_pointer_cast<DragEntry>(mPendingEvent);
848 dispatchDragLocked(currentTime, typedEntry);
849 done = true;
850 break;
851 }
852
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700853 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700854 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 resetPendingAppSwitchLocked(true);
858 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 } else if (dropReason == DropReason::NOT_DROPPED) {
860 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 }
862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700864 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
867 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 break;
871 }
872
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700873 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 std::shared_ptr<MotionEntry> motionEntry =
875 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
877 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700880 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
883 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700885 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 }
Chris Yef59a2f42020-10-16 12:55:26 -0700888
889 case EventEntry::Type::SENSOR: {
890 std::shared_ptr<SensorEntry> sensorEntry =
891 std::static_pointer_cast<SensorEntry>(mPendingEvent);
892 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
893 dropReason = DropReason::APP_SWITCH;
894 }
895 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
896 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
897 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
898 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
899 dropReason = DropReason::STALE;
900 }
901 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
902 done = true;
903 break;
904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
906
907 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700908 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700909 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
Michael Wright3a981722015-06-10 15:26:13 +0100911 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
913 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 }
916}
917
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700918/**
919 * Return true if the events preceding this incoming motion event should be dropped
920 * Return false otherwise (the default behaviour)
921 */
922bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925
926 // Optimize case where the current application is unresponsive and the user
927 // decides to touch a window in a different application.
928 // If the application takes too long to catch up then we drop all events preceding
929 // the touch into the other window.
930 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700931 int32_t displayId = motionEntry.displayId;
932 int32_t x = static_cast<int32_t>(
933 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
934 int32_t y = static_cast<int32_t>(
935 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500936 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 findTouchedWindowAtLocked(displayId, x, y, nullptr);
938 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 touchedWindowHandle->getApplicationToken() !=
940 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 ALOGI("Pruning input queue because user touched a different application while waiting "
943 "for %s",
944 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700945 return true;
946 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947
948 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600949 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
951 sp<Connection> connection =
952 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000953 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700954 // This monitor could take more input. Drop all events preceding this
955 // event, so that gesture monitor could get a chance to receive the stream
956 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
957 "responsive gesture monitor that may handle the event",
958 mAwaitedFocusedApplication->getName().c_str());
959 return true;
960 }
961 }
962 }
963
964 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
965 // yet been processed by some connections, the dispatcher will wait for these motion
966 // events to be processed before dispatching the key event. This is because these motion events
967 // may cause a new window to be launched, which the user might expect to receive focus.
968 // To prevent waiting forever for such events, just send the key to the currently focused window
969 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
970 ALOGD("Received a new pointer down event, stop waiting for events to process and "
971 "just send the pending key event to the focused window.");
972 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700973 }
974 return false;
975}
976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700978 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 mInboundQueue.push_back(std::move(newEntry));
980 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 traceInboundQueueLengthLocked();
982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700984 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 // Optimize app switch latency.
986 // If the application takes too long to catch up then we drop all events preceding
987 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700988 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700990 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000994 if (DEBUG_APP_SWITCH) {
995 ALOGD("App switch is pending!");
996 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 mAppSwitchSawKeyDown = false;
999 needWake = true;
1000 }
1001 }
1002 }
1003 break;
1004 }
1005
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001006 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001007 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1008 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001009 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001013 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001014 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1015 break;
1016 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001017 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001018 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001019 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001020 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001021 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1022 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 // nothing to do
1024 break;
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027
1028 return needWake;
1029}
1030
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001031void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001032 // Do not store sensor event in recent queue to avoid flooding the queue.
1033 if (entry->type != EventEntry::Type::SENSOR) {
1034 mRecentQueue.push_back(entry);
1035 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001036 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001037 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039}
1040
chaviw98318de2021-05-19 16:45:23 -05001041sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1042 int32_t y, TouchState* touchState,
1043 bool addOutsideTargets,
1044 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001045 if (addOutsideTargets && touchState == nullptr) {
1046 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001049 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1050 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001051 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001052 continue;
1053 }
chaviw98318de2021-05-19 16:45:23 -05001054 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001056 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057
1058 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001059 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1060 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1061 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1063 // Found window.
1064 return windowHandle;
1065 }
1066 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001067
chaviw98318de2021-05-19 16:45:23 -05001068 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001069 touchState->addOrUpdateWindow(windowHandle,
1070 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1071 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
1075 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001076 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077}
1078
Garfield Tane84e6f92019-08-29 17:28:41 -07001079std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001080 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001081 std::vector<TouchedMonitor> touchedMonitors;
1082
1083 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1084 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001085 return touchedMonitors;
1086}
1087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001088void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 const char* reason;
1090 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001092 if (DEBUG_INBOUND_EVENT_DETAILS) {
1093 ALOGD("Dropped event because policy consumed it.");
1094 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 reason = "inbound event was dropped because the policy consumed it";
1096 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 case DropReason::DISABLED:
1098 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 ALOGI("Dropped event because input dispatch is disabled.");
1100 }
1101 reason = "inbound event was dropped because input dispatch is disabled";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because of pending overdue app switch.");
1105 reason = "inbound event was dropped because of pending overdue app switch";
1106 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001107 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 ALOGI("Dropped event because the current application is not responding and the user "
1109 "has started interacting with a different application.");
1110 reason = "inbound event was dropped because the current application is not responding "
1111 "and the user has started interacting with a different application";
1112 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 ALOGI("Dropped event because it is stale.");
1115 reason = "inbound event was dropped because it is stale";
1116 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001117 case DropReason::NO_POINTER_CAPTURE:
1118 ALOGI("Dropped event because there is no window with Pointer Capture.");
1119 reason = "inbound event was dropped because there is no window with Pointer Capture";
1120 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 case DropReason::NOT_DROPPED: {
1122 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001127 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001128 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1130 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001134 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1135 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1137 synthesizeCancelationEventsForAllConnectionsLocked(options);
1138 } else {
1139 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1140 synthesizeCancelationEventsForAllConnectionsLocked(options);
1141 }
1142 break;
1143 }
Chris Yef59a2f42020-10-16 12:55:26 -07001144 case EventEntry::Type::SENSOR: {
1145 break;
1146 }
arthurhungb89ccb02020-12-30 16:19:01 +08001147 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1148 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001149 break;
1150 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001151 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001152 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001153 case EventEntry::Type::CONFIGURATION_CHANGED:
1154 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001155 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001156 break;
1157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159}
1160
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001161static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1163 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164}
1165
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1167 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1168 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1169 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170}
1171
1172bool InputDispatcher::isAppSwitchPendingLocked() {
1173 return mAppSwitchDueTime != LONG_LONG_MAX;
1174}
1175
1176void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1177 mAppSwitchDueTime = LONG_LONG_MAX;
1178
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001179 if (DEBUG_APP_SWITCH) {
1180 if (handled) {
1181 ALOGD("App switch has arrived.");
1182 } else {
1183 ALOGD("App switch was abandoned.");
1184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186}
1187
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190}
1191
Prabir Pradhancef936d2021-07-21 16:17:52 +00001192bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001193 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return false;
1195 }
1196
1197 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001198 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001199 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001200 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1201 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001202 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 return true;
1204}
1205
Prabir Pradhancef936d2021-07-21 16:17:52 +00001206void InputDispatcher::postCommandLocked(Command&& command) {
1207 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
1210void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001211 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001212 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001213 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 releaseInboundEventLocked(entry);
1215 }
1216 traceInboundQueueLengthLocked();
1217}
1218
1219void InputDispatcher::releasePendingEventLocked() {
1220 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001222 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224}
1225
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001226void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001228 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001229 if (DEBUG_DISPATCH_CYCLE) {
1230 ALOGD("Injected inbound event was dropped.");
1231 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001235 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 }
1237 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238}
1239
1240void InputDispatcher::resetKeyRepeatLocked() {
1241 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001242 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244}
1245
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1247 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
Michael Wright2e732952014-09-24 13:26:59 -07001249 uint32_t policyFlags = entry->policyFlags &
1250 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 std::shared_ptr<KeyEntry> newEntry =
1253 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1254 entry->source, entry->displayId, policyFlags, entry->action,
1255 entry->flags, entry->keyCode, entry->scanCode,
1256 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001258 newEntry->syntheticRepeat = true;
1259 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262}
1263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001266 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1267 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269
1270 // Reset key repeating in case a keyboard device was added or removed or something.
1271 resetKeyRepeatLocked();
1272
1273 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001274 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1275 scoped_unlock unlock(mLock);
1276 mPolicy->notifyConfigurationChanged(eventTime);
1277 };
1278 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280}
1281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1283 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001284 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1285 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1286 entry.deviceId);
1287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
liushenxiang42232912021-05-21 20:24:09 +08001289 // Reset key repeating in case a keyboard device was disabled or enabled.
1290 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1291 resetKeyRepeatLocked();
1292 }
1293
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 synthesizeCancelationEventsForAllConnectionsLocked(options);
1297 return true;
1298}
1299
Vishnu Nairad321cd2020-08-20 16:40:21 -07001300void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001301 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302 if (mPendingEvent != nullptr) {
1303 // Move the pending event to the front of the queue. This will give the chance
1304 // for the pending event to get dispatched to the newly focused window
1305 mInboundQueue.push_front(mPendingEvent);
1306 mPendingEvent = nullptr;
1307 }
1308
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001309 std::unique_ptr<FocusEntry> focusEntry =
1310 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1311 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001312
1313 // This event should go to the front of the queue, but behind all other focus events
1314 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001316 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001317 [](const std::shared_ptr<EventEntry>& event) {
1318 return event->type == EventEntry::Type::FOCUS;
1319 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001320
1321 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001322 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001323}
1324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001326 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001327 if (channel == nullptr) {
1328 return; // Window has gone away
1329 }
1330 InputTarget target;
1331 target.inputChannel = channel;
1332 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1333 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001334 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1335 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001336 std::string reason = std::string("reason=").append(entry->reason);
1337 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001338 dispatchEventLocked(currentTime, entry, {target});
1339}
1340
Prabir Pradhan99987712020-11-10 18:43:05 -08001341void InputDispatcher::dispatchPointerCaptureChangedLocked(
1342 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1343 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001344 dropReason = DropReason::NOT_DROPPED;
1345
Prabir Pradhan99987712020-11-10 18:43:05 -08001346 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001347 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001348
1349 if (entry->pointerCaptureRequest.enable) {
1350 // Enable Pointer Capture.
1351 if (haveWindowWithPointerCapture &&
1352 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1353 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1354 "to the window.");
1355 }
1356 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001357 // This can happen if a window requests capture and immediately releases capture.
1358 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001359 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001360 return;
1361 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001362 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1363 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1364 return;
1365 }
1366
Vishnu Nairc519ff72021-01-21 08:23:08 -08001367 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1369 mWindowTokenWithPointerCapture = token;
1370 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001371 // Disable Pointer Capture.
1372 // We do not check if the sequence number matches for requests to disable Pointer Capture
1373 // for two reasons:
1374 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1375 // to disable capture with the same sequence number: one generated by
1376 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1377 // Capture being disabled in InputReader.
1378 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1379 // actual Pointer Capture state that affects events being generated by input devices is
1380 // in InputReader.
1381 if (!haveWindowWithPointerCapture) {
1382 // Pointer capture was already forcefully disabled because of focus change.
1383 dropReason = DropReason::NOT_DROPPED;
1384 return;
1385 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001386 token = mWindowTokenWithPointerCapture;
1387 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001388 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001389 setPointerCaptureLocked(false);
1390 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 }
1392
1393 auto channel = getInputChannelLocked(token);
1394 if (channel == nullptr) {
1395 // Window has gone away, clean up Pointer Capture state.
1396 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001397 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001398 setPointerCaptureLocked(false);
1399 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001400 return;
1401 }
1402 InputTarget target;
1403 target.inputChannel = channel;
1404 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1405 entry->dispatchInProgress = true;
1406 dispatchEventLocked(currentTime, entry, {target});
1407
1408 dropReason = DropReason::NOT_DROPPED;
1409}
1410
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001411void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1412 const std::shared_ptr<TouchModeEntry>& entry) {
1413 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1414 getWindowHandlesLocked(mFocusedDisplayId);
1415 if (windowHandles.empty()) {
1416 return;
1417 }
1418 const std::vector<InputTarget> inputTargets =
1419 getInputTargetsFromWindowHandlesLocked(windowHandles);
1420 if (inputTargets.empty()) {
1421 return;
1422 }
1423 entry->dispatchInProgress = true;
1424 dispatchEventLocked(currentTime, entry, inputTargets);
1425}
1426
1427std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1428 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1429 std::vector<InputTarget> inputTargets;
1430 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1431 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1432 const sp<IBinder>& token = handle->getToken();
1433 if (token == nullptr) {
1434 continue;
1435 }
1436 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1437 if (channel == nullptr) {
1438 continue; // Window has gone away
1439 }
1440 InputTarget target;
1441 target.inputChannel = channel;
1442 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1443 inputTargets.push_back(target);
1444 }
1445 return inputTargets;
1446}
1447
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001448bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 if (!entry->dispatchInProgress) {
1452 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1453 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1454 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1455 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001456 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 // We have seen two identical key downs in a row which indicates that the device
1458 // driver is automatically generating key repeats itself. We take note of the
1459 // repeat here, but we disable our own next key repeat timer since it is clear that
1460 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001461 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1462 // Make sure we don't get key down from a different device. If a different
1463 // device Id has same key pressed down, the new device Id will replace the
1464 // current one to hold the key repeat with repeat count reset.
1465 // In the future when got a KEY_UP on the device id, drop it and do not
1466 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1468 resetKeyRepeatLocked();
1469 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1470 } else {
1471 // Not a repeat. Save key down state in case we do see a repeat later.
1472 resetKeyRepeatLocked();
1473 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1474 }
1475 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001476 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1477 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001478 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001479 if (DEBUG_INBOUND_EVENT_DETAILS) {
1480 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1481 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 resetKeyRepeatLocked();
1484 }
1485
1486 if (entry->repeatCount == 1) {
1487 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1488 } else {
1489 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1490 }
1491
1492 entry->dispatchInProgress = true;
1493
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001494 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
1496
1497 // Handle case where the policy asked us to try again later last time.
1498 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1499 if (currentTime < entry->interceptKeyWakeupTime) {
1500 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1501 *nextWakeupTime = entry->interceptKeyWakeupTime;
1502 }
1503 return false; // wait until next wakeup
1504 }
1505 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1506 entry->interceptKeyWakeupTime = 0;
1507 }
1508
1509 // Give the policy a chance to intercept the key.
1510 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1511 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001512 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001513 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001514
1515 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1516 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1517 };
1518 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 return false; // wait for the command to run
1520 } else {
1521 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1522 }
1523 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001524 if (*dropReason == DropReason::NOT_DROPPED) {
1525 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527 }
1528
1529 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001530 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1533 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001534 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 return true;
1536 }
1537
1538 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001539 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001540 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001542 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 return false;
1544 }
1545
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001546 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 return true;
1549 }
1550
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001551 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001552 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553
1554 // Dispatch the key.
1555 dispatchEventLocked(currentTime, entry, inputTargets);
1556 return true;
1557}
1558
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001559void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001560 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1561 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1562 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1563 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1564 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1565 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1566 entry.metaState, entry.repeatCount, entry.downTime);
1567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568}
1569
Prabir Pradhancef936d2021-07-21 16:17:52 +00001570void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1571 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001572 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001573 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1574 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1575 "source=0x%x, sensorType=%s",
1576 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001577 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001578 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001579 auto command = [this, entry]() REQUIRES(mLock) {
1580 scoped_unlock unlock(mLock);
1581
1582 if (entry->accuracyChanged) {
1583 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1584 }
1585 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1586 entry->hwTimestamp, entry->values);
1587 };
1588 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001589}
1590
1591bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1593 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001594 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001595 }
Chris Yef59a2f42020-10-16 12:55:26 -07001596 { // acquire lock
1597 std::scoped_lock _l(mLock);
1598
1599 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1600 std::shared_ptr<EventEntry> entry = *it;
1601 if (entry->type == EventEntry::Type::SENSOR) {
1602 it = mInboundQueue.erase(it);
1603 releaseInboundEventLocked(entry);
1604 }
1605 }
1606 }
1607 return true;
1608}
1609
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001610bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001612 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 entry->dispatchInProgress = true;
1616
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001617 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 }
1619
1620 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001621 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001622 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001623 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1624 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 return true;
1626 }
1627
1628 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1629
1630 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001631 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632
1633 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001634 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 if (isPointerEvent) {
1636 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001637 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001638 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001639 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 } else {
1641 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001643 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 return false;
1647 }
1648
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001649 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001650 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001651 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1652 return true;
1653 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001654 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001655 CancelationOptions::Mode mode(isPointerEvent
1656 ? CancelationOptions::CANCEL_POINTER_EVENTS
1657 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1658 CancelationOptions options(mode, "input event injection failed");
1659 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 return true;
1661 }
1662
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001663 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001664 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665
1666 // Dispatch the motion.
1667 if (conflictingPointerActions) {
1668 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001669 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 synthesizeCancelationEventsForAllConnectionsLocked(options);
1671 }
1672 dispatchEventLocked(currentTime, entry, inputTargets);
1673 return true;
1674}
1675
chaviw98318de2021-05-19 16:45:23 -05001676void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001677 bool isExiting, const MotionEntry& motionEntry) {
1678 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1679 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1680 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1681 PointerCoords pointerCoords;
1682 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1683 pointerCoords.transform(windowHandle->getInfo()->transform);
1684
1685 std::unique_ptr<DragEntry> dragEntry =
1686 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1687 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1688 pointerCoords.getY());
1689
1690 enqueueInboundEventLocked(std::move(dragEntry));
1691}
1692
1693void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1694 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1695 if (channel == nullptr) {
1696 return; // Window has gone away
1697 }
1698 InputTarget target;
1699 target.inputChannel = channel;
1700 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1701 entry->dispatchInProgress = true;
1702 dispatchEventLocked(currentTime, entry, {target});
1703}
1704
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001705void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001706 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1707 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1708 ", policyFlags=0x%x, "
1709 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1710 "metaState=0x%x, buttonState=0x%x,"
1711 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1712 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1713 entry.policyFlags, entry.action, entry.actionButton, entry.flags, entry.metaState,
1714 entry.buttonState, entry.edgeFlags, entry.xPrecision, entry.yPrecision,
1715 entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001717 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1718 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1719 "x=%f, y=%f, pressure=%f, size=%f, "
1720 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1721 "orientation=%f",
1722 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1723 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1724 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1725 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1726 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1727 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1728 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1729 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1730 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1731 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734}
1735
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001736void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1737 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001740 if (DEBUG_DISPATCH_CYCLE) {
1741 ALOGD("dispatchEventToCurrentInputTargets");
1742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001744 updateInteractionTokensLocked(*eventEntry, inputTargets);
1745
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1747
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001748 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001750 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001751 sp<Connection> connection =
1752 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001753 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001754 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001756 if (DEBUG_FOCUS) {
1757 ALOGD("Dropping event delivery to target with channel '%s' because it "
1758 "is no longer registered with the input dispatcher.",
1759 inputTarget.inputChannel->getName().c_str());
1760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762 }
1763}
1764
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1766 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1767 // If the policy decides to close the app, we will get a channel removal event via
1768 // unregisterInputChannel, and will clean up the connection that way. We are already not
1769 // sending new pointers to the connection when it blocked, but focused events will continue to
1770 // pile up.
1771 ALOGW("Canceling events for %s because it is unresponsive",
1772 connection->inputChannel->getName().c_str());
1773 if (connection->status == Connection::STATUS_NORMAL) {
1774 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1775 "application not responding");
1776 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
1778}
1779
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001780void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001781 if (DEBUG_FOCUS) {
1782 ALOGD("Resetting ANR timeouts.");
1783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784
1785 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001787 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788}
1789
Tiger Huang721e26f2018-07-24 22:26:19 +08001790/**
1791 * Get the display id that the given event should go to. If this event specifies a valid display id,
1792 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1793 * Focused display is the display that the user most recently interacted with.
1794 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001796 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001798 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001799 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1800 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 break;
1802 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001803 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001804 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1805 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 break;
1807 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001808 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001809 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001810 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001811 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001812 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001813 case EventEntry::Type::SENSOR:
1814 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001815 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001816 return ADISPLAY_ID_NONE;
1817 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001818 }
1819 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1820}
1821
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1823 const char* focusedWindowName) {
1824 if (mAnrTracker.empty()) {
1825 // already processed all events that we waited for
1826 mKeyIsWaitingForEventsTimeout = std::nullopt;
1827 return false;
1828 }
1829
1830 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1831 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001832 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001833 mKeyIsWaitingForEventsTimeout = currentTime +
1834 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1835 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 return true;
1837 }
1838
1839 // We still have pending events, and already started the timer
1840 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1841 return true; // Still waiting
1842 }
1843
1844 // Waited too long, and some connection still hasn't processed all motions
1845 // Just send the key to the focused window
1846 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1847 focusedWindowName);
1848 mKeyIsWaitingForEventsTimeout = std::nullopt;
1849 return false;
1850}
1851
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1853 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1854 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001855 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
Tiger Huang721e26f2018-07-24 22:26:19 +08001857 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001858 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001859 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001860 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1861
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 // If there is no currently focused window and no focused application
1863 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001864 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1865 ALOGI("Dropping %s event because there is no focused window or focused application in "
1866 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001867 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
1870
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001871 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1872 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1873 // start interacting with another application via touch (app switch). This code can be removed
1874 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1875 // an app is expected to have a focused window.
1876 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1877 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1878 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001879 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1880 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1881 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001883 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 ALOGW("Waiting because no window has focus but %s may eventually add a "
1885 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001886 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1890 // Already raised ANR. Drop the event
1891 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001892 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 } else {
1895 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001896 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001897 }
1898 }
1899
1900 // we have a valid, non-null focused window
1901 resetNoFocusedWindowTimeoutLocked();
1902
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001904 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001905 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 }
1907
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 if (focusedWindowHandle->getInfo()->paused) {
1909 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001911 }
1912
1913 // If the event is a key event, then we must wait for all previous events to
1914 // complete before delivering it because previous events may have the
1915 // side-effect of transferring focus to a different window and we want to
1916 // ensure that the following keys are sent to the new window.
1917 //
1918 // Suppose the user touches a button in a window then immediately presses "A".
1919 // If the button causes a pop-up window to appear then we want to ensure that
1920 // the "A" key is delivered to the new pop-up window. This is because users
1921 // often anticipate pending UI changes when typing on a keyboard.
1922 // To obtain this behavior, we must serialize key events with respect to all
1923 // prior input events.
1924 if (entry.type == EventEntry::Type::KEY) {
1925 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1926 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
1930
1931 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001932 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1934 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
1936 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938}
1939
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001940/**
1941 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1942 * that are currently unresponsive.
1943 */
1944std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1945 const std::vector<TouchedMonitor>& monitors) const {
1946 std::vector<TouchedMonitor> responsiveMonitors;
1947 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1948 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1949 sp<Connection> connection = getConnectionLocked(
1950 monitor.monitor.inputChannel->getConnectionToken());
1951 if (connection == nullptr) {
1952 ALOGE("Could not find connection for monitor %s",
1953 monitor.monitor.inputChannel->getName().c_str());
1954 return false;
1955 }
1956 if (!connection->responsive) {
1957 ALOGW("Unresponsive monitor %s will not get the new gesture",
1958 connection->inputChannel->getName().c_str());
1959 return false;
1960 }
1961 return true;
1962 });
1963 return responsiveMonitors;
1964}
1965
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001966InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1967 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1968 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 enum InjectionPermission {
1971 INJECTION_PERMISSION_UNKNOWN,
1972 INJECTION_PERMISSION_GRANTED,
1973 INJECTION_PERMISSION_DENIED
1974 };
1975
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 // For security reasons, we defer updating the touch state until we are sure that
1977 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001978 int32_t displayId = entry.displayId;
1979 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1981
1982 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001983 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001985 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1986 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 // Copy current touch state into tempTouchState.
1989 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1990 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001991 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001992 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001993 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1994 mTouchStatesByDisplay.find(displayId);
1995 if (oldStateIt != mTouchStatesByDisplay.end()) {
1996 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001998 }
1999
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002000 bool isSplit = tempTouchState.split;
2001 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2002 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2003 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002004 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2005 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2006 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2007 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2008 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002009 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 bool wrongDevice = false;
2011 if (newGesture) {
2012 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002014 ALOGI("Dropping event because a pointer for a different device is already down "
2015 "in display %" PRId32,
2016 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002017 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002018 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 switchedDevice = false;
2020 wrongDevice = true;
2021 goto Failed;
2022 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 tempTouchState.reset();
2024 tempTouchState.down = down;
2025 tempTouchState.deviceId = entry.deviceId;
2026 tempTouchState.source = entry.source;
2027 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002029 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002030 ALOGI("Dropping move event because a pointer for a different device is already active "
2031 "in display %" PRId32,
2032 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002033 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002035 switchedDevice = false;
2036 wrongDevice = true;
2037 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 }
2039
2040 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2041 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2042
Garfield Tan00f511d2019-06-12 16:55:40 -07002043 int32_t x;
2044 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 // Always dispatch mouse events to cursor position.
2047 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 x = int32_t(entry.xCursorPosition);
2049 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002050 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2052 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002053 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002054 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002055 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2056 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002057
2058 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002059 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00002060 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 if (newTouchedWindowHandle != nullptr &&
2064 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002065 // New window supports splitting, but we should never split mouse events.
2066 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 } else if (isSplit) {
2068 // New window does not support splitting but we have already split events.
2069 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002070 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
2072
2073 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002074 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002076 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 }
2078
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002079 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2080 ALOGI("Not sending touch event to %s because it is paused",
2081 newTouchedWindowHandle->getName().c_str());
2082 newTouchedWindowHandle = nullptr;
2083 }
2084
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002085 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002087 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2088 if (!isResponsive) {
2089 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2091 newTouchedWindowHandle = nullptr;
2092 }
2093 }
2094
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002095 // Drop events that can't be trusted due to occlusion
2096 if (newTouchedWindowHandle != nullptr &&
2097 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2098 TouchOcclusionInfo occlusionInfo =
2099 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002100 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002101 if (DEBUG_TOUCH_OCCLUSION) {
2102 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2103 for (const auto& log : occlusionInfo.debugInfo) {
2104 ALOGD("%s", log.c_str());
2105 }
2106 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002107 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002108 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2109 ALOGW("Dropping untrusted touch event due to %s/%d",
2110 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2111 newTouchedWindowHandle = nullptr;
2112 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002113 }
2114 }
2115
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 // Also don't send the new touch event to unresponsive gesture monitors
2117 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2118
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2120 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 "(%d, %d) in display %" PRId32 ".",
2122 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002123 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002124 goto Failed;
2125 }
2126
2127 if (newTouchedWindowHandle != nullptr) {
2128 // Set target flags.
2129 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2130 if (isSplit) {
2131 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002133 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2134 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2135 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2136 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2137 }
2138
2139 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002140 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2141 newHoverWindowHandle = nullptr;
2142 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 }
2145
2146 // Update the temporary touch state.
2147 BitSet32 pointerIds;
2148 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002149 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002150 pointerIds.markBit(pointerId);
2151 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002152 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 } else {
2157 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2158
2159 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002160 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002161 if (DEBUG_FOCUS) {
2162 ALOGD("Dropping event because the pointer is not down or we previously "
2163 "dropped the pointer down event in display %" PRId32,
2164 displayId);
2165 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002166 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 goto Failed;
2168 }
2169
arthurhung6d4bed92021-03-17 11:59:33 +08002170 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002171
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002173 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002175 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2176 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177
chaviw98318de2021-05-19 16:45:23 -05002178 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002179 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002180 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
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
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002330 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002333 }
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Drop the outside or hover touch windows since we will not care about them
2336 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002337 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
2339Failed:
2340 // Check injection permission once and for all.
2341 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002342 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 injectionPermission = INJECTION_PERMISSION_GRANTED;
2344 } else {
2345 injectionPermission = INJECTION_PERMISSION_DENIED;
2346 }
2347 }
2348
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002349 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2350 return injectionResult;
2351 }
2352
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002354 if (!wrongDevice) {
2355 if (switchedDevice) {
2356 if (DEBUG_FOCUS) {
2357 ALOGD("Conflicting pointer actions: Switched to a different device.");
2358 }
2359 *outConflictingPointerActions = true;
2360 }
2361
2362 if (isHoverAction) {
2363 // Started hovering, therefore no longer down.
2364 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002365 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2367 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 *outConflictingPointerActions = true;
2370 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 tempTouchState.reset();
2372 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2373 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2374 tempTouchState.deviceId = entry.deviceId;
2375 tempTouchState.source = entry.source;
2376 tempTouchState.displayId = displayId;
2377 }
2378 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2379 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2380 // All pointers up or canceled.
2381 tempTouchState.reset();
2382 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2383 // First pointer went down.
2384 if (oldState && oldState->down) {
2385 if (DEBUG_FOCUS) {
2386 ALOGD("Conflicting pointer actions: Down received while already down.");
2387 }
2388 *outConflictingPointerActions = true;
2389 }
2390 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2391 // One pointer went up.
2392 if (isSplit) {
2393 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2394 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002396 for (size_t i = 0; i < tempTouchState.windows.size();) {
2397 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2398 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2399 touchedWindow.pointerIds.clearBit(pointerId);
2400 if (touchedWindow.pointerIds.isEmpty()) {
2401 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2402 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002405 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002407 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002408 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002409
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002410 // Save changes unless the action was scroll in which case the temporary touch
2411 // state was only valid for this one action.
2412 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2413 if (tempTouchState.displayId >= 0) {
2414 mTouchStatesByDisplay[displayId] = tempTouchState;
2415 } else {
2416 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002420 // Update hover state.
2421 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 return injectionResult;
2425}
2426
arthurhung6d4bed92021-03-17 11:59:33 +08002427void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002428 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002429 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002430 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002431 if (dropWindow) {
2432 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002433 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002434 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002435 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002436 }
2437 mDragState.reset();
2438}
2439
2440void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2441 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002442 return;
2443 }
2444
arthurhung6d4bed92021-03-17 11:59:33 +08002445 if (!mDragState->isStartDrag) {
2446 mDragState->isStartDrag = true;
2447 mDragState->isStylusButtonDownAtStart =
2448 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2449 }
2450
arthurhungb89ccb02020-12-30 16:19:01 +08002451 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2452 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2453 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2454 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002455 // Handle the special case : stylus button no longer pressed.
2456 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2457 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2458 finishDragAndDrop(entry.displayId, x, y);
2459 return;
2460 }
2461
chaviw98318de2021-05-19 16:45:23 -05002462 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002463 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002464 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002465 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002466 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2467 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2468 if (mDragState->dragHoverWindowHandle != nullptr) {
2469 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2470 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002471 }
arthurhung6d4bed92021-03-17 11:59:33 +08002472 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002473 }
2474 // enqueue drag location if needed.
2475 if (hoverWindowHandle != nullptr) {
2476 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2477 }
arthurhung6d4bed92021-03-17 11:59:33 +08002478 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2479 finishDragAndDrop(entry.displayId, x, y);
2480 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002481 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002482 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002483 }
2484}
2485
chaviw98318de2021-05-19 16:45:23 -05002486void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 int32_t targetFlags, BitSet32 pointerIds,
2488 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002489 std::vector<InputTarget>::iterator it =
2490 std::find_if(inputTargets.begin(), inputTargets.end(),
2491 [&windowHandle](const InputTarget& inputTarget) {
2492 return inputTarget.inputChannel->getConnectionToken() ==
2493 windowHandle->getToken();
2494 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002495
chaviw98318de2021-05-19 16:45:23 -05002496 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002497
2498 if (it == inputTargets.end()) {
2499 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002500 std::shared_ptr<InputChannel> inputChannel =
2501 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002502 if (inputChannel == nullptr) {
2503 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2504 return;
2505 }
2506 inputTarget.inputChannel = inputChannel;
2507 inputTarget.flags = targetFlags;
2508 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002509 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002510 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002511 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002512 inputTargets.push_back(inputTarget);
2513 it = inputTargets.end() - 1;
2514 }
2515
2516 ALOG_ASSERT(it->flags == targetFlags);
2517 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2518
chaviw1ff3d1e2020-07-01 15:53:47 -07002519 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520}
2521
Michael Wright3dd60e22019-03-27 22:06:44 +00002522void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 int32_t displayId, float xOffset,
2524 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002525 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2526 mGlobalMonitorsByDisplay.find(displayId);
2527
2528 if (it != mGlobalMonitorsByDisplay.end()) {
2529 const std::vector<Monitor>& monitors = it->second;
2530 for (const Monitor& monitor : monitors) {
2531 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534}
2535
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2537 float yOffset,
2538 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002539 InputTarget target;
2540 target.inputChannel = monitor.inputChannel;
2541 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002542 ui::Transform t;
2543 t.set(xOffset, yOffset);
2544 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002545 inputTargets.push_back(target);
2546}
2547
chaviw98318de2021-05-19 16:45:23 -05002548bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 const InjectionState* injectionState) {
2550 if (injectionState &&
2551 (windowHandle == nullptr ||
2552 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2553 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002554 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 "owned by uid %d",
2557 injectionState->injectorPid, injectionState->injectorUid,
2558 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 } else {
2560 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
2563 return false;
2564 }
2565 return true;
2566}
2567
Robert Carrc9bf1d32020-04-13 17:21:08 -07002568/**
2569 * Indicate whether one window handle should be considered as obscuring
2570 * another window handle. We only check a few preconditions. Actually
2571 * checking the bounds is left to the caller.
2572 */
chaviw98318de2021-05-19 16:45:23 -05002573static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2574 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002575 // Compare by token so cloned layers aren't counted
2576 if (haveSameToken(windowHandle, otherHandle)) {
2577 return false;
2578 }
2579 auto info = windowHandle->getInfo();
2580 auto otherInfo = otherHandle->getInfo();
2581 if (!otherInfo->visible) {
2582 return false;
chaviw98318de2021-05-19 16:45:23 -05002583 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002584 // Those act as if they were invisible, so we don't need to flag them.
2585 // We do want to potentially flag touchable windows even if they have 0
2586 // opacity, since they can consume touches and alter the effects of the
2587 // user interaction (eg. apps that rely on
2588 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2589 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2590 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002591 } else if (info->ownerUid == otherInfo->ownerUid) {
2592 // If ownerUid is the same we don't generate occlusion events as there
2593 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002594 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002595 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002596 return false;
2597 } else if (otherInfo->displayId != info->displayId) {
2598 return false;
2599 }
2600 return true;
2601}
2602
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002603/**
2604 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2605 * untrusted, one should check:
2606 *
2607 * 1. If result.hasBlockingOcclusion is true.
2608 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2609 * BLOCK_UNTRUSTED.
2610 *
2611 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2612 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2613 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2614 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2615 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2616 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2617 *
2618 * If neither of those is true, then it means the touch can be allowed.
2619 */
2620InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002621 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2622 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002623 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002624 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002625 TouchOcclusionInfo info;
2626 info.hasBlockingOcclusion = false;
2627 info.obscuringOpacity = 0;
2628 info.obscuringUid = -1;
2629 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002630 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002631 if (windowHandle == otherHandle) {
2632 break; // All future windows are below us. Exit early.
2633 }
chaviw98318de2021-05-19 16:45:23 -05002634 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002635 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2636 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002637 if (DEBUG_TOUCH_OCCLUSION) {
2638 info.debugInfo.push_back(
2639 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2640 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002641 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2642 // we perform the checks below to see if the touch can be propagated or not based on the
2643 // window's touch occlusion mode
2644 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2645 info.hasBlockingOcclusion = true;
2646 info.obscuringUid = otherInfo->ownerUid;
2647 info.obscuringPackage = otherInfo->packageName;
2648 break;
2649 }
2650 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2651 uint32_t uid = otherInfo->ownerUid;
2652 float opacity =
2653 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2654 // Given windows A and B:
2655 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2656 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2657 opacityByUid[uid] = opacity;
2658 if (opacity > info.obscuringOpacity) {
2659 info.obscuringOpacity = opacity;
2660 info.obscuringUid = uid;
2661 info.obscuringPackage = otherInfo->packageName;
2662 }
2663 }
2664 }
2665 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002666 if (DEBUG_TOUCH_OCCLUSION) {
2667 info.debugInfo.push_back(
2668 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2669 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002670 return info;
2671}
2672
chaviw98318de2021-05-19 16:45:23 -05002673std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002674 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002675 return StringPrintf(INDENT2
2676 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2677 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2678 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2679 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002680 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002681 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002682 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2683 info->frameTop, info->frameRight, info->frameBottom,
2684 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002685 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2686 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2687 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002688}
2689
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002690bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2691 if (occlusionInfo.hasBlockingOcclusion) {
2692 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2693 occlusionInfo.obscuringUid);
2694 return false;
2695 }
2696 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2697 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2698 "%.2f, maximum allowed = %.2f)",
2699 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2700 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2701 return false;
2702 }
2703 return true;
2704}
2705
chaviw98318de2021-05-19 16:45:23 -05002706bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002707 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002709 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2710 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002711 if (windowHandle == otherHandle) {
2712 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 }
chaviw98318de2021-05-19 16:45:23 -05002714 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002715 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002716 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 return true;
2718 }
2719 }
2720 return false;
2721}
2722
chaviw98318de2021-05-19 16:45:23 -05002723bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002724 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002725 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2726 const WindowInfo* windowInfo = windowHandle->getInfo();
2727 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002728 if (windowHandle == otherHandle) {
2729 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002730 }
chaviw98318de2021-05-19 16:45:23 -05002731 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002732 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002733 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002734 return true;
2735 }
2736 }
2737 return false;
2738}
2739
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002740std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002741 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002742 if (applicationHandle != nullptr) {
2743 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002744 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 } else {
2746 return applicationHandle->getName();
2747 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002748 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002749 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002751 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753}
2754
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002755void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002756 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002757 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2758 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002759 // Focus or pointer capture changed events are passed to apps, but do not represent user
2760 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002761 return;
2762 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002763 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002764 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002765 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002766 const WindowInfo* info = focusedWindowHandle->getInfo();
2767 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002768 if (DEBUG_DISPATCH_CYCLE) {
2769 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 return;
2772 }
2773 }
2774
2775 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002776 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002777 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002778 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2779 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 return;
2781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002783 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 eventType = USER_ACTIVITY_EVENT_TOUCH;
2785 }
2786 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002788 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002789 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2790 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 return;
2792 }
2793 eventType = USER_ACTIVITY_EVENT_BUTTON;
2794 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07002796 case EventEntry::Type::TOUCH_MODE_CHANGED: {
2797 break;
2798 }
2799
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002800 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002801 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002802 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002803 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002804 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2805 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002806 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002807 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002808 break;
2809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811
Prabir Pradhancef936d2021-07-21 16:17:52 +00002812 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2813 REQUIRES(mLock) {
2814 scoped_unlock unlock(mLock);
2815 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2816 };
2817 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818}
2819
2820void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002822 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002823 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002824 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002826 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002827 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002828 ATRACE_NAME(message.c_str());
2829 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002830 if (DEBUG_DISPATCH_CYCLE) {
2831 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2832 "globalScaleFactor=%f, pointerIds=0x%x %s",
2833 connection->getInputChannelName().c_str(), inputTarget.flags,
2834 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2835 inputTarget.getPointerInfoString().c_str());
2836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
2838 // Skip this event if the connection status is not normal.
2839 // We don't want to enqueue additional outbound events if the connection is broken.
2840 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002841 if (DEBUG_DISPATCH_CYCLE) {
2842 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2843 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 return;
2846 }
2847
2848 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002849 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2850 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2851 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002852 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002854 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002855 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002856 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002857 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 if (!splitMotionEntry) {
2859 return; // split event was dropped
2860 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002861 if (DEBUG_FOCUS) {
2862 ALOGD("channel '%s' ~ Split motion event.",
2863 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002864 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002865 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002866 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2867 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 return;
2869 }
2870 }
2871
2872 // Not splitting. Enqueue dispatch entries for the event as is.
2873 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2874}
2875
2876void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002878 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002879 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002880 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002882 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002883 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002884 ATRACE_NAME(message.c_str());
2885 }
2886
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002887 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
2889 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002890 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002892 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002894 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002896 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002898 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002900 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902
2903 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002904 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 startDispatchCycleLocked(currentTime, connection);
2906 }
2907}
2908
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002910 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002911 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002913 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2915 connection->getInputChannelName().c_str(),
2916 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002917 ATRACE_NAME(message.c_str());
2918 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002919 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 if (!(inputTargetFlags & dispatchMode)) {
2921 return;
2922 }
2923 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2924
2925 // This is a new event.
2926 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002927 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002928 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002930 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2931 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002932 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002934 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002935 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002936 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002937 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002938 dispatchEntry->resolvedAction = keyEntry.action;
2939 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2942 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 if (DEBUG_DISPATCH_CYCLE) {
2944 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2945 "event",
2946 connection->getInputChannelName().c_str());
2947 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 return; // skip the inconsistent event
2949 }
2950 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002953 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002955 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2956 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2957 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2958 static_cast<int32_t>(IdGenerator::Source::OTHER);
2959 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2961 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2962 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2963 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2964 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2965 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2966 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2967 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2968 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2969 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2970 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002971 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002972 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 }
2974 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002975 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2976 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002977 if (DEBUG_DISPATCH_CYCLE) {
2978 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2979 "enter event",
2980 connection->getInputChannelName().c_str());
2981 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002982 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2983 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002987 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002988 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2989 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2990 }
2991 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2992 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2996 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002997 if (DEBUG_DISPATCH_CYCLE) {
2998 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2999 "event",
3000 connection->getInputChannelName().c_str());
3001 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 return; // skip the inconsistent event
3003 }
3004
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003005 dispatchEntry->resolvedEventId =
3006 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3007 ? mIdGenerator.nextId()
3008 : motionEntry.id;
3009 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3010 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3011 ") to MotionEvent(id=0x%" PRIx32 ").",
3012 motionEntry.id, dispatchEntry->resolvedEventId);
3013 ATRACE_NAME(message.c_str());
3014 }
3015
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003016 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3017 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3018 // Skip reporting pointer down outside focus to the policy.
3019 break;
3020 }
3021
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003022 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003023 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024
3025 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003027 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003028 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003029 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3030 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003031 break;
3032 }
Chris Yef59a2f42020-10-16 12:55:26 -07003033 case EventEntry::Type::SENSOR: {
3034 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3035 break;
3036 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003037 case EventEntry::Type::CONFIGURATION_CHANGED:
3038 case EventEntry::Type::DEVICE_RESET: {
3039 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003040 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003041 break;
3042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
3044
3045 // Remember that we are waiting for this dispatch to complete.
3046 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003047 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
3049
3050 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003051 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003052 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003053}
3054
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003055/**
3056 * This function is purely for debugging. It helps us understand where the user interaction
3057 * was taking place. For example, if user is touching launcher, we will see a log that user
3058 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3059 * We will see both launcher and wallpaper in that list.
3060 * Once the interaction with a particular set of connections starts, no new logs will be printed
3061 * until the set of interacted connections changes.
3062 *
3063 * The following items are skipped, to reduce the logspam:
3064 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3065 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3066 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3067 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3068 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003069 */
3070void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3071 const std::vector<InputTarget>& targets) {
3072 // Skip ACTION_UP events, and all events other than keys and motions
3073 if (entry.type == EventEntry::Type::KEY) {
3074 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3075 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3076 return;
3077 }
3078 } else if (entry.type == EventEntry::Type::MOTION) {
3079 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3080 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3081 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3082 return;
3083 }
3084 } else {
3085 return; // Not a key or a motion
3086 }
3087
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003088 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003089 std::vector<sp<Connection>> newConnections;
3090 for (const InputTarget& target : targets) {
3091 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3092 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3093 continue; // Skip windows that receive ACTION_OUTSIDE
3094 }
3095
3096 sp<IBinder> token = target.inputChannel->getConnectionToken();
3097 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003098 if (connection == nullptr) {
3099 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003100 }
3101 newConnectionTokens.insert(std::move(token));
3102 newConnections.emplace_back(connection);
3103 }
3104 if (newConnectionTokens == mInteractionConnectionTokens) {
3105 return; // no change
3106 }
3107 mInteractionConnectionTokens = newConnectionTokens;
3108
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003109 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003110 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003111 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003112 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003113 std::string message = "Interaction with: " + targetList;
3114 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003115 message += "<none>";
3116 }
3117 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3118}
3119
chaviwfd6d3512019-03-25 13:23:49 -07003120void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003121 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003122 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003123 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3124 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003125 return;
3126 }
3127
Vishnu Nairc519ff72021-01-21 08:23:08 -08003128 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003129 if (focusedToken == token) {
3130 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003131 return;
3132 }
3133
Prabir Pradhancef936d2021-07-21 16:17:52 +00003134 auto command = [this, token]() REQUIRES(mLock) {
3135 scoped_unlock unlock(mLock);
3136 mPolicy->onPointerDownOutsideFocus(token);
3137 };
3138 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139}
3140
3141void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003143 if (ATRACE_ENABLED()) {
3144 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003146 ATRACE_NAME(message.c_str());
3147 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003148 if (DEBUG_DISPATCH_CYCLE) {
3149 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003152 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3153 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003155 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003156 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003157 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
3159 // Publish the event.
3160 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3162 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003163 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3165 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003168 status = connection->inputPublisher
3169 .publishKeyEvent(dispatchEntry->seq,
3170 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3171 keyEntry.source, keyEntry.displayId,
3172 std::move(hmac), dispatchEntry->resolvedAction,
3173 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3174 keyEntry.scanCode, keyEntry.metaState,
3175 keyEntry.repeatCount, keyEntry.downTime,
3176 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
3179
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003180 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003184 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185
chaviw82357092020-01-28 13:13:06 -08003186 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003187 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3189 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003190 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003191 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3192 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003193 // Don't apply window scale here since we don't want scale to affect raw
3194 // coordinates. The scale will be sent back to the client and applied
3195 // later when requesting relative coordinates.
3196 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3197 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 }
3199 usingCoords = scaledCoords;
3200 }
3201 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 // We don't want the dispatch target to know.
3203 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 scaledCoords[i].clear();
3206 }
3207 usingCoords = scaledCoords;
3208 }
3209 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003211 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212
3213 // Publish the motion event.
3214 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003215 .publishMotionEvent(dispatchEntry->seq,
3216 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003217 motionEntry.deviceId, motionEntry.source,
3218 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003219 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003222 motionEntry.edgeFlags, motionEntry.metaState,
3223 motionEntry.buttonState,
3224 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003225 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003226 motionEntry.xPrecision, motionEntry.yPrecision,
3227 motionEntry.xCursorPosition,
3228 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003229 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003230 dispatchEntry->displaySize.x,
3231 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 motionEntry.downTime, motionEntry.eventTime,
3233 motionEntry.pointerCount,
3234 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 break;
3236 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003237
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003238 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003240 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 focusEntry.id,
3242 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003243 mInTouchMode);
3244 break;
3245 }
3246
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003247 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3248 const TouchModeEntry& touchModeEntry =
3249 static_cast<const TouchModeEntry&>(eventEntry);
3250 status = connection->inputPublisher
3251 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3252 touchModeEntry.inTouchMode);
3253
3254 break;
3255 }
3256
Prabir Pradhan99987712020-11-10 18:43:05 -08003257 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3258 const auto& captureEntry =
3259 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3260 status = connection->inputPublisher
3261 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003262 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003263 break;
3264 }
3265
arthurhungb89ccb02020-12-30 16:19:01 +08003266 case EventEntry::Type::DRAG: {
3267 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3268 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3269 dragEntry.id, dragEntry.x,
3270 dragEntry.y,
3271 dragEntry.isExiting);
3272 break;
3273 }
3274
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003275 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003276 case EventEntry::Type::DEVICE_RESET:
3277 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003278 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003279 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
3284 // Check the result.
3285 if (status) {
3286 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 "This is unexpected because the wait queue is empty, so the pipe "
3290 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003291 "event to it, status=%s(%d)",
3292 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3293 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3295 } else {
3296 // Pipe is full and we are waiting for the app to finish process some events
3297 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003298 if (DEBUG_DISPATCH_CYCLE) {
3299 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3300 "waiting for the application to catch up",
3301 connection->getInputChannelName().c_str());
3302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 }
3304 } else {
3305 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003306 "status=%s(%d)",
3307 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3308 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3310 }
3311 return;
3312 }
3313
3314 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3316 connection->outboundQueue.end(),
3317 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003318 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003319 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003320 if (connection->responsive) {
3321 mAnrTracker.insert(dispatchEntry->timeoutTime,
3322 connection->inputChannel->getConnectionToken());
3323 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003324 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
3326}
3327
chaviw09c8d2d2020-08-24 15:48:26 -07003328std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3329 size_t size;
3330 switch (event.type) {
3331 case VerifiedInputEvent::Type::KEY: {
3332 size = sizeof(VerifiedKeyEvent);
3333 break;
3334 }
3335 case VerifiedInputEvent::Type::MOTION: {
3336 size = sizeof(VerifiedMotionEvent);
3337 break;
3338 }
3339 }
3340 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3341 return mHmacKeyManager.sign(start, size);
3342}
3343
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003344const std::array<uint8_t, 32> InputDispatcher::getSignature(
3345 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3346 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3347 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3348 // Only sign events up and down events as the purely move events
3349 // are tied to their up/down counterparts so signing would be redundant.
3350 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3351 verifiedEvent.actionMasked = actionMasked;
3352 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003353 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003354 }
3355 return INVALID_HMAC;
3356}
3357
3358const std::array<uint8_t, 32> InputDispatcher::getSignature(
3359 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3360 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3361 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3362 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003363 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003364}
3365
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003368 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003369 if (DEBUG_DISPATCH_CYCLE) {
3370 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3371 connection->getInputChannelName().c_str(), seq, toString(handled));
3372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 if (connection->status == Connection::STATUS_BROKEN ||
3375 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 return;
3377 }
3378
3379 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003380 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3381 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3382 };
3383 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384}
3385
3386void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 const sp<Connection>& connection,
3388 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003389 if (DEBUG_DISPATCH_CYCLE) {
3390 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3391 connection->getInputChannelName().c_str(), toString(notify));
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
3394 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003395 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003396 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003397 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003398 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399
3400 // The connection appears to be unrecoverably broken.
3401 // Ignore already broken or zombie connections.
3402 if (connection->status == Connection::STATUS_NORMAL) {
3403 connection->status = Connection::STATUS_BROKEN;
3404
3405 if (notify) {
3406 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003407 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3408 connection->getInputChannelName().c_str());
3409
3410 auto command = [this, connection]() REQUIRES(mLock) {
3411 if (connection->status == Connection::STATUS_ZOMBIE) return;
3412 scoped_unlock unlock(mLock);
3413 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3414 };
3415 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417 }
3418}
3419
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003420void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3421 while (!queue.empty()) {
3422 DispatchEntry* dispatchEntry = queue.front();
3423 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003424 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426}
3427
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003428void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003430 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 }
3432 delete dispatchEntry;
3433}
3434
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003435int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3436 std::scoped_lock _l(mLock);
3437 sp<Connection> connection = getConnectionLocked(connectionToken);
3438 if (connection == nullptr) {
3439 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3440 connectionToken.get(), events);
3441 return 0; // remove the callback
3442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003444 bool notify;
3445 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3446 if (!(events & ALOOPER_EVENT_INPUT)) {
3447 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3448 "events=0x%x",
3449 connection->getInputChannelName().c_str(), events);
3450 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003453 nsecs_t currentTime = now();
3454 bool gotOne = false;
3455 status_t status = OK;
3456 for (;;) {
3457 Result<InputPublisher::ConsumerResponse> result =
3458 connection->inputPublisher.receiveConsumerResponse();
3459 if (!result.ok()) {
3460 status = result.error().code();
3461 break;
3462 }
3463
3464 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3465 const InputPublisher::Finished& finish =
3466 std::get<InputPublisher::Finished>(*result);
3467 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3468 finish.consumeTime);
3469 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003470 if (shouldReportMetricsForConnection(*connection)) {
3471 const InputPublisher::Timeline& timeline =
3472 std::get<InputPublisher::Timeline>(*result);
3473 mLatencyTracker
3474 .trackGraphicsLatency(timeline.inputEventId,
3475 connection->inputChannel->getConnectionToken(),
3476 std::move(timeline.graphicsTimeline));
3477 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003478 }
3479 gotOne = true;
3480 }
3481 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003482 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003483 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 return 1;
3485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003488 notify = status != DEAD_OBJECT || !connection->monitor;
3489 if (notify) {
3490 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3491 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3492 status);
3493 }
3494 } else {
3495 // Monitor channels are never explicitly unregistered.
3496 // We do it automatically when the remote endpoint is closed so don't warn about them.
3497 const bool stillHaveWindowHandle =
3498 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3499 notify = !connection->monitor && stillHaveWindowHandle;
3500 if (notify) {
3501 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3502 connection->getInputChannelName().c_str(), events);
3503 }
3504 }
3505
3506 // Remove the channel.
3507 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3508 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509}
3510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003513 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003514 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516}
3517
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003519 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003520 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3521 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3522}
3523
3524void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3525 const CancelationOptions& options,
3526 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3527 for (const auto& it : monitorsByDisplay) {
3528 const std::vector<Monitor>& monitors = it.second;
3529 for (const Monitor& monitor : monitors) {
3530 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003531 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003532 }
3533}
3534
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003536 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003537 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003538 if (connection == nullptr) {
3539 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003541
3542 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543}
3544
3545void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3546 const sp<Connection>& connection, const CancelationOptions& options) {
3547 if (connection->status == Connection::STATUS_BROKEN) {
3548 return;
3549 }
3550
3551 nsecs_t currentTime = now();
3552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003553 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003554 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003556 if (cancelationEvents.empty()) {
3557 return;
3558 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003559 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3560 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3561 "with reality: %s, mode=%d.",
3562 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3563 options.mode);
3564 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003565
3566 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003567 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003568 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3569 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003570 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003571 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003572 target.globalScaleFactor = windowInfo->globalScaleFactor;
3573 }
3574 target.inputChannel = connection->inputChannel;
3575 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3576
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003577 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003579 switch (cancelationEventEntry->type) {
3580 case EventEntry::Type::KEY: {
3581 logOutboundKeyDetails("cancel - ",
3582 static_cast<const KeyEntry&>(*cancelationEventEntry));
3583 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003585 case EventEntry::Type::MOTION: {
3586 logOutboundMotionDetails("cancel - ",
3587 static_cast<const MotionEntry&>(*cancelationEventEntry));
3588 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003590 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003591 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003592 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3593 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003594 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003595 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003596 break;
3597 }
3598 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003599 case EventEntry::Type::DEVICE_RESET:
3600 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003601 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003602 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003603 break;
3604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
3606
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003607 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3608 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003610
3611 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612}
3613
Svet Ganov5d3bc372020-01-26 23:11:07 -08003614void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3615 const sp<Connection>& connection) {
3616 if (connection->status == Connection::STATUS_BROKEN) {
3617 return;
3618 }
3619
3620 nsecs_t currentTime = now();
3621
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003622 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 connection->inputState.synthesizePointerDownEvents(currentTime);
3624
3625 if (downEvents.empty()) {
3626 return;
3627 }
3628
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003629 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003630 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3631 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003632 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003633
3634 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003635 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003636 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3637 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003638 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003639 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003640 target.globalScaleFactor = windowInfo->globalScaleFactor;
3641 }
3642 target.inputChannel = connection->inputChannel;
3643 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003645 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003646 switch (downEventEntry->type) {
3647 case EventEntry::Type::MOTION: {
3648 logOutboundMotionDetails("down - ",
3649 static_cast<const MotionEntry&>(*downEventEntry));
3650 break;
3651 }
3652
3653 case EventEntry::Type::KEY:
3654 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003655 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003656 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003657 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003658 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003659 case EventEntry::Type::SENSOR:
3660 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003662 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003663 break;
3664 }
3665 }
3666
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003667 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3668 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669 }
3670
3671 startDispatchCycleLocked(currentTime, connection);
3672}
3673
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003674std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3675 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 ALOG_ASSERT(pointerIds.value != 0);
3677
3678 uint32_t splitPointerIndexMap[MAX_POINTERS];
3679 PointerProperties splitPointerProperties[MAX_POINTERS];
3680 PointerCoords splitPointerCoords[MAX_POINTERS];
3681
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003682 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 uint32_t splitPointerCount = 0;
3684
3685 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003686 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003688 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 uint32_t pointerId = uint32_t(pointerProperties.id);
3690 if (pointerIds.hasBit(pointerId)) {
3691 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3692 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3693 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003694 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 splitPointerCount += 1;
3696 }
3697 }
3698
3699 if (splitPointerCount != pointerIds.count()) {
3700 // This is bad. We are missing some of the pointers that we expected to deliver.
3701 // Most likely this indicates that we received an ACTION_MOVE events that has
3702 // different pointer ids than we expected based on the previous ACTION_DOWN
3703 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3704 // in this way.
3705 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003706 "we expected there to be %d pointers. This probably means we received "
3707 "a broken sequence of pointer ids from the input device.",
3708 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003709 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
3711
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003712 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3715 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3717 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003718 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 uint32_t pointerId = uint32_t(pointerProperties.id);
3720 if (pointerIds.hasBit(pointerId)) {
3721 if (pointerIds.count() == 1) {
3722 // The first/last pointer went down/up.
3723 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003725 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3726 ? AMOTION_EVENT_ACTION_CANCEL
3727 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 } else {
3729 // A secondary pointer went down/up.
3730 uint32_t splitPointerIndex = 0;
3731 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3732 splitPointerIndex += 1;
3733 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003734 action = maskedAction |
3735 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737 } else {
3738 // An unrelated pointer changed.
3739 action = AMOTION_EVENT_ACTION_MOVE;
3740 }
3741 }
3742
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003743 int32_t newId = mIdGenerator.nextId();
3744 if (ATRACE_ENABLED()) {
3745 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3746 ") to MotionEvent(id=0x%" PRIx32 ").",
3747 originalMotionEntry.id, newId);
3748 ATRACE_NAME(message.c_str());
3749 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003750 std::unique_ptr<MotionEntry> splitMotionEntry =
3751 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3752 originalMotionEntry.deviceId, originalMotionEntry.source,
3753 originalMotionEntry.displayId,
3754 originalMotionEntry.policyFlags, action,
3755 originalMotionEntry.actionButton,
3756 originalMotionEntry.flags, originalMotionEntry.metaState,
3757 originalMotionEntry.buttonState,
3758 originalMotionEntry.classification,
3759 originalMotionEntry.edgeFlags,
3760 originalMotionEntry.xPrecision,
3761 originalMotionEntry.yPrecision,
3762 originalMotionEntry.xCursorPosition,
3763 originalMotionEntry.yCursorPosition,
3764 originalMotionEntry.downTime, splitPointerCount,
3765 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003767 if (originalMotionEntry.injectionState) {
3768 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 splitMotionEntry->injectionState->refCount += 1;
3770 }
3771
3772 return splitMotionEntry;
3773}
3774
3775void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003776 if (DEBUG_INBOUND_EVENT_DETAILS) {
3777 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
3780 bool needWake;
3781 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003782 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003784 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3785 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3786 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 } // release lock
3788
3789 if (needWake) {
3790 mLooper->wake();
3791 }
3792}
3793
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003794/**
3795 * If one of the meta shortcuts is detected, process them here:
3796 * Meta + Backspace -> generate BACK
3797 * Meta + Enter -> generate HOME
3798 * This will potentially overwrite keyCode and metaState.
3799 */
3800void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003802 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3803 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3804 if (keyCode == AKEYCODE_DEL) {
3805 newKeyCode = AKEYCODE_BACK;
3806 } else if (keyCode == AKEYCODE_ENTER) {
3807 newKeyCode = AKEYCODE_HOME;
3808 }
3809 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003810 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003811 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003812 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003813 keyCode = newKeyCode;
3814 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3815 }
3816 } else if (action == AKEY_EVENT_ACTION_UP) {
3817 // In order to maintain a consistent stream of up and down events, check to see if the key
3818 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3819 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003820 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003821 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003822 auto replacementIt = mReplacedKeys.find(replacement);
3823 if (replacementIt != mReplacedKeys.end()) {
3824 keyCode = replacementIt->second;
3825 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003826 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3827 }
3828 }
3829}
3830
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003832 if (DEBUG_INBOUND_EVENT_DETAILS) {
3833 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3834 "policyFlags=0x%x, action=0x%x, "
3835 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3836 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3837 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3838 args->downTime);
3839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 if (!validateKeyEvent(args->action)) {
3841 return;
3842 }
3843
3844 uint32_t policyFlags = args->policyFlags;
3845 int32_t flags = args->flags;
3846 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003847 // InputDispatcher tracks and generates key repeats on behalf of
3848 // whatever notifies it, so repeatCount should always be set to 0
3849 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3851 policyFlags |= POLICY_FLAG_VIRTUAL;
3852 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 if (policyFlags & POLICY_FLAG_FUNCTION) {
3855 metaState |= AMETA_FUNCTION_ON;
3856 }
3857
3858 policyFlags |= POLICY_FLAG_TRUSTED;
3859
Michael Wright78f24442014-08-06 15:55:28 -07003860 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003861 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003862
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003864 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003865 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3866 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867
Michael Wright2b3c3302018-03-02 17:19:13 +00003868 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003870 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3871 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 bool needWake;
3876 { // acquire lock
3877 mLock.lock();
3878
3879 if (shouldSendKeyToInputFilterLocked(args)) {
3880 mLock.unlock();
3881
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003882 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3884 return; // event was consumed by the filter
3885 }
3886
3887 mLock.lock();
3888 }
3889
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003890 std::unique_ptr<KeyEntry> newEntry =
3891 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3892 args->displayId, policyFlags, args->action, flags,
3893 keyCode, args->scanCode, metaState, repeatCount,
3894 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003896 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 mLock.unlock();
3898 } // release lock
3899
3900 if (needWake) {
3901 mLooper->wake();
3902 }
3903}
3904
3905bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3906 return mInputFilterEnabled;
3907}
3908
3909void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003910 if (DEBUG_INBOUND_EVENT_DETAILS) {
3911 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3912 "displayId=%" PRId32 ", policyFlags=0x%x, "
3913 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3914 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3915 "yCursorPosition=%f, downTime=%" PRId64,
3916 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3917 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3918 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3919 args->xCursorPosition, args->yCursorPosition, args->downTime);
3920 for (uint32_t i = 0; i < args->pointerCount; i++) {
3921 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3922 "x=%f, y=%f, pressure=%f, size=%f, "
3923 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3924 "orientation=%f",
3925 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3926 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3927 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3928 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3929 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3930 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3931 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3932 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3933 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3934 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003937 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3938 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 return;
3940 }
3941
3942 uint32_t policyFlags = args->policyFlags;
3943 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003944
3945 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003946 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003947 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3948 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951
3952 bool needWake;
3953 { // acquire lock
3954 mLock.lock();
3955
3956 if (shouldSendMotionToInputFilterLocked(args)) {
3957 mLock.unlock();
3958
3959 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003960 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003961 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3962 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003963 args->metaState, args->buttonState, args->classification, transform,
3964 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003965 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3966 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3967 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
3969 policyFlags |= POLICY_FLAG_FILTERED;
3970 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3971 return; // event was consumed by the filter
3972 }
3973
3974 mLock.lock();
3975 }
3976
3977 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003978 std::unique_ptr<MotionEntry> newEntry =
3979 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3980 args->source, args->displayId, policyFlags,
3981 args->action, args->actionButton, args->flags,
3982 args->metaState, args->buttonState,
3983 args->classification, args->edgeFlags,
3984 args->xPrecision, args->yPrecision,
3985 args->xCursorPosition, args->yCursorPosition,
3986 args->downTime, args->pointerCount,
3987 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003989 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3990 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3991 !mInputFilterEnabled) {
3992 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3993 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3994 }
3995
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003996 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 mLock.unlock();
3998 } // release lock
3999
4000 if (needWake) {
4001 mLooper->wake();
4002 }
4003}
4004
Chris Yef59a2f42020-10-16 12:55:26 -07004005void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004006 if (DEBUG_INBOUND_EVENT_DETAILS) {
4007 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4008 " sensorType=%s",
4009 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004010 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004011 }
Chris Yef59a2f42020-10-16 12:55:26 -07004012
4013 bool needWake;
4014 { // acquire lock
4015 mLock.lock();
4016
4017 // Just enqueue a new sensor event.
4018 std::unique_ptr<SensorEntry> newEntry =
4019 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4020 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4021 args->sensorType, args->accuracy,
4022 args->accuracyChanged, args->values);
4023
4024 needWake = enqueueInboundEventLocked(std::move(newEntry));
4025 mLock.unlock();
4026 } // release lock
4027
4028 if (needWake) {
4029 mLooper->wake();
4030 }
4031}
4032
Chris Yefb552902021-02-03 17:18:37 -08004033void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 if (DEBUG_INBOUND_EVENT_DETAILS) {
4035 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4036 args->deviceId, args->isOn);
4037 }
Chris Yefb552902021-02-03 17:18:37 -08004038 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4039}
4040
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004042 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043}
4044
4045void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004046 if (DEBUG_INBOUND_EVENT_DETAILS) {
4047 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4048 "switchMask=0x%08x",
4049 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
4052 uint32_t policyFlags = args->policyFlags;
4053 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055}
4056
4057void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004058 if (DEBUG_INBOUND_EVENT_DETAILS) {
4059 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4060 args->deviceId);
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
4063 bool needWake;
4064 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004065 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004067 std::unique_ptr<DeviceResetEntry> newEntry =
4068 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4069 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 } // release lock
4071
4072 if (needWake) {
4073 mLooper->wake();
4074 }
4075}
4076
Prabir Pradhan7e186182020-11-10 13:56:45 -08004077void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004078 if (DEBUG_INBOUND_EVENT_DETAILS) {
4079 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004080 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004081 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004082
Prabir Pradhan99987712020-11-10 18:43:05 -08004083 bool needWake;
4084 { // acquire lock
4085 std::scoped_lock _l(mLock);
4086 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004087 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004088 needWake = enqueueInboundEventLocked(std::move(entry));
4089 } // release lock
4090
4091 if (needWake) {
4092 mLooper->wake();
4093 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004094}
4095
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096InputEventInjectionResult InputDispatcher::injectInputEvent(
4097 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4098 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004099 if (DEBUG_INBOUND_EVENT_DETAILS) {
4100 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4101 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4102 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4103 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004104 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105
4106 policyFlags |= POLICY_FLAG_INJECTED;
4107 if (hasInjectionPermission(injectorPid, injectorUid)) {
4108 policyFlags |= POLICY_FLAG_TRUSTED;
4109 }
4110
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004112 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4113 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4114 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4115 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4116 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004117 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004118 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004120 }
4121
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004122 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004125 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4126 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004128 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004131 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004132 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4133 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4134 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004135 int32_t keyCode = incomingKey.getKeyCode();
4136 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004139 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004140 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004141 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4142 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4143 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4146 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004147 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148
4149 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4150 android::base::Timer t;
4151 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4152 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4153 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4154 std::to_string(t.duration().count()).c_str());
4155 }
4156 }
4157
4158 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004159 std::unique_ptr<KeyEntry> injectedEntry =
4160 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004161 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004162 incomingKey.getDisplayId(), policyFlags, action,
4163 flags, keyCode, incomingKey.getScanCode(), metaState,
4164 incomingKey.getRepeatCount(),
4165 incomingKey.getDownTime());
4166 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004171 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4172 int32_t action = motionEvent.getAction();
4173 size_t pointerCount = motionEvent.getPointerCount();
4174 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4175 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004176 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004177 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 }
4181
4182 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 android::base::Timer t;
4185 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4186 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4187 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4188 std::to_string(t.duration().count()).c_str());
4189 }
4190 }
4191
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004192 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4193 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4194 }
4195
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004197 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4198 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004199 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004200 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4201 resolvedDeviceId, motionEvent.getSource(),
4202 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004203 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004204 motionEvent.getButtonState(),
4205 motionEvent.getClassification(),
4206 motionEvent.getEdgeFlags(),
4207 motionEvent.getXPrecision(),
4208 motionEvent.getYPrecision(),
4209 motionEvent.getRawXCursorPosition(),
4210 motionEvent.getRawYCursorPosition(),
4211 motionEvent.getDownTime(), uint32_t(pointerCount),
4212 pointerProperties, samplePointerCoords,
4213 motionEvent.getXOffset(),
4214 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004215 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004216 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 sampleEventTimes += 1;
4218 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004219 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4221 resolvedDeviceId, motionEvent.getSource(),
4222 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004223 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 motionEvent.getMetaState(),
4225 motionEvent.getButtonState(),
4226 motionEvent.getClassification(),
4227 motionEvent.getEdgeFlags(),
4228 motionEvent.getXPrecision(),
4229 motionEvent.getYPrecision(),
4230 motionEvent.getRawXCursorPosition(),
4231 motionEvent.getRawYCursorPosition(),
4232 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 samplePointerCoords, motionEvent.getXOffset(),
4235 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 }
4238 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004242 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 }
4245
4246 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 injectionState->injectionIsAsync = true;
4249 }
4250
4251 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004252 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
4254 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004255 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004256 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004257 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
4260 mLock.unlock();
4261
4262 if (needWake) {
4263 mLooper->wake();
4264 }
4265
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004268 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 if (syncMode == InputEventInjectionSync::NONE) {
4271 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 } else {
4273 for (;;) {
4274 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004275 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 break;
4277 }
4278
4279 nsecs_t remainingTimeout = endTime - now();
4280 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004281 if (DEBUG_INJECTION) {
4282 ALOGD("injectInputEvent - Timed out waiting for injection result "
4283 "to become available.");
4284 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004285 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 break;
4287 }
4288
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004289 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4293 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004295 if (DEBUG_INJECTION) {
4296 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4297 injectionState->pendingForegroundDispatches);
4298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 nsecs_t remainingTimeout = endTime - now();
4300 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004301 if (DEBUG_INJECTION) {
4302 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4303 "dispatches to finish.");
4304 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 break;
4307 }
4308
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004309 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
4312 }
4313
4314 injectionState->release();
4315 } // release lock
4316
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 if (DEBUG_INJECTION) {
4318 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4319 injectionResult, injectorPid, injectorUid);
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
4322 return injectionResult;
4323}
4324
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004325std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004326 std::array<uint8_t, 32> calculatedHmac;
4327 std::unique_ptr<VerifiedInputEvent> result;
4328 switch (event.getType()) {
4329 case AINPUT_EVENT_TYPE_KEY: {
4330 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4331 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4332 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004333 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004334 break;
4335 }
4336 case AINPUT_EVENT_TYPE_MOTION: {
4337 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4338 VerifiedMotionEvent verifiedMotionEvent =
4339 verifiedMotionEventFromMotionEvent(motionEvent);
4340 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004341 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004342 break;
4343 }
4344 default: {
4345 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4346 return nullptr;
4347 }
4348 }
4349 if (calculatedHmac == INVALID_HMAC) {
4350 return nullptr;
4351 }
4352 if (calculatedHmac != event.getHmac()) {
4353 return nullptr;
4354 }
4355 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004356}
4357
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 return injectorUid == 0 ||
4360 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361}
4362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004363void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004367 if (DEBUG_INJECTION) {
4368 ALOGD("Setting input event injection result to %d. "
4369 "injectorPid=%d, injectorUid=%d",
4370 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 // Log the outcome since the injector did not wait for the injection result.
4375 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004376 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 ALOGV("Asynchronous input event injection succeeded.");
4378 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004379 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 ALOGW("Asynchronous input event injection failed.");
4381 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004382 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 ALOGW("Asynchronous input event injection permission denied.");
4384 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004386 ALOGW("Asynchronous input event injection timed out.");
4387 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 case InputEventInjectionResult::PENDING:
4389 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392 }
4393
4394 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004395 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397}
4398
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004399void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4400 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 if (injectionState) {
4402 injectionState->pendingForegroundDispatches += 1;
4403 }
4404}
4405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004406void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4407 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 if (injectionState) {
4409 injectionState->pendingForegroundDispatches -= 1;
4410
4411 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004412 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414 }
4415}
4416
chaviw98318de2021-05-19 16:45:23 -05004417const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004418 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004419 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004420 auto it = mWindowHandlesByDisplay.find(displayId);
4421 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004422}
4423
chaviw98318de2021-05-19 16:45:23 -05004424sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004425 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004426 if (windowHandleToken == nullptr) {
4427 return nullptr;
4428 }
4429
Arthur Hungb92218b2018-08-14 12:00:21 +08004430 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004431 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4432 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004433 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004434 return windowHandle;
4435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 }
4437 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004438 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439}
4440
chaviw98318de2021-05-19 16:45:23 -05004441sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4442 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004443 if (windowHandleToken == nullptr) {
4444 return nullptr;
4445 }
4446
chaviw98318de2021-05-19 16:45:23 -05004447 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004448 if (windowHandle->getToken() == windowHandleToken) {
4449 return windowHandle;
4450 }
4451 }
4452 return nullptr;
4453}
4454
chaviw98318de2021-05-19 16:45:23 -05004455sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4456 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004457 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004458 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4459 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004460 if (handle->getId() == windowHandle->getId() &&
4461 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004462 if (windowHandle->getInfo()->displayId != it.first) {
4463 ALOGE("Found window %s in display %" PRId32
4464 ", but it should belong to display %" PRId32,
4465 windowHandle->getName().c_str(), it.first,
4466 windowHandle->getInfo()->displayId);
4467 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004468 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 }
4471 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004472 return nullptr;
4473}
4474
chaviw98318de2021-05-19 16:45:23 -05004475sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004476 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4477 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478}
4479
chaviw98318de2021-05-19 16:45:23 -05004480bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004481 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4482 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004483 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004484 if (connection != nullptr && noInputChannel) {
4485 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4486 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4487 return false;
4488 }
4489
4490 if (connection == nullptr) {
4491 if (!noInputChannel) {
4492 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4493 }
4494 return false;
4495 }
4496 if (!connection->responsive) {
4497 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4498 return false;
4499 }
4500 return true;
4501}
4502
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004503std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4504 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004505 auto connectionIt = mConnectionsByToken.find(token);
4506 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004507 return nullptr;
4508 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004509 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004510}
4511
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004512void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004513 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4514 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004515 // Remove all handles on a display if there are no windows left.
4516 mWindowHandlesByDisplay.erase(displayId);
4517 return;
4518 }
4519
4520 // Since we compare the pointer of input window handles across window updates, we need
4521 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004522 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4523 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4524 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004525 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004526 }
4527
chaviw98318de2021-05-19 16:45:23 -05004528 std::vector<sp<WindowInfoHandle>> newHandles;
4529 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004530 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004531 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004532 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004533 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4534 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4535 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004536 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004537 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004538 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004539 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004540 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004541 }
4542
4543 if (info->displayId != displayId) {
4544 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4545 handle->getName().c_str(), displayId, info->displayId);
4546 continue;
4547 }
4548
Robert Carredd13602020-04-13 17:24:34 -07004549 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4550 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004551 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004552 oldHandle->updateFrom(handle);
4553 newHandles.push_back(oldHandle);
4554 } else {
4555 newHandles.push_back(handle);
4556 }
4557 }
4558
4559 // Insert or replace
4560 mWindowHandlesByDisplay[displayId] = newHandles;
4561}
4562
Arthur Hung72d8dc32020-03-28 00:48:39 +00004563void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004564 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004565 { // acquire lock
4566 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004567 for (const auto& [displayId, handles] : handlesPerDisplay) {
4568 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004569 }
4570 }
4571 // Wake up poll loop since it may need to make new input dispatching choices.
4572 mLooper->wake();
4573}
4574
Arthur Hungb92218b2018-08-14 12:00:21 +08004575/**
4576 * Called from InputManagerService, update window handle list by displayId that can receive input.
4577 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4578 * If set an empty list, remove all handles from the specific display.
4579 * For focused handle, check if need to change and send a cancel event to previous one.
4580 * For removed handle, check if need to send a cancel event if already in touch.
4581 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004582void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004583 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004584 if (DEBUG_FOCUS) {
4585 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004586 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004587 windowList += iwh->getName() + " ";
4588 }
4589 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004592 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004593 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004594 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004595 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004596 if (noInputWindow && window->getToken() != nullptr) {
4597 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4598 window->getName().c_str());
4599 window->releaseChannel();
4600 }
4601 }
4602
Arthur Hung72d8dc32020-03-28 00:48:39 +00004603 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004604 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004606 // Save the old windows' orientation by ID before it gets updated.
4607 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004608 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004609 oldWindowOrientations.emplace(handle->getId(),
4610 handle->getInfo()->transform.getOrientation());
4611 }
4612
chaviw98318de2021-05-19 16:45:23 -05004613 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004614
chaviw98318de2021-05-19 16:45:23 -05004615 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004616 if (mLastHoverWindowHandle &&
4617 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4618 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619 mLastHoverWindowHandle = nullptr;
4620 }
4621
Vishnu Nairc519ff72021-01-21 08:23:08 -08004622 std::optional<FocusResolver::FocusChanges> changes =
4623 mFocusResolver.setInputWindows(displayId, windowHandles);
4624 if (changes) {
4625 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004628 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4629 mTouchStatesByDisplay.find(displayId);
4630 if (stateIt != mTouchStatesByDisplay.end()) {
4631 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004632 for (size_t i = 0; i < state.windows.size();) {
4633 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004634 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004635 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004636 ALOGD("Touched window was removed: %s in display %" PRId32,
4637 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004638 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004639 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004640 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4641 if (touchedInputChannel != nullptr) {
4642 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4643 "touched window was removed");
4644 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004646 state.windows.erase(state.windows.begin() + i);
4647 } else {
4648 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 }
4650 }
arthurhungb89ccb02020-12-30 16:19:01 +08004651
arthurhung6d4bed92021-03-17 11:59:33 +08004652 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004653 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004654 if (mDragState &&
4655 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004656 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004657 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004658 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004659 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004660
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004661 if (isPerWindowInputRotationEnabled()) {
4662 // Determine if the orientation of any of the input windows have changed, and cancel all
4663 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004664 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4665 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004666 if (newWindowHandle != nullptr &&
4667 newWindowHandle->getInfo()->transform.getOrientation() !=
4668 oldWindowOrientations[oldWindowHandle->getId()]) {
4669 std::shared_ptr<InputChannel> inputChannel =
4670 getInputChannelLocked(newWindowHandle->getToken());
4671 if (inputChannel != nullptr) {
4672 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4673 "touched window's orientation changed");
4674 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4675 }
4676 }
4677 }
4678 }
4679
Arthur Hung72d8dc32020-03-28 00:48:39 +00004680 // Release information for windows that are no longer present.
4681 // This ensures that unused input channels are released promptly.
4682 // Otherwise, they might stick around until the window handle is destroyed
4683 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004684 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004685 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004686 if (DEBUG_FOCUS) {
4687 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004688 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004689 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004690 // To avoid making too many calls into the compat framework, only
4691 // check for window flags when windows are going away.
4692 // TODO(b/157929241) : delete this. This is only needed temporarily
4693 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004694 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004695 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4696 oldWindowHandle->getName().c_str());
4697 if (mCompatService != nullptr) {
4698 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4699 oldWindowHandle->getInfo()->ownerUid);
4700 }
4701 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004702 }
chaviw291d88a2019-02-14 10:33:58 -08004703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704}
4705
4706void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004707 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004708 if (DEBUG_FOCUS) {
4709 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4710 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4711 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004712 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004714 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 } // release lock
4716
4717 // Wake up poll loop since it may need to make new input dispatching choices.
4718 mLooper->wake();
4719}
4720
Vishnu Nair599f1412021-06-21 10:39:58 -07004721void InputDispatcher::setFocusedApplicationLocked(
4722 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4723 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4724 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4725
4726 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4727 return; // This application is already focused. No need to wake up or change anything.
4728 }
4729
4730 // Set the new application handle.
4731 if (inputApplicationHandle != nullptr) {
4732 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4733 } else {
4734 mFocusedApplicationHandlesByDisplay.erase(displayId);
4735 }
4736
4737 // No matter what the old focused application was, stop waiting on it because it is
4738 // no longer focused.
4739 resetNoFocusedWindowTimeoutLocked();
4740}
4741
Tiger Huang721e26f2018-07-24 22:26:19 +08004742/**
4743 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4744 * the display not specified.
4745 *
4746 * We track any unreleased events for each window. If a window loses the ability to receive the
4747 * released event, we will send a cancel event to it. So when the focused display is changed, we
4748 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4749 * display. The display-specified events won't be affected.
4750 */
4751void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004752 if (DEBUG_FOCUS) {
4753 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4754 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004755 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004756 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004757
4758 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004759 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004760 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004761 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004762 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004763 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004764 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004765 CancelationOptions
4766 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4767 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004768 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004769 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4770 }
4771 }
4772 mFocusedDisplayId = displayId;
4773
Chris Ye3c2d6f52020-08-09 10:39:48 -07004774 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004775 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004776 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004777
Vishnu Nairad321cd2020-08-20 16:40:21 -07004778 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004779 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004780 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004781 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004782 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004783 }
4784 }
4785 }
4786
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004787 if (DEBUG_FOCUS) {
4788 logDispatchStateLocked();
4789 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004790 } // release lock
4791
4792 // Wake up poll loop since it may need to make new input dispatching choices.
4793 mLooper->wake();
4794}
4795
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004797 if (DEBUG_FOCUS) {
4798 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
4801 bool changed;
4802 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004803 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804
4805 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4806 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809
4810 if (mDispatchEnabled && !enabled) {
4811 resetAndDropEverythingLocked("dispatcher is being disabled");
4812 }
4813
4814 mDispatchEnabled = enabled;
4815 mDispatchFrozen = frozen;
4816 changed = true;
4817 } else {
4818 changed = false;
4819 }
4820
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004821 if (DEBUG_FOCUS) {
4822 logDispatchStateLocked();
4823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 } // release lock
4825
4826 if (changed) {
4827 // Wake up poll loop since it may need to make new input dispatching choices.
4828 mLooper->wake();
4829 }
4830}
4831
4832void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004833 if (DEBUG_FOCUS) {
4834 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
4837 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004838 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839
4840 if (mInputFilterEnabled == enabled) {
4841 return;
4842 }
4843
4844 mInputFilterEnabled = enabled;
4845 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4846 } // release lock
4847
4848 // Wake up poll loop since there might be work to do to drop everything.
4849 mLooper->wake();
4850}
4851
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004852void InputDispatcher::setInTouchMode(bool inTouchMode) {
4853 std::scoped_lock lock(mLock);
4854 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004855 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004856}
4857
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004858void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4859 if (opacity < 0 || opacity > 1) {
4860 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4861 return;
4862 }
4863
4864 std::scoped_lock lock(mLock);
4865 mMaximumObscuringOpacityForTouch = opacity;
4866}
4867
4868void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4869 std::scoped_lock lock(mLock);
4870 mBlockUntrustedTouchesMode = mode;
4871}
4872
arthurhungb89ccb02020-12-30 16:19:01 +08004873bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4874 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004875 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004876 if (DEBUG_FOCUS) {
4877 ALOGD("Trivial transfer to same window.");
4878 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004879 return true;
4880 }
4881
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004883 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884
chaviw98318de2021-05-19 16:45:23 -05004885 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4886 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004887 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004888 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 return false;
4890 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004891 if (DEBUG_FOCUS) {
4892 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4893 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004896 if (DEBUG_FOCUS) {
4897 ALOGD("Cannot transfer focus because windows are on different displays.");
4898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 return false;
4900 }
4901
4902 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004903 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4904 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004905 for (size_t i = 0; i < state.windows.size(); i++) {
4906 const TouchedWindow& touchedWindow = state.windows[i];
4907 if (touchedWindow.windowHandle == fromWindowHandle) {
4908 int32_t oldTargetFlags = touchedWindow.targetFlags;
4909 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004911 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004913 int32_t newTargetFlags = oldTargetFlags &
4914 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4915 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004916 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917
arthurhungb89ccb02020-12-30 16:19:01 +08004918 // Store the dragging window.
4919 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004920 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004921 }
4922
Jeff Brownf086ddb2014-02-11 14:28:48 -08004923 found = true;
4924 goto Found;
4925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 }
4927 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004930 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004931 if (DEBUG_FOCUS) {
4932 ALOGD("Focus transfer failed because from window did not have focus.");
4933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 return false;
4935 }
4936
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004937 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4938 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004939 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004940 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004941 CancelationOptions
4942 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4943 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004945 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
4947
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004948 if (DEBUG_FOCUS) {
4949 logDispatchStateLocked();
4950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 } // release lock
4952
4953 // Wake up poll loop since it may need to make new input dispatching choices.
4954 mLooper->wake();
4955 return true;
4956}
4957
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004958// Binder call
4959bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4960 sp<IBinder> fromToken;
4961 { // acquire lock
4962 std::scoped_lock _l(mLock);
4963
chaviw98318de2021-05-19 16:45:23 -05004964 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004965 if (toWindowHandle == nullptr) {
4966 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4967 return false;
4968 }
4969
4970 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4971
4972 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4973 if (touchStateIt == mTouchStatesByDisplay.end()) {
4974 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4975 displayId);
4976 return false;
4977 }
4978
4979 TouchState& state = touchStateIt->second;
4980 if (state.windows.size() != 1) {
4981 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4982 state.windows.size());
4983 return false;
4984 }
4985 const TouchedWindow& touchedWindow = state.windows[0];
4986 fromToken = touchedWindow.windowHandle->getToken();
4987 } // release lock
4988
4989 return transferTouchFocus(fromToken, destChannelToken);
4990}
4991
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004993 if (DEBUG_FOCUS) {
4994 ALOGD("Resetting and dropping all events (%s).", reason);
4995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996
4997 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4998 synthesizeCancelationEventsForAllConnectionsLocked(options);
4999
5000 resetKeyRepeatLocked();
5001 releasePendingEventLocked();
5002 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005003 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005005 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005006 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005008 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009}
5010
5011void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005012 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 dumpDispatchStateLocked(dump);
5014
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005015 std::istringstream stream(dump);
5016 std::string line;
5017
5018 while (std::getline(stream, line, '\n')) {
5019 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 }
5021}
5022
Prabir Pradhan99987712020-11-10 18:43:05 -08005023std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5024 std::string dump;
5025
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005026 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5027 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005028
5029 std::string windowName = "None";
5030 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005031 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005032 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5033 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5034 : "token has capture without window";
5035 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005036 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005037
5038 return dump;
5039}
5040
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005041void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005042 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5043 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5044 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005045 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046
Tiger Huang721e26f2018-07-24 22:26:19 +08005047 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5048 dump += StringPrintf(INDENT "FocusedApplications:\n");
5049 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5050 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005051 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005052 const std::chrono::duration timeout =
5053 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005054 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005055 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005056 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005059 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005061
Vishnu Nairc519ff72021-01-21 08:23:08 -08005062 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005063 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005065 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005066 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005067 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5068 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005069 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005070 state.displayId, toString(state.down), toString(state.split),
5071 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005072 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005073 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005074 for (size_t i = 0; i < state.windows.size(); i++) {
5075 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005076 dump += StringPrintf(INDENT4
5077 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5078 i, touchedWindow.windowHandle->getName().c_str(),
5079 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005080 }
5081 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005082 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 }
5085 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005086 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 }
5088
arthurhung6d4bed92021-03-17 11:59:33 +08005089 if (mDragState) {
5090 dump += StringPrintf(INDENT "DragState:\n");
5091 mDragState->dump(dump, INDENT2);
5092 }
5093
Arthur Hungb92218b2018-08-14 12:00:21 +08005094 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005095 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005096 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005097 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005098 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005099 dump += INDENT2 "Windows:\n";
5100 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005101 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5102 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005104 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005105 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005106 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005107 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005108 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005109 "applicationInfo.name=%s, "
5110 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005111 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005112 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005113 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005114 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005115 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005116 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005117 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005118 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005119 windowInfo->frameLeft, windowInfo->frameTop,
5120 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005121 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005122 windowInfo->applicationInfo.name.c_str(),
5123 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005124 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005125 dump += StringPrintf(", inputFeatures=%s",
5126 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005127 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005128 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005129 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005130 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005131 millis(windowInfo->dispatchingTimeout),
5132 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005133 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005134 toString(windowInfo->touchOcclusionMode).c_str(),
5135 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005136 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005137 }
5138 } else {
5139 dump += INDENT2 "Windows: <none>\n";
5140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 }
5142 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005143 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 }
5145
Michael Wright3dd60e22019-03-27 22:06:44 +00005146 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005147 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005148 const std::vector<Monitor>& monitors = it.second;
5149 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5150 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005151 }
5152 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005153 const std::vector<Monitor>& monitors = it.second;
5154 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5155 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005158 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160
5161 nsecs_t currentTime = now();
5162
5163 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005164 if (!mRecentQueue.empty()) {
5165 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005166 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005167 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005168 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
5175 // Dump event currently being dispatched.
5176 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 dump += INDENT "PendingEvent:\n";
5178 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005179 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005180 dump += StringPrintf(", age=%" PRId64 "ms\n",
5181 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005183 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 }
5185
5186 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005187 if (!mInboundQueue.empty()) {
5188 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005189 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005190 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005191 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005192 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 }
5194 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005195 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 }
5197
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005198 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005199 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005200 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5201 const KeyReplacement& replacement = pair.first;
5202 int32_t newKeyCode = pair.second;
5203 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005204 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005205 }
5206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005207 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005208 }
5209
Prabir Pradhancef936d2021-07-21 16:17:52 +00005210 if (!mCommandQueue.empty()) {
5211 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5212 } else {
5213 dump += INDENT "CommandQueue: <empty>\n";
5214 }
5215
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005216 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005217 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005218 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005219 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005220 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005221 connection->inputChannel->getFd().get(),
5222 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005223 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005224 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005226 if (!connection->outboundQueue.empty()) {
5227 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5228 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005229 dump += dumpQueue(connection->outboundQueue, currentTime);
5230
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005232 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 }
5234
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005235 if (!connection->waitQueue.empty()) {
5236 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5237 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005238 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005240 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 }
5242 }
5243 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005244 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 }
5246
5247 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005248 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5249 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005251 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 }
5253
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005254 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005255 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5256 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5257 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005258 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005259 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260}
5261
Michael Wright3dd60e22019-03-27 22:06:44 +00005262void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5263 const size_t numMonitors = monitors.size();
5264 for (size_t i = 0; i < numMonitors; i++) {
5265 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005266 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005267 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5268 dump += "\n";
5269 }
5270}
5271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272class LooperEventCallback : public LooperCallback {
5273public:
5274 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5275 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5276
5277private:
5278 std::function<int(int events)> mCallback;
5279};
5280
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005281Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005282 if (DEBUG_CHANNEL_CREATION) {
5283 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005286 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005287 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005288 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005289
5290 if (result) {
5291 return base::Error(result) << "Failed to open input channel pair with name " << name;
5292 }
5293
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005295 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005296 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005297 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005298 sp<Connection> connection =
5299 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005301 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5302 ALOGE("Created a new connection, but the token %p is already known", token.get());
5303 }
5304 mConnectionsByToken.emplace(token, connection);
5305
5306 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5307 this, std::placeholders::_1, token);
5308
5309 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 } // release lock
5311
5312 // Wake the looper because some connections have changed.
5313 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005314 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315}
5316
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005317Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5318 bool isGestureMonitor,
5319 const std::string& name,
5320 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005321 std::shared_ptr<InputChannel> serverChannel;
5322 std::unique_ptr<InputChannel> clientChannel;
5323 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5324 if (result) {
5325 return base::Error(result) << "Failed to open input channel pair with name " << name;
5326 }
5327
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 { // acquire lock
5329 std::scoped_lock _l(mLock);
5330
5331 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005332 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5333 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005334 }
5335
Garfield Tan15601662020-09-22 15:32:38 -07005336 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005337 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005338 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005339
5340 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5341 ALOGE("Created a new connection, but the token %p is already known", token.get());
5342 }
5343 mConnectionsByToken.emplace(token, connection);
5344 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5345 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005347 auto& monitorsByDisplay =
5348 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005349 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005350
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005351 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005352 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5353 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005354 }
Garfield Tan15601662020-09-22 15:32:38 -07005355
Michael Wright3dd60e22019-03-27 22:06:44 +00005356 // Wake the looper because some connections have changed.
5357 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005358 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005359}
5360
Garfield Tan15601662020-09-22 15:32:38 -07005361status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005363 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364
Garfield Tan15601662020-09-22 15:32:38 -07005365 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366 if (status) {
5367 return status;
5368 }
5369 } // release lock
5370
5371 // Wake the poll loop because removing the connection may have changed the current
5372 // synchronization state.
5373 mLooper->wake();
5374 return OK;
5375}
5376
Garfield Tan15601662020-09-22 15:32:38 -07005377status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5378 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005379 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005380 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005381 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 return BAD_VALUE;
5383 }
5384
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005385 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005386
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005388 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 }
5390
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005391 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392
5393 nsecs_t currentTime = now();
5394 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5395
5396 connection->status = Connection::STATUS_ZOMBIE;
5397 return OK;
5398}
5399
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005400void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5401 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5402 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005403}
5404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005405void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005406 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005407 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005408 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005409 std::vector<Monitor>& monitors = it->second;
5410 const size_t numMonitors = monitors.size();
5411 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005412 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005413 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5414 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005415 monitors.erase(monitors.begin() + i);
5416 break;
5417 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005418 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005419 if (monitors.empty()) {
5420 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005421 } else {
5422 ++it;
5423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 }
5425}
5426
Michael Wright3dd60e22019-03-27 22:06:44 +00005427status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5428 { // acquire lock
5429 std::scoped_lock _l(mLock);
5430 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5431
5432 if (!foundDisplayId) {
5433 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5434 return BAD_VALUE;
5435 }
5436 int32_t displayId = foundDisplayId.value();
5437
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005438 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5439 mTouchStatesByDisplay.find(displayId);
5440 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005441 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5442 return BAD_VALUE;
5443 }
5444
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005445 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005446 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005447 std::optional<int32_t> foundDeviceId;
5448 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005449 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005450 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005451 foundDeviceId = state.deviceId;
5452 }
5453 }
5454 if (!foundDeviceId || !state.down) {
5455 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005456 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005457 return BAD_VALUE;
5458 }
5459 int32_t deviceId = foundDeviceId.value();
5460
5461 // Send cancel events to all the input channels we're stealing from.
5462 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005463 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005464 options.deviceId = deviceId;
5465 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005466 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005467 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005468 std::shared_ptr<InputChannel> channel =
5469 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005470 if (channel != nullptr) {
5471 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005472 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005473 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005474 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005475 canceledWindows += "]";
5476 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5477 canceledWindows.c_str());
5478
Michael Wright3dd60e22019-03-27 22:06:44 +00005479 // Then clear the current touch state so we stop dispatching to them as well.
5480 state.filterNonMonitors();
5481 }
5482 return OK;
5483}
5484
Prabir Pradhan99987712020-11-10 18:43:05 -08005485void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5486 { // acquire lock
5487 std::scoped_lock _l(mLock);
5488 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005489 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005490 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5491 windowHandle != nullptr ? windowHandle->getName().c_str()
5492 : "token without window");
5493 }
5494
Vishnu Nairc519ff72021-01-21 08:23:08 -08005495 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005496 if (focusedToken != windowToken) {
5497 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5498 enabled ? "enable" : "disable");
5499 return;
5500 }
5501
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005502 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005503 ALOGW("Ignoring request to %s Pointer Capture: "
5504 "window has %s requested pointer capture.",
5505 enabled ? "enable" : "disable", enabled ? "already" : "not");
5506 return;
5507 }
5508
Prabir Pradhan99987712020-11-10 18:43:05 -08005509 setPointerCaptureLocked(enabled);
5510 } // release lock
5511
5512 // Wake the thread to process command entries.
5513 mLooper->wake();
5514}
5515
Michael Wright3dd60e22019-03-27 22:06:44 +00005516std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5517 const sp<IBinder>& token) {
5518 for (const auto& it : mGestureMonitorsByDisplay) {
5519 const std::vector<Monitor>& monitors = it.second;
5520 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005521 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005522 return it.first;
5523 }
5524 }
5525 }
5526 return std::nullopt;
5527}
5528
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005529std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5530 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5531 if (gesturePid.has_value()) {
5532 return gesturePid;
5533 }
5534 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5535}
5536
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005537sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005538 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005539 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005540 }
5541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542 for (const auto& [token, connection] : mConnectionsByToken) {
5543 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005544 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 }
5546 }
Robert Carr4e670e52018-08-15 13:26:12 -07005547
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005548 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549}
5550
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005551std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5552 sp<Connection> connection = getConnectionLocked(connectionToken);
5553 if (connection == nullptr) {
5554 return "<nullptr>";
5555 }
5556 return connection->getInputChannelName();
5557}
5558
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005559void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005561 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005562}
5563
Prabir Pradhancef936d2021-07-21 16:17:52 +00005564void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5565 const sp<Connection>& connection, uint32_t seq,
5566 bool handled, nsecs_t consumeTime) {
5567 // Handle post-event policy actions.
5568 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5569 if (dispatchEntryIt == connection->waitQueue.end()) {
5570 return;
5571 }
5572 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5573 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5574 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5575 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5576 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5577 }
5578 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5579 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5580 connection->inputChannel->getConnectionToken(),
5581 dispatchEntry->deliveryTime, consumeTime, finishTime);
5582 }
5583
5584 bool restartEvent;
5585 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5586 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5587 restartEvent =
5588 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5589 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5590 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5591 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5592 handled);
5593 } else {
5594 restartEvent = false;
5595 }
5596
5597 // Dequeue the event and start the next cycle.
5598 // Because the lock might have been released, it is possible that the
5599 // contents of the wait queue to have been drained, so we need to double-check
5600 // a few things.
5601 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5602 if (dispatchEntryIt != connection->waitQueue.end()) {
5603 dispatchEntry = *dispatchEntryIt;
5604 connection->waitQueue.erase(dispatchEntryIt);
5605 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5606 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5607 if (!connection->responsive) {
5608 connection->responsive = isConnectionResponsive(*connection);
5609 if (connection->responsive) {
5610 // The connection was unresponsive, and now it's responsive.
5611 processConnectionResponsiveLocked(*connection);
5612 }
5613 }
5614 traceWaitQueueLength(*connection);
5615 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5616 connection->outboundQueue.push_front(dispatchEntry);
5617 traceOutboundQueueLength(*connection);
5618 } else {
5619 releaseDispatchEntry(dispatchEntry);
5620 }
5621 }
5622
5623 // Start the next dispatch cycle for this connection.
5624 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625}
5626
Prabir Pradhancef936d2021-07-21 16:17:52 +00005627void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5628 const sp<IBinder>& newToken) {
5629 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5630 scoped_unlock unlock(mLock);
5631 mPolicy->notifyFocusChanged(oldToken, newToken);
5632 };
5633 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634}
5635
Prabir Pradhancef936d2021-07-21 16:17:52 +00005636void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5637 auto command = [this, token, x, y]() REQUIRES(mLock) {
5638 scoped_unlock unlock(mLock);
5639 mPolicy->notifyDropWindow(token, x, y);
5640 };
5641 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005642}
5643
Prabir Pradhancef936d2021-07-21 16:17:52 +00005644void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5645 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5646 scoped_unlock unlock(mLock);
5647 mPolicy->notifyUntrustedTouch(obscuringPackage);
5648 };
5649 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005650}
5651
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005652void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5653 if (connection == nullptr) {
5654 LOG_ALWAYS_FATAL("Caller must check for nullness");
5655 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005656 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5657 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005658 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005659 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005660 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005661 return;
5662 }
5663 /**
5664 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5665 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5666 * has changed. This could cause newer entries to time out before the already dispatched
5667 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5668 * processes the events linearly. So providing information about the oldest entry seems to be
5669 * most useful.
5670 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005671 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5673 std::string reason =
5674 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005675 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005676 ns2ms(currentWait),
5677 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005678 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005679 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005680
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005681 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5682
5683 // Stop waking up for events on this connection, it is already unresponsive
5684 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005685}
5686
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005687void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5688 std::string reason =
5689 StringPrintf("%s does not have a focused window", application->getName().c_str());
5690 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005691
Prabir Pradhancef936d2021-07-21 16:17:52 +00005692 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5693 scoped_unlock unlock(mLock);
5694 mPolicy->notifyNoFocusedWindowAnr(application);
5695 };
5696 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005697}
5698
chaviw98318de2021-05-19 16:45:23 -05005699void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005700 const std::string& reason) {
5701 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5702 updateLastAnrStateLocked(windowLabel, reason);
5703}
5704
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005705void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5706 const std::string& reason) {
5707 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005708 updateLastAnrStateLocked(windowLabel, reason);
5709}
5710
5711void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5712 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005714 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 struct tm tm;
5716 localtime_r(&t, &tm);
5717 char timestr[64];
5718 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005719 mLastAnrState.clear();
5720 mLastAnrState += INDENT "ANR:\n";
5721 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5723 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005724 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725}
5726
Prabir Pradhancef936d2021-07-21 16:17:52 +00005727void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5728 KeyEntry& entry) {
5729 const KeyEvent event = createKeyEvent(entry);
5730 nsecs_t delay = 0;
5731 { // release lock
5732 scoped_unlock unlock(mLock);
5733 android::base::Timer t;
5734 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5735 entry.policyFlags);
5736 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5737 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5738 std::to_string(t.duration().count()).c_str());
5739 }
5740 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741
5742 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005743 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005744 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005745 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005747 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5748 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750}
5751
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005752void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005753 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5754 scoped_unlock unlock(mLock);
5755 mPolicy->notifyMonitorUnresponsive(pid, reason);
5756 };
5757 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005758}
5759
Prabir Pradhancef936d2021-07-21 16:17:52 +00005760void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005761 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005762 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5763 scoped_unlock unlock(mLock);
5764 mPolicy->notifyWindowUnresponsive(token, reason);
5765 };
5766 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005767}
5768
5769void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005770 auto command = [this, pid]() REQUIRES(mLock) {
5771 scoped_unlock unlock(mLock);
5772 mPolicy->notifyMonitorResponsive(pid);
5773 };
5774 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005775}
5776
Prabir Pradhancef936d2021-07-21 16:17:52 +00005777void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5778 auto command = [this, connectionToken]() REQUIRES(mLock) {
5779 scoped_unlock unlock(mLock);
5780 mPolicy->notifyWindowResponsive(connectionToken);
5781 };
5782 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005783}
5784
5785/**
5786 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5787 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5788 * command entry to the command queue.
5789 */
5790void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5791 std::string reason) {
5792 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5793 if (connection.monitor) {
5794 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5795 reason.c_str());
5796 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5797 if (!pid.has_value()) {
5798 ALOGE("Could not find unresponsive monitor for connection %s",
5799 connection.inputChannel->getName().c_str());
5800 return;
5801 }
5802 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5803 return;
5804 }
5805 // If not a monitor, must be a window
5806 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5807 reason.c_str());
5808 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5809}
5810
5811/**
5812 * Tell the policy that a connection has become responsive so that it can stop ANR.
5813 */
5814void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5815 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5816 if (connection.monitor) {
5817 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5818 if (!pid.has_value()) {
5819 ALOGE("Could not find responsive monitor for connection %s",
5820 connection.inputChannel->getName().c_str());
5821 return;
5822 }
5823 sendMonitorResponsiveCommandLocked(pid.value());
5824 return;
5825 }
5826 // If not a monitor, must be a window
5827 sendWindowResponsiveCommandLocked(connectionToken);
5828}
5829
Prabir Pradhancef936d2021-07-21 16:17:52 +00005830bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005831 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005832 KeyEntry& keyEntry, bool handled) {
5833 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005834 if (!handled) {
5835 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005836 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005837 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005838 return false;
5839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005841 // Get the fallback key state.
5842 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005843 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005844 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005845 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005846 connection->inputState.removeFallbackKey(originalKeyCode);
5847 }
5848
5849 if (handled || !dispatchEntry->hasForegroundTarget()) {
5850 // If the application handles the original key for which we previously
5851 // generated a fallback or if the window is not a foreground window,
5852 // then cancel the associated fallback key, if any.
5853 if (fallbackKeyCode != -1) {
5854 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005855 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5856 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5857 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5858 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5859 keyEntry.policyFlags);
5860 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005861 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005862 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863
5864 mLock.unlock();
5865
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005866 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005867 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868
5869 mLock.lock();
5870
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005871 // Cancel the fallback key.
5872 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005874 "application handled the original non-fallback key "
5875 "or is no longer a foreground target, "
5876 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 options.keyCode = fallbackKeyCode;
5878 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 connection->inputState.removeFallbackKey(originalKeyCode);
5881 }
5882 } else {
5883 // If the application did not handle a non-fallback key, first check
5884 // that we are in a good state to perform unhandled key event processing
5885 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005887 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005888 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5889 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5890 "since this is not an initial down. "
5891 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5892 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5893 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005894 return false;
5895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005898 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5899 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5900 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5901 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5902 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005903 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005904
5905 mLock.unlock();
5906
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005907 bool fallback =
5908 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005909 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005910
5911 mLock.lock();
5912
5913 if (connection->status != Connection::STATUS_NORMAL) {
5914 connection->inputState.removeFallbackKey(originalKeyCode);
5915 return false;
5916 }
5917
5918 // Latch the fallback keycode for this key on an initial down.
5919 // The fallback keycode cannot change at any other point in the lifecycle.
5920 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922 fallbackKeyCode = event.getKeyCode();
5923 } else {
5924 fallbackKeyCode = AKEYCODE_UNKNOWN;
5925 }
5926 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5927 }
5928
5929 ALOG_ASSERT(fallbackKeyCode != -1);
5930
5931 // Cancel the fallback key if the policy decides not to send it anymore.
5932 // We will continue to dispatch the key to the policy but we will no
5933 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005934 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5935 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005936 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5937 if (fallback) {
5938 ALOGD("Unhandled key event: Policy requested to send key %d"
5939 "as a fallback for %d, but on the DOWN it had requested "
5940 "to send %d instead. Fallback canceled.",
5941 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5942 } else {
5943 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5944 "but on the DOWN it had requested to send %d. "
5945 "Fallback canceled.",
5946 originalKeyCode, fallbackKeyCode);
5947 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005949
5950 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5951 "canceling fallback, policy no longer desires it");
5952 options.keyCode = fallbackKeyCode;
5953 synthesizeCancelationEventsForConnectionLocked(connection, options);
5954
5955 fallback = false;
5956 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005958 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 }
5960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005962 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5963 {
5964 std::string msg;
5965 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5966 connection->inputState.getFallbackKeys();
5967 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5968 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5969 }
5970 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5971 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005974
5975 if (fallback) {
5976 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005977 keyEntry.eventTime = event.getEventTime();
5978 keyEntry.deviceId = event.getDeviceId();
5979 keyEntry.source = event.getSource();
5980 keyEntry.displayId = event.getDisplayId();
5981 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5982 keyEntry.keyCode = fallbackKeyCode;
5983 keyEntry.scanCode = event.getScanCode();
5984 keyEntry.metaState = event.getMetaState();
5985 keyEntry.repeatCount = event.getRepeatCount();
5986 keyEntry.downTime = event.getDownTime();
5987 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005989 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5990 ALOGD("Unhandled key event: Dispatching fallback key. "
5991 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5992 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
5993 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005994 return true; // restart the event
5995 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005996 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5997 ALOGD("Unhandled key event: No fallback key.");
5998 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005999
6000 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006001 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002 }
6003 }
6004 return false;
6005}
6006
Prabir Pradhancef936d2021-07-21 16:17:52 +00006007bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006008 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006009 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 return false;
6011}
6012
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013void InputDispatcher::traceInboundQueueLengthLocked() {
6014 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006015 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 }
6017}
6018
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006019void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 if (ATRACE_ENABLED()) {
6021 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006022 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6023 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 }
6025}
6026
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006027void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 if (ATRACE_ENABLED()) {
6029 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006030 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6031 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 }
6033}
6034
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006035void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006036 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006038 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 dumpDispatchStateLocked(dump);
6040
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006041 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006042 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006043 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 }
6045}
6046
6047void InputDispatcher::monitor() {
6048 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006049 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006051 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052}
6053
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006054/**
6055 * Wake up the dispatcher and wait until it processes all events and commands.
6056 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6057 * this method can be safely called from any thread, as long as you've ensured that
6058 * the work you are interested in completing has already been queued.
6059 */
6060bool InputDispatcher::waitForIdle() {
6061 /**
6062 * Timeout should represent the longest possible time that a device might spend processing
6063 * events and commands.
6064 */
6065 constexpr std::chrono::duration TIMEOUT = 100ms;
6066 std::unique_lock lock(mLock);
6067 mLooper->wake();
6068 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6069 return result == std::cv_status::no_timeout;
6070}
6071
Vishnu Naire798b472020-07-23 13:52:21 -07006072/**
6073 * Sets focus to the window identified by the token. This must be called
6074 * after updating any input window handles.
6075 *
6076 * Params:
6077 * request.token - input channel token used to identify the window that should gain focus.
6078 * request.focusedToken - the token that the caller expects currently to be focused. If the
6079 * specified token does not match the currently focused window, this request will be dropped.
6080 * If the specified focused token matches the currently focused window, the call will succeed.
6081 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6082 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6083 * when requesting the focus change. This determines which request gets
6084 * precedence if there is a focus change request from another source such as pointer down.
6085 */
Vishnu Nair958da932020-08-21 17:12:37 -07006086void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6087 { // acquire lock
6088 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006089 std::optional<FocusResolver::FocusChanges> changes =
6090 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6091 if (changes) {
6092 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006093 }
6094 } // release lock
6095 // Wake up poll loop since it may need to make new input dispatching choices.
6096 mLooper->wake();
6097}
6098
Vishnu Nairc519ff72021-01-21 08:23:08 -08006099void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6100 if (changes.oldFocus) {
6101 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006102 if (focusedInputChannel) {
6103 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6104 "focus left window");
6105 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006106 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006107 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006108 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006109 if (changes.newFocus) {
6110 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006111 }
6112
Prabir Pradhan99987712020-11-10 18:43:05 -08006113 // If a window has pointer capture, then it must have focus. We need to ensure that this
6114 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6115 // If the window loses focus before it loses pointer capture, then the window can be in a state
6116 // where it has pointer capture but not focus, violating the contract. Therefore we must
6117 // dispatch the pointer capture event before the focus event. Since focus events are added to
6118 // the front of the queue (above), we add the pointer capture event to the front of the queue
6119 // after the focus events are added. This ensures the pointer capture event ends up at the
6120 // front.
6121 disablePointerCaptureForcedLocked();
6122
Vishnu Nairc519ff72021-01-21 08:23:08 -08006123 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006124 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006125 }
6126}
Vishnu Nair958da932020-08-21 17:12:37 -07006127
Prabir Pradhan99987712020-11-10 18:43:05 -08006128void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006129 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006130 return;
6131 }
6132
6133 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6134
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006135 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006136 setPointerCaptureLocked(false);
6137 }
6138
6139 if (!mWindowTokenWithPointerCapture) {
6140 // No need to send capture changes because no window has capture.
6141 return;
6142 }
6143
6144 if (mPendingEvent != nullptr) {
6145 // Move the pending event to the front of the queue. This will give the chance
6146 // for the pending event to be dropped if it is a captured event.
6147 mInboundQueue.push_front(mPendingEvent);
6148 mPendingEvent = nullptr;
6149 }
6150
6151 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006152 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006153 mInboundQueue.push_front(std::move(entry));
6154}
6155
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006156void InputDispatcher::setPointerCaptureLocked(bool enable) {
6157 mCurrentPointerCaptureRequest.enable = enable;
6158 mCurrentPointerCaptureRequest.seq++;
6159 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006161 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006162 };
6163 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006164}
6165
Vishnu Nair599f1412021-06-21 10:39:58 -07006166void InputDispatcher::displayRemoved(int32_t displayId) {
6167 { // acquire lock
6168 std::scoped_lock _l(mLock);
6169 // Set an empty list to remove all handles from the specific display.
6170 setInputWindowsLocked(/* window handles */ {}, displayId);
6171 setFocusedApplicationLocked(displayId, nullptr);
6172 // Call focus resolver to clean up stale requests. This must be called after input windows
6173 // have been removed for the removed display.
6174 mFocusResolver.displayRemoved(displayId);
6175 } // release lock
6176
6177 // Wake up poll loop since it may need to make new input dispatching choices.
6178 mLooper->wake();
6179}
6180
chaviw15fab6f2021-06-07 14:15:52 -05006181void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6182 // The listener sends the windows as a flattened array. Separate the windows by display for
6183 // more convenient parsing.
6184 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6185
6186 for (const auto& info : windowInfos) {
6187 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6188 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6189 }
6190 setInputWindows(handlesPerDisplay);
6191}
6192
Garfield Tane84e6f92019-08-29 17:28:41 -07006193} // namespace android::inputdispatcher