blob: 0d0d1c44f72f6bc54b50750ce30017eae2df9d2c [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
Vishnu Nair062a8672021-09-03 16:07:44 -07001871 // Drop key events if requested by input feature
1872 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1873 return InputEventInjectionResult::FAILED;
1874 }
1875
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001876 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1877 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1878 // start interacting with another application via touch (app switch). This code can be removed
1879 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1880 // an app is expected to have a focused window.
1881 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1882 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1883 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001884 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1885 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1886 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001888 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889 ALOGW("Waiting because no window has focus but %s may eventually add a "
1890 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001891 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1895 // Already raised ANR. Drop the event
1896 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001897 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001898 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899 } else {
1900 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001901 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 }
1903 }
1904
1905 // we have a valid, non-null focused window
1906 resetNoFocusedWindowTimeoutLocked();
1907
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001909 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 if (focusedWindowHandle->getInfo()->paused) {
1914 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001915 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001916 }
1917
1918 // If the event is a key event, then we must wait for all previous events to
1919 // complete before delivering it because previous events may have the
1920 // side-effect of transferring focus to a different window and we want to
1921 // ensure that the following keys are sent to the new window.
1922 //
1923 // Suppose the user touches a button in a window then immediately presses "A".
1924 // If the button causes a pop-up window to appear then we want to ensure that
1925 // the "A" key is delivered to the new pop-up window. This is because users
1926 // often anticipate pending UI changes when typing on a keyboard.
1927 // To obtain this behavior, we must serialize key events with respect to all
1928 // prior input events.
1929 if (entry.type == EventEntry::Type::KEY) {
1930 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1931 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 }
1935
1936 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001937 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001938 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1939 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940
1941 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943}
1944
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001945/**
1946 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1947 * that are currently unresponsive.
1948 */
1949std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1950 const std::vector<TouchedMonitor>& monitors) const {
1951 std::vector<TouchedMonitor> responsiveMonitors;
1952 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1953 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1954 sp<Connection> connection = getConnectionLocked(
1955 monitor.monitor.inputChannel->getConnectionToken());
1956 if (connection == nullptr) {
1957 ALOGE("Could not find connection for monitor %s",
1958 monitor.monitor.inputChannel->getName().c_str());
1959 return false;
1960 }
1961 if (!connection->responsive) {
1962 ALOGW("Unresponsive monitor %s will not get the new gesture",
1963 connection->inputChannel->getName().c_str());
1964 return false;
1965 }
1966 return true;
1967 });
1968 return responsiveMonitors;
1969}
1970
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001971InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1972 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1973 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001974 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 enum InjectionPermission {
1976 INJECTION_PERMISSION_UNKNOWN,
1977 INJECTION_PERMISSION_GRANTED,
1978 INJECTION_PERMISSION_DENIED
1979 };
1980
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 // For security reasons, we defer updating the touch state until we are sure that
1982 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001983 int32_t displayId = entry.displayId;
1984 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1986
1987 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001988 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001990 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1991 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001993 // Copy current touch state into tempTouchState.
1994 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1995 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001996 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001998 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1999 mTouchStatesByDisplay.find(displayId);
2000 if (oldStateIt != mTouchStatesByDisplay.end()) {
2001 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002002 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002003 }
2004
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002005 bool isSplit = tempTouchState.split;
2006 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2007 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2008 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002009 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2010 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2011 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2012 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2013 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002014 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 bool wrongDevice = false;
2016 if (newGesture) {
2017 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002018 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002019 ALOGI("Dropping event because a pointer for a different device is already down "
2020 "in display %" PRId32,
2021 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002022 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002023 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 switchedDevice = false;
2025 wrongDevice = true;
2026 goto Failed;
2027 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002028 tempTouchState.reset();
2029 tempTouchState.down = down;
2030 tempTouchState.deviceId = entry.deviceId;
2031 tempTouchState.source = entry.source;
2032 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002034 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002035 ALOGI("Dropping move event because a pointer for a different device is already active "
2036 "in display %" PRId32,
2037 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002038 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002039 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002040 switchedDevice = false;
2041 wrongDevice = true;
2042 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044
2045 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2046 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2047
Garfield Tan00f511d2019-06-12 16:55:40 -07002048 int32_t x;
2049 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002051 // Always dispatch mouse events to cursor position.
2052 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002053 x = int32_t(entry.xCursorPosition);
2054 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002055 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002056 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2057 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002058 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002060 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2061 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002062
2063 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002064 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00002065 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 if (newTouchedWindowHandle != nullptr &&
2069 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002070 // New window supports splitting, but we should never split mouse events.
2071 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 } else if (isSplit) {
2073 // New window does not support splitting but we have already split events.
2074 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002075 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077
2078 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002079 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002081 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002082 }
2083
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002084 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2085 ALOGI("Not sending touch event to %s because it is paused",
2086 newTouchedWindowHandle->getName().c_str());
2087 newTouchedWindowHandle = nullptr;
2088 }
2089
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002090 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002092 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2093 if (!isResponsive) {
2094 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2096 newTouchedWindowHandle = nullptr;
2097 }
2098 }
2099
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002100 // Drop events that can't be trusted due to occlusion
2101 if (newTouchedWindowHandle != nullptr &&
2102 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2103 TouchOcclusionInfo occlusionInfo =
2104 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002105 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002106 if (DEBUG_TOUCH_OCCLUSION) {
2107 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2108 for (const auto& log : occlusionInfo.debugInfo) {
2109 ALOGD("%s", log.c_str());
2110 }
2111 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002112 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002113 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2114 ALOGW("Dropping untrusted touch event due to %s/%d",
2115 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2116 newTouchedWindowHandle = nullptr;
2117 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002118 }
2119 }
2120
Vishnu Nair062a8672021-09-03 16:07:44 -07002121 // Drop touch events if requested by input feature
2122 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2123 newTouchedWindowHandle = nullptr;
2124 }
2125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002126 // Also don't send the new touch event to unresponsive gesture monitors
2127 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2128
Michael Wright3dd60e22019-03-27 22:06:44 +00002129 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2130 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 "(%d, %d) in display %" PRId32 ".",
2132 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002133 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002134 goto Failed;
2135 }
2136
2137 if (newTouchedWindowHandle != nullptr) {
2138 // Set target flags.
2139 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2140 if (isSplit) {
2141 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2144 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2145 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2146 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2147 }
2148
2149 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002150 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2151 newHoverWindowHandle = nullptr;
2152 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002153 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002154 }
2155
2156 // Update the temporary touch state.
2157 BitSet32 pointerIds;
2158 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002160 pointerIds.markBit(pointerId);
2161 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002162 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
2164
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002165 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 } else {
2167 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2168
2169 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002170 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002171 if (DEBUG_FOCUS) {
2172 ALOGD("Dropping event because the pointer is not down or we previously "
2173 "dropped the pointer down event in display %" PRId32,
2174 displayId);
2175 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002176 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 goto Failed;
2178 }
2179
arthurhung6d4bed92021-03-17 11:59:33 +08002180 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002181
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002183 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002184 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002185 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2186 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187
chaviw98318de2021-05-19 16:45:23 -05002188 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002190 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002191
2192 // Drop touch events if requested by input feature
2193 if (newTouchedWindowHandle != nullptr &&
2194 shouldDropInput(entry, newTouchedWindowHandle)) {
2195 newTouchedWindowHandle = nullptr;
2196 }
2197
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2199 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002200 if (DEBUG_FOCUS) {
2201 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2202 oldTouchedWindowHandle->getName().c_str(),
2203 newTouchedWindowHandle->getName().c_str(), displayId);
2204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002206 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2207 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2208 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209
2210 // Make a slippery entrance into the new window.
2211 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2212 isSplit = true;
2213 }
2214
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002215 int32_t targetFlags =
2216 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 if (isSplit) {
2218 targetFlags |= InputTarget::FLAG_SPLIT;
2219 }
2220 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2221 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002222 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2223 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
2225
2226 BitSet32 pointerIds;
2227 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002228 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002230 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
2232 }
2233 }
2234
2235 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002236 // Let the previous window know that the hover sequence is over, unless we already did it
2237 // when dispatching it as is to newTouchedWindowHandle.
2238 if (mLastHoverWindowHandle != nullptr &&
2239 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2240 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002241 if (DEBUG_HOVER) {
2242 ALOGD("Sending hover exit event to window %s.",
2243 mLastHoverWindowHandle->getName().c_str());
2244 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002245 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2246 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 }
2248
Garfield Tandf26e862020-07-01 20:18:19 -07002249 // Let the new window know that the hover sequence is starting, unless we already did it
2250 // when dispatching it as is to newTouchedWindowHandle.
2251 if (newHoverWindowHandle != nullptr &&
2252 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2253 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002254 if (DEBUG_HOVER) {
2255 ALOGD("Sending hover enter event to window %s.",
2256 newHoverWindowHandle->getName().c_str());
2257 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002258 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2259 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2260 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
2262 }
2263
2264 // Check permission to inject into all touched foreground windows and ensure there
2265 // is at least one touched foreground window.
2266 {
2267 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002268 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2270 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002271 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002272 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 injectionPermission = INJECTION_PERMISSION_DENIED;
2274 goto Failed;
2275 }
2276 }
2277 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002280 ALOGI("Dropping event because there is no touched foreground window in display "
2281 "%" PRId32 " or gesture monitor to receive it.",
2282 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002283 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 goto Failed;
2285 }
2286
2287 // Permission granted to injection into all touched foreground windows.
2288 injectionPermission = INJECTION_PERMISSION_GRANTED;
2289 }
2290
2291 // Check whether windows listening for outside touches are owned by the same UID. If it is
2292 // set the policy flag that we will not reveal coordinate information to this window.
2293 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002294 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002295 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002296 if (foregroundWindowHandle) {
2297 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002298 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002299 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002300 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2301 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2302 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 InputTarget::FLAG_ZERO_COORDS,
2304 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307 }
2308 }
2309 }
2310
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 // If this is the first pointer going down and the touched window has a wallpaper
2312 // then also add the touched wallpaper windows so they are locked in for the duration
2313 // of the touch gesture.
2314 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2315 // engine only supports touch events. We would need to add a mechanism similar
2316 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2317 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002318 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002319 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002320 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002321 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002322 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002323 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2324 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002326 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002327 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 .addOrUpdateWindow(windowHandle,
2329 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2330 InputTarget::
2331 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2332 InputTarget::FLAG_DISPATCH_AS_IS,
2333 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
2335 }
2336 }
2337 }
2338
2339 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002340 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002342 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 }
2346
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002347 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002348 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002350 }
2351
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 // Drop the outside or hover touch windows since we will not care about them
2353 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002354 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355
2356Failed:
2357 // Check injection permission once and for all.
2358 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002359 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 injectionPermission = INJECTION_PERMISSION_GRANTED;
2361 } else {
2362 injectionPermission = INJECTION_PERMISSION_DENIED;
2363 }
2364 }
2365
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2367 return injectionResult;
2368 }
2369
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 if (!wrongDevice) {
2372 if (switchedDevice) {
2373 if (DEBUG_FOCUS) {
2374 ALOGD("Conflicting pointer actions: Switched to a different device.");
2375 }
2376 *outConflictingPointerActions = true;
2377 }
2378
2379 if (isHoverAction) {
2380 // Started hovering, therefore no longer down.
2381 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002382 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002383 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2384 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 *outConflictingPointerActions = true;
2387 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002388 tempTouchState.reset();
2389 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2390 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2391 tempTouchState.deviceId = entry.deviceId;
2392 tempTouchState.source = entry.source;
2393 tempTouchState.displayId = displayId;
2394 }
2395 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2396 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2397 // All pointers up or canceled.
2398 tempTouchState.reset();
2399 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2400 // First pointer went down.
2401 if (oldState && oldState->down) {
2402 if (DEBUG_FOCUS) {
2403 ALOGD("Conflicting pointer actions: Down received while already down.");
2404 }
2405 *outConflictingPointerActions = true;
2406 }
2407 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2408 // One pointer went up.
2409 if (isSplit) {
2410 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2411 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002413 for (size_t i = 0; i < tempTouchState.windows.size();) {
2414 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2415 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2416 touchedWindow.pointerIds.clearBit(pointerId);
2417 if (touchedWindow.pointerIds.isEmpty()) {
2418 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2419 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002422 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002424 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002425 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002426
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002427 // Save changes unless the action was scroll in which case the temporary touch
2428 // state was only valid for this one action.
2429 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2430 if (tempTouchState.displayId >= 0) {
2431 mTouchStatesByDisplay[displayId] = tempTouchState;
2432 } else {
2433 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002437 // Update hover state.
2438 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 return injectionResult;
2442}
2443
arthurhung6d4bed92021-03-17 11:59:33 +08002444void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002445 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002446 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002447 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002448 if (dropWindow) {
2449 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002450 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002451 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002452 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002453 }
2454 mDragState.reset();
2455}
2456
2457void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2458 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002459 return;
2460 }
2461
arthurhung6d4bed92021-03-17 11:59:33 +08002462 if (!mDragState->isStartDrag) {
2463 mDragState->isStartDrag = true;
2464 mDragState->isStylusButtonDownAtStart =
2465 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2466 }
2467
arthurhungb89ccb02020-12-30 16:19:01 +08002468 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2469 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2470 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2471 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002472 // Handle the special case : stylus button no longer pressed.
2473 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2474 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2475 finishDragAndDrop(entry.displayId, x, y);
2476 return;
2477 }
2478
chaviw98318de2021-05-19 16:45:23 -05002479 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002480 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002481 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002482 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002483 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2484 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2485 if (mDragState->dragHoverWindowHandle != nullptr) {
2486 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2487 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002488 }
arthurhung6d4bed92021-03-17 11:59:33 +08002489 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002490 }
2491 // enqueue drag location if needed.
2492 if (hoverWindowHandle != nullptr) {
2493 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2494 }
arthurhung6d4bed92021-03-17 11:59:33 +08002495 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2496 finishDragAndDrop(entry.displayId, x, y);
2497 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002498 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002499 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002500 }
2501}
2502
chaviw98318de2021-05-19 16:45:23 -05002503void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 int32_t targetFlags, BitSet32 pointerIds,
2505 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002506 std::vector<InputTarget>::iterator it =
2507 std::find_if(inputTargets.begin(), inputTargets.end(),
2508 [&windowHandle](const InputTarget& inputTarget) {
2509 return inputTarget.inputChannel->getConnectionToken() ==
2510 windowHandle->getToken();
2511 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002512
chaviw98318de2021-05-19 16:45:23 -05002513 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002514
2515 if (it == inputTargets.end()) {
2516 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002517 std::shared_ptr<InputChannel> inputChannel =
2518 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002519 if (inputChannel == nullptr) {
2520 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2521 return;
2522 }
2523 inputTarget.inputChannel = inputChannel;
2524 inputTarget.flags = targetFlags;
2525 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002526 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002527 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002528 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002529 inputTargets.push_back(inputTarget);
2530 it = inputTargets.end() - 1;
2531 }
2532
2533 ALOG_ASSERT(it->flags == targetFlags);
2534 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2535
chaviw1ff3d1e2020-07-01 15:53:47 -07002536 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537}
2538
Michael Wright3dd60e22019-03-27 22:06:44 +00002539void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 int32_t displayId, float xOffset,
2541 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002542 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2543 mGlobalMonitorsByDisplay.find(displayId);
2544
2545 if (it != mGlobalMonitorsByDisplay.end()) {
2546 const std::vector<Monitor>& monitors = it->second;
2547 for (const Monitor& monitor : monitors) {
2548 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 }
2551}
2552
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2554 float yOffset,
2555 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002556 InputTarget target;
2557 target.inputChannel = monitor.inputChannel;
2558 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002559 ui::Transform t;
2560 t.set(xOffset, yOffset);
2561 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002562 inputTargets.push_back(target);
2563}
2564
chaviw98318de2021-05-19 16:45:23 -05002565bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 const InjectionState* injectionState) {
2567 if (injectionState &&
2568 (windowHandle == nullptr ||
2569 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2570 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002571 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 "owned by uid %d",
2574 injectionState->injectorPid, injectionState->injectorUid,
2575 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 } else {
2577 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 }
2580 return false;
2581 }
2582 return true;
2583}
2584
Robert Carrc9bf1d32020-04-13 17:21:08 -07002585/**
2586 * Indicate whether one window handle should be considered as obscuring
2587 * another window handle. We only check a few preconditions. Actually
2588 * checking the bounds is left to the caller.
2589 */
chaviw98318de2021-05-19 16:45:23 -05002590static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2591 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002592 // Compare by token so cloned layers aren't counted
2593 if (haveSameToken(windowHandle, otherHandle)) {
2594 return false;
2595 }
2596 auto info = windowHandle->getInfo();
2597 auto otherInfo = otherHandle->getInfo();
2598 if (!otherInfo->visible) {
2599 return false;
chaviw98318de2021-05-19 16:45:23 -05002600 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002601 // Those act as if they were invisible, so we don't need to flag them.
2602 // We do want to potentially flag touchable windows even if they have 0
2603 // opacity, since they can consume touches and alter the effects of the
2604 // user interaction (eg. apps that rely on
2605 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2606 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2607 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002608 } else if (info->ownerUid == otherInfo->ownerUid) {
2609 // If ownerUid is the same we don't generate occlusion events as there
2610 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002611 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002612 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002613 return false;
2614 } else if (otherInfo->displayId != info->displayId) {
2615 return false;
2616 }
2617 return true;
2618}
2619
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002620/**
2621 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2622 * untrusted, one should check:
2623 *
2624 * 1. If result.hasBlockingOcclusion is true.
2625 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2626 * BLOCK_UNTRUSTED.
2627 *
2628 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2629 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2630 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2631 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2632 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2633 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2634 *
2635 * If neither of those is true, then it means the touch can be allowed.
2636 */
2637InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002638 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2639 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002640 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002641 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002642 TouchOcclusionInfo info;
2643 info.hasBlockingOcclusion = false;
2644 info.obscuringOpacity = 0;
2645 info.obscuringUid = -1;
2646 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002647 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002648 if (windowHandle == otherHandle) {
2649 break; // All future windows are below us. Exit early.
2650 }
chaviw98318de2021-05-19 16:45:23 -05002651 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002652 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2653 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002654 if (DEBUG_TOUCH_OCCLUSION) {
2655 info.debugInfo.push_back(
2656 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2657 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002658 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2659 // we perform the checks below to see if the touch can be propagated or not based on the
2660 // window's touch occlusion mode
2661 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2662 info.hasBlockingOcclusion = true;
2663 info.obscuringUid = otherInfo->ownerUid;
2664 info.obscuringPackage = otherInfo->packageName;
2665 break;
2666 }
2667 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2668 uint32_t uid = otherInfo->ownerUid;
2669 float opacity =
2670 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2671 // Given windows A and B:
2672 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2673 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2674 opacityByUid[uid] = opacity;
2675 if (opacity > info.obscuringOpacity) {
2676 info.obscuringOpacity = opacity;
2677 info.obscuringUid = uid;
2678 info.obscuringPackage = otherInfo->packageName;
2679 }
2680 }
2681 }
2682 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002683 if (DEBUG_TOUCH_OCCLUSION) {
2684 info.debugInfo.push_back(
2685 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2686 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002687 return info;
2688}
2689
chaviw98318de2021-05-19 16:45:23 -05002690std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002691 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002692 return StringPrintf(INDENT2
2693 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2694 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2695 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2696 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002697 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002698 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002699 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2700 info->frameTop, info->frameRight, info->frameBottom,
2701 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002702 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2703 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2704 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002705}
2706
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002707bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2708 if (occlusionInfo.hasBlockingOcclusion) {
2709 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2710 occlusionInfo.obscuringUid);
2711 return false;
2712 }
2713 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2714 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2715 "%.2f, maximum allowed = %.2f)",
2716 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2717 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2718 return false;
2719 }
2720 return true;
2721}
2722
chaviw98318de2021-05-19 16:45:23 -05002723bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002726 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
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 Wrightd02c5b62014-02-10 15:10:22 -08002730 }
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->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 return true;
2735 }
2736 }
2737 return false;
2738}
2739
chaviw98318de2021-05-19 16:45:23 -05002740bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002741 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002742 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2743 const WindowInfo* windowInfo = windowHandle->getInfo();
2744 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002745 if (windowHandle == otherHandle) {
2746 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002747 }
chaviw98318de2021-05-19 16:45:23 -05002748 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002749 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002750 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002751 return true;
2752 }
2753 }
2754 return false;
2755}
2756
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002757std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002758 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002759 if (applicationHandle != nullptr) {
2760 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002761 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 } else {
2763 return applicationHandle->getName();
2764 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002765 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002766 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002768 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 }
2770}
2771
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002772void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002773 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002774 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2775 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002776 // Focus or pointer capture changed events are passed to apps, but do not represent user
2777 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002778 return;
2779 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002780 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002781 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002782 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002783 const WindowInfo* info = focusedWindowHandle->getInfo();
2784 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002785 if (DEBUG_DISPATCH_CYCLE) {
2786 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 return;
2789 }
2790 }
2791
2792 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002793 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002794 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002795 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2796 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002797 return;
2798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002800 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 eventType = USER_ACTIVITY_EVENT_TOUCH;
2802 }
2803 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002805 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002806 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2807 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 return;
2809 }
2810 eventType = USER_ACTIVITY_EVENT_BUTTON;
2811 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07002813 case EventEntry::Type::TOUCH_MODE_CHANGED: {
2814 break;
2815 }
2816
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002817 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002818 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002819 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002820 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002821 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2822 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002823 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002824 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002825 break;
2826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 }
2828
Prabir Pradhancef936d2021-07-21 16:17:52 +00002829 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2830 REQUIRES(mLock) {
2831 scoped_unlock unlock(mLock);
2832 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2833 };
2834 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835}
2836
2837void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002839 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002840 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002841 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002843 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002844 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002845 ATRACE_NAME(message.c_str());
2846 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002847 if (DEBUG_DISPATCH_CYCLE) {
2848 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2849 "globalScaleFactor=%f, pointerIds=0x%x %s",
2850 connection->getInputChannelName().c_str(), inputTarget.flags,
2851 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2852 inputTarget.getPointerInfoString().c_str());
2853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854
2855 // Skip this event if the connection status is not normal.
2856 // We don't want to enqueue additional outbound events if the connection is broken.
2857 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002858 if (DEBUG_DISPATCH_CYCLE) {
2859 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2860 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 return;
2863 }
2864
2865 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002866 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2867 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2868 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002869 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002871 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002872 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002873 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002874 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 if (!splitMotionEntry) {
2876 return; // split event was dropped
2877 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002878 if (DEBUG_FOCUS) {
2879 ALOGD("channel '%s' ~ Split motion event.",
2880 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002881 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002882 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002883 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2884 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 return;
2886 }
2887 }
2888
2889 // Not splitting. Enqueue dispatch entries for the event as is.
2890 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2891}
2892
2893void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002895 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002896 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002897 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002899 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002900 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002901 ATRACE_NAME(message.c_str());
2902 }
2903
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002904 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905
2906 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002907 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002908 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002909 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002911 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002913 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002915 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002917 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
2920 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002921 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 startDispatchCycleLocked(currentTime, connection);
2923 }
2924}
2925
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002927 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002928 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002930 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2932 connection->getInputChannelName().c_str(),
2933 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002934 ATRACE_NAME(message.c_str());
2935 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002936 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 if (!(inputTargetFlags & dispatchMode)) {
2938 return;
2939 }
2940 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2941
2942 // This is a new event.
2943 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002944 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002945 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002947 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2948 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002949 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002951 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002952 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002954 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002955 dispatchEntry->resolvedAction = keyEntry.action;
2956 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2959 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002960 if (DEBUG_DISPATCH_CYCLE) {
2961 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2962 "event",
2963 connection->getInputChannelName().c_str());
2964 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 return; // skip the inconsistent event
2966 }
2967 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002970 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002971 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002972 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2973 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2974 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2975 static_cast<int32_t>(IdGenerator::Source::OTHER);
2976 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2978 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2979 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2980 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2981 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2982 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2983 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2984 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2985 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2986 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2987 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002988 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002989 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002990 }
2991 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002992 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2993 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002994 if (DEBUG_DISPATCH_CYCLE) {
2995 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2996 "enter event",
2997 connection->getInputChannelName().c_str());
2998 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002999 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3000 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003004 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3006 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3007 }
3008 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3009 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3013 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003014 if (DEBUG_DISPATCH_CYCLE) {
3015 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3016 "event",
3017 connection->getInputChannelName().c_str());
3018 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003019 return; // skip the inconsistent event
3020 }
3021
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003022 dispatchEntry->resolvedEventId =
3023 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3024 ? mIdGenerator.nextId()
3025 : motionEntry.id;
3026 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3027 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3028 ") to MotionEvent(id=0x%" PRIx32 ").",
3029 motionEntry.id, dispatchEntry->resolvedEventId);
3030 ATRACE_NAME(message.c_str());
3031 }
3032
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003033 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3034 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3035 // Skip reporting pointer down outside focus to the policy.
3036 break;
3037 }
3038
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003040 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041
3042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003044 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003045 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003046 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3047 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003048 break;
3049 }
Chris Yef59a2f42020-10-16 12:55:26 -07003050 case EventEntry::Type::SENSOR: {
3051 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3052 break;
3053 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003054 case EventEntry::Type::CONFIGURATION_CHANGED:
3055 case EventEntry::Type::DEVICE_RESET: {
3056 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003057 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003058 break;
3059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060 }
3061
3062 // Remember that we are waiting for this dispatch to complete.
3063 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003064 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
3066
3067 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003068 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003069 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003070}
3071
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003072/**
3073 * This function is purely for debugging. It helps us understand where the user interaction
3074 * was taking place. For example, if user is touching launcher, we will see a log that user
3075 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3076 * We will see both launcher and wallpaper in that list.
3077 * Once the interaction with a particular set of connections starts, no new logs will be printed
3078 * until the set of interacted connections changes.
3079 *
3080 * The following items are skipped, to reduce the logspam:
3081 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3082 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3083 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3084 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3085 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003086 */
3087void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3088 const std::vector<InputTarget>& targets) {
3089 // Skip ACTION_UP events, and all events other than keys and motions
3090 if (entry.type == EventEntry::Type::KEY) {
3091 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3092 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3093 return;
3094 }
3095 } else if (entry.type == EventEntry::Type::MOTION) {
3096 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3097 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3098 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3099 return;
3100 }
3101 } else {
3102 return; // Not a key or a motion
3103 }
3104
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003105 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003106 std::vector<sp<Connection>> newConnections;
3107 for (const InputTarget& target : targets) {
3108 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3109 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3110 continue; // Skip windows that receive ACTION_OUTSIDE
3111 }
3112
3113 sp<IBinder> token = target.inputChannel->getConnectionToken();
3114 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003115 if (connection == nullptr) {
3116 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003117 }
3118 newConnectionTokens.insert(std::move(token));
3119 newConnections.emplace_back(connection);
3120 }
3121 if (newConnectionTokens == mInteractionConnectionTokens) {
3122 return; // no change
3123 }
3124 mInteractionConnectionTokens = newConnectionTokens;
3125
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003126 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003127 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003128 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003129 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003130 std::string message = "Interaction with: " + targetList;
3131 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003132 message += "<none>";
3133 }
3134 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3135}
3136
chaviwfd6d3512019-03-25 13:23:49 -07003137void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003138 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003139 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003140 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3141 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003142 return;
3143 }
3144
Vishnu Nairc519ff72021-01-21 08:23:08 -08003145 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003146 if (focusedToken == token) {
3147 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003148 return;
3149 }
3150
Prabir Pradhancef936d2021-07-21 16:17:52 +00003151 auto command = [this, token]() REQUIRES(mLock) {
3152 scoped_unlock unlock(mLock);
3153 mPolicy->onPointerDownOutsideFocus(token);
3154 };
3155 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156}
3157
3158void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003160 if (ATRACE_ENABLED()) {
3161 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003163 ATRACE_NAME(message.c_str());
3164 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003165 if (DEBUG_DISPATCH_CYCLE) {
3166 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003169 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3170 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003172 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003173 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003174 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175
3176 // Publish the event.
3177 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003178 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3179 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003180 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3182 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 status = connection->inputPublisher
3186 .publishKeyEvent(dispatchEntry->seq,
3187 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3188 keyEntry.source, keyEntry.displayId,
3189 std::move(hmac), dispatchEntry->resolvedAction,
3190 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3191 keyEntry.scanCode, keyEntry.metaState,
3192 keyEntry.repeatCount, keyEntry.downTime,
3193 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 }
3196
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003197 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003198 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003201 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202
chaviw82357092020-01-28 13:13:06 -08003203 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3206 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003207 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003208 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3209 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003210 // Don't apply window scale here since we don't want scale to affect raw
3211 // coordinates. The scale will be sent back to the client and applied
3212 // later when requesting relative coordinates.
3213 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3214 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 }
3216 usingCoords = scaledCoords;
3217 }
3218 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 // We don't want the dispatch target to know.
3220 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003221 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 scaledCoords[i].clear();
3223 }
3224 usingCoords = scaledCoords;
3225 }
3226 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003228 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229
3230 // Publish the motion event.
3231 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003232 .publishMotionEvent(dispatchEntry->seq,
3233 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 motionEntry.deviceId, motionEntry.source,
3235 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 motionEntry.edgeFlags, motionEntry.metaState,
3240 motionEntry.buttonState,
3241 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003242 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003243 motionEntry.xPrecision, motionEntry.yPrecision,
3244 motionEntry.xCursorPosition,
3245 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003246 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003247 dispatchEntry->displaySize.x,
3248 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003249 motionEntry.downTime, motionEntry.eventTime,
3250 motionEntry.pointerCount,
3251 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 break;
3253 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003254
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003255 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003257 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003258 focusEntry.id,
3259 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003260 mInTouchMode);
3261 break;
3262 }
3263
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003264 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3265 const TouchModeEntry& touchModeEntry =
3266 static_cast<const TouchModeEntry&>(eventEntry);
3267 status = connection->inputPublisher
3268 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3269 touchModeEntry.inTouchMode);
3270
3271 break;
3272 }
3273
Prabir Pradhan99987712020-11-10 18:43:05 -08003274 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3275 const auto& captureEntry =
3276 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3277 status = connection->inputPublisher
3278 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003279 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003280 break;
3281 }
3282
arthurhungb89ccb02020-12-30 16:19:01 +08003283 case EventEntry::Type::DRAG: {
3284 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3285 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3286 dragEntry.id, dragEntry.x,
3287 dragEntry.y,
3288 dragEntry.isExiting);
3289 break;
3290 }
3291
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003292 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003293 case EventEntry::Type::DEVICE_RESET:
3294 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003295 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003296 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
3300
3301 // Check the result.
3302 if (status) {
3303 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003304 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 "This is unexpected because the wait queue is empty, so the pipe "
3307 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003308 "event to it, status=%s(%d)",
3309 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3310 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3312 } else {
3313 // Pipe is full and we are waiting for the app to finish process some events
3314 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003315 if (DEBUG_DISPATCH_CYCLE) {
3316 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3317 "waiting for the application to catch up",
3318 connection->getInputChannelName().c_str());
3319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
3321 } else {
3322 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003323 "status=%s(%d)",
3324 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3325 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3327 }
3328 return;
3329 }
3330
3331 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003332 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3333 connection->outboundQueue.end(),
3334 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003335 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003336 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003337 if (connection->responsive) {
3338 mAnrTracker.insert(dispatchEntry->timeoutTime,
3339 connection->inputChannel->getConnectionToken());
3340 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003341 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343}
3344
chaviw09c8d2d2020-08-24 15:48:26 -07003345std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3346 size_t size;
3347 switch (event.type) {
3348 case VerifiedInputEvent::Type::KEY: {
3349 size = sizeof(VerifiedKeyEvent);
3350 break;
3351 }
3352 case VerifiedInputEvent::Type::MOTION: {
3353 size = sizeof(VerifiedMotionEvent);
3354 break;
3355 }
3356 }
3357 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3358 return mHmacKeyManager.sign(start, size);
3359}
3360
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003361const std::array<uint8_t, 32> InputDispatcher::getSignature(
3362 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3363 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3364 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3365 // Only sign events up and down events as the purely move events
3366 // are tied to their up/down counterparts so signing would be redundant.
3367 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3368 verifiedEvent.actionMasked = actionMasked;
3369 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003370 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003371 }
3372 return INVALID_HMAC;
3373}
3374
3375const std::array<uint8_t, 32> InputDispatcher::getSignature(
3376 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3377 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3378 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3379 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003380 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003381}
3382
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003385 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003386 if (DEBUG_DISPATCH_CYCLE) {
3387 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3388 connection->getInputChannelName().c_str(), seq, toString(handled));
3389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391 if (connection->status == Connection::STATUS_BROKEN ||
3392 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 return;
3394 }
3395
3396 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003397 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3398 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3399 };
3400 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401}
3402
3403void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 const sp<Connection>& connection,
3405 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003406 if (DEBUG_DISPATCH_CYCLE) {
3407 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3408 connection->getInputChannelName().c_str(), toString(notify));
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410
3411 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003412 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003413 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003414 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003415 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
3417 // The connection appears to be unrecoverably broken.
3418 // Ignore already broken or zombie connections.
3419 if (connection->status == Connection::STATUS_NORMAL) {
3420 connection->status = Connection::STATUS_BROKEN;
3421
3422 if (notify) {
3423 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003424 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3425 connection->getInputChannelName().c_str());
3426
3427 auto command = [this, connection]() REQUIRES(mLock) {
3428 if (connection->status == Connection::STATUS_ZOMBIE) return;
3429 scoped_unlock unlock(mLock);
3430 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3431 };
3432 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 }
3434 }
3435}
3436
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003437void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3438 while (!queue.empty()) {
3439 DispatchEntry* dispatchEntry = queue.front();
3440 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003441 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 }
3443}
3444
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003445void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003447 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449 delete dispatchEntry;
3450}
3451
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003452int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3453 std::scoped_lock _l(mLock);
3454 sp<Connection> connection = getConnectionLocked(connectionToken);
3455 if (connection == nullptr) {
3456 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3457 connectionToken.get(), events);
3458 return 0; // remove the callback
3459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003461 bool notify;
3462 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3463 if (!(events & ALOOPER_EVENT_INPUT)) {
3464 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3465 "events=0x%x",
3466 connection->getInputChannelName().c_str(), events);
3467 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
3469
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003470 nsecs_t currentTime = now();
3471 bool gotOne = false;
3472 status_t status = OK;
3473 for (;;) {
3474 Result<InputPublisher::ConsumerResponse> result =
3475 connection->inputPublisher.receiveConsumerResponse();
3476 if (!result.ok()) {
3477 status = result.error().code();
3478 break;
3479 }
3480
3481 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3482 const InputPublisher::Finished& finish =
3483 std::get<InputPublisher::Finished>(*result);
3484 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3485 finish.consumeTime);
3486 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003487 if (shouldReportMetricsForConnection(*connection)) {
3488 const InputPublisher::Timeline& timeline =
3489 std::get<InputPublisher::Timeline>(*result);
3490 mLatencyTracker
3491 .trackGraphicsLatency(timeline.inputEventId,
3492 connection->inputChannel->getConnectionToken(),
3493 std::move(timeline.graphicsTimeline));
3494 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003495 }
3496 gotOne = true;
3497 }
3498 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003499 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003500 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 return 1;
3502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 }
3504
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003505 notify = status != DEAD_OBJECT || !connection->monitor;
3506 if (notify) {
3507 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3508 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3509 status);
3510 }
3511 } else {
3512 // Monitor channels are never explicitly unregistered.
3513 // We do it automatically when the remote endpoint is closed so don't warn about them.
3514 const bool stillHaveWindowHandle =
3515 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3516 notify = !connection->monitor && stillHaveWindowHandle;
3517 if (notify) {
3518 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3519 connection->getInputChannelName().c_str(), events);
3520 }
3521 }
3522
3523 // Remove the channel.
3524 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3525 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526}
3527
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003528void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003530 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003531 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533}
3534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003535void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003536 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003537 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3538 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3539}
3540
3541void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3542 const CancelationOptions& options,
3543 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3544 for (const auto& it : monitorsByDisplay) {
3545 const std::vector<Monitor>& monitors = it.second;
3546 for (const Monitor& monitor : monitors) {
3547 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003548 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003549 }
3550}
3551
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003553 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003554 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003555 if (connection == nullptr) {
3556 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003558
3559 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560}
3561
3562void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3563 const sp<Connection>& connection, const CancelationOptions& options) {
3564 if (connection->status == Connection::STATUS_BROKEN) {
3565 return;
3566 }
3567
3568 nsecs_t currentTime = now();
3569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003570 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003571 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003573 if (cancelationEvents.empty()) {
3574 return;
3575 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003576 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3577 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3578 "with reality: %s, mode=%d.",
3579 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3580 options.mode);
3581 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582
3583 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003584 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003585 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3586 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003587 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003588 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003589 target.globalScaleFactor = windowInfo->globalScaleFactor;
3590 }
3591 target.inputChannel = connection->inputChannel;
3592 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3593
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003594 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003596 switch (cancelationEventEntry->type) {
3597 case EventEntry::Type::KEY: {
3598 logOutboundKeyDetails("cancel - ",
3599 static_cast<const KeyEntry&>(*cancelationEventEntry));
3600 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003602 case EventEntry::Type::MOTION: {
3603 logOutboundMotionDetails("cancel - ",
3604 static_cast<const MotionEntry&>(*cancelationEventEntry));
3605 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003607 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003608 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003609 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3610 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003611 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003612 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003613 break;
3614 }
3615 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003616 case EventEntry::Type::DEVICE_RESET:
3617 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003618 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003619 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003620 break;
3621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003624 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3625 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003627
3628 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629}
3630
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3632 const sp<Connection>& connection) {
3633 if (connection->status == Connection::STATUS_BROKEN) {
3634 return;
3635 }
3636
3637 nsecs_t currentTime = now();
3638
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003639 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003640 connection->inputState.synthesizePointerDownEvents(currentTime);
3641
3642 if (downEvents.empty()) {
3643 return;
3644 }
3645
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003646 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003647 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3648 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003649 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003650
3651 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003652 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003653 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3654 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003655 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003656 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003657 target.globalScaleFactor = windowInfo->globalScaleFactor;
3658 }
3659 target.inputChannel = connection->inputChannel;
3660 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3661
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003663 switch (downEventEntry->type) {
3664 case EventEntry::Type::MOTION: {
3665 logOutboundMotionDetails("down - ",
3666 static_cast<const MotionEntry&>(*downEventEntry));
3667 break;
3668 }
3669
3670 case EventEntry::Type::KEY:
3671 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003672 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003673 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003674 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003675 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003676 case EventEntry::Type::SENSOR:
3677 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003678 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003679 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003680 break;
3681 }
3682 }
3683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3685 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003686 }
3687
3688 startDispatchCycleLocked(currentTime, connection);
3689}
3690
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003691std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3692 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 ALOG_ASSERT(pointerIds.value != 0);
3694
3695 uint32_t splitPointerIndexMap[MAX_POINTERS];
3696 PointerProperties splitPointerProperties[MAX_POINTERS];
3697 PointerCoords splitPointerCoords[MAX_POINTERS];
3698
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003699 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 uint32_t splitPointerCount = 0;
3701
3702 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003703 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003705 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 uint32_t pointerId = uint32_t(pointerProperties.id);
3707 if (pointerIds.hasBit(pointerId)) {
3708 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3709 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3710 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003711 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 splitPointerCount += 1;
3713 }
3714 }
3715
3716 if (splitPointerCount != pointerIds.count()) {
3717 // This is bad. We are missing some of the pointers that we expected to deliver.
3718 // Most likely this indicates that we received an ACTION_MOVE events that has
3719 // different pointer ids than we expected based on the previous ACTION_DOWN
3720 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3721 // in this way.
3722 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 "we expected there to be %d pointers. This probably means we received "
3724 "a broken sequence of pointer ids from the input device.",
3725 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003726 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 }
3728
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003729 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003731 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3732 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3734 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003735 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 uint32_t pointerId = uint32_t(pointerProperties.id);
3737 if (pointerIds.hasBit(pointerId)) {
3738 if (pointerIds.count() == 1) {
3739 // The first/last pointer went down/up.
3740 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003742 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3743 ? AMOTION_EVENT_ACTION_CANCEL
3744 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 } else {
3746 // A secondary pointer went down/up.
3747 uint32_t splitPointerIndex = 0;
3748 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3749 splitPointerIndex += 1;
3750 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003751 action = maskedAction |
3752 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
3754 } else {
3755 // An unrelated pointer changed.
3756 action = AMOTION_EVENT_ACTION_MOVE;
3757 }
3758 }
3759
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003760 int32_t newId = mIdGenerator.nextId();
3761 if (ATRACE_ENABLED()) {
3762 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3763 ") to MotionEvent(id=0x%" PRIx32 ").",
3764 originalMotionEntry.id, newId);
3765 ATRACE_NAME(message.c_str());
3766 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003767 std::unique_ptr<MotionEntry> splitMotionEntry =
3768 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3769 originalMotionEntry.deviceId, originalMotionEntry.source,
3770 originalMotionEntry.displayId,
3771 originalMotionEntry.policyFlags, action,
3772 originalMotionEntry.actionButton,
3773 originalMotionEntry.flags, originalMotionEntry.metaState,
3774 originalMotionEntry.buttonState,
3775 originalMotionEntry.classification,
3776 originalMotionEntry.edgeFlags,
3777 originalMotionEntry.xPrecision,
3778 originalMotionEntry.yPrecision,
3779 originalMotionEntry.xCursorPosition,
3780 originalMotionEntry.yCursorPosition,
3781 originalMotionEntry.downTime, splitPointerCount,
3782 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003784 if (originalMotionEntry.injectionState) {
3785 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 splitMotionEntry->injectionState->refCount += 1;
3787 }
3788
3789 return splitMotionEntry;
3790}
3791
3792void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003793 if (DEBUG_INBOUND_EVENT_DETAILS) {
3794 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
3797 bool needWake;
3798 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003799 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003801 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3802 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3803 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 } // release lock
3805
3806 if (needWake) {
3807 mLooper->wake();
3808 }
3809}
3810
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003811/**
3812 * If one of the meta shortcuts is detected, process them here:
3813 * Meta + Backspace -> generate BACK
3814 * Meta + Enter -> generate HOME
3815 * This will potentially overwrite keyCode and metaState.
3816 */
3817void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003819 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3820 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3821 if (keyCode == AKEYCODE_DEL) {
3822 newKeyCode = AKEYCODE_BACK;
3823 } else if (keyCode == AKEYCODE_ENTER) {
3824 newKeyCode = AKEYCODE_HOME;
3825 }
3826 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003827 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003828 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003829 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003830 keyCode = newKeyCode;
3831 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3832 }
3833 } else if (action == AKEY_EVENT_ACTION_UP) {
3834 // In order to maintain a consistent stream of up and down events, check to see if the key
3835 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3836 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003837 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003838 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003839 auto replacementIt = mReplacedKeys.find(replacement);
3840 if (replacementIt != mReplacedKeys.end()) {
3841 keyCode = replacementIt->second;
3842 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003843 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3844 }
3845 }
3846}
3847
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003849 if (DEBUG_INBOUND_EVENT_DETAILS) {
3850 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3851 "policyFlags=0x%x, action=0x%x, "
3852 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3853 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3854 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3855 args->downTime);
3856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 if (!validateKeyEvent(args->action)) {
3858 return;
3859 }
3860
3861 uint32_t policyFlags = args->policyFlags;
3862 int32_t flags = args->flags;
3863 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003864 // InputDispatcher tracks and generates key repeats on behalf of
3865 // whatever notifies it, so repeatCount should always be set to 0
3866 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3868 policyFlags |= POLICY_FLAG_VIRTUAL;
3869 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 if (policyFlags & POLICY_FLAG_FUNCTION) {
3872 metaState |= AMETA_FUNCTION_ON;
3873 }
3874
3875 policyFlags |= POLICY_FLAG_TRUSTED;
3876
Michael Wright78f24442014-08-06 15:55:28 -07003877 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003878 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003879
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003881 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003882 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3883 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
Michael Wright2b3c3302018-03-02 17:19:13 +00003885 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003887 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3888 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003889 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892 bool needWake;
3893 { // acquire lock
3894 mLock.lock();
3895
3896 if (shouldSendKeyToInputFilterLocked(args)) {
3897 mLock.unlock();
3898
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003899 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3901 return; // event was consumed by the filter
3902 }
3903
3904 mLock.lock();
3905 }
3906
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003907 std::unique_ptr<KeyEntry> newEntry =
3908 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3909 args->displayId, policyFlags, args->action, flags,
3910 keyCode, args->scanCode, metaState, repeatCount,
3911 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003913 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 mLock.unlock();
3915 } // release lock
3916
3917 if (needWake) {
3918 mLooper->wake();
3919 }
3920}
3921
3922bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3923 return mInputFilterEnabled;
3924}
3925
3926void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003927 if (DEBUG_INBOUND_EVENT_DETAILS) {
3928 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3929 "displayId=%" PRId32 ", policyFlags=0x%x, "
3930 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3931 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3932 "yCursorPosition=%f, downTime=%" PRId64,
3933 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3934 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3935 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3936 args->xCursorPosition, args->yCursorPosition, args->downTime);
3937 for (uint32_t i = 0; i < args->pointerCount; i++) {
3938 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3939 "x=%f, y=%f, pressure=%f, size=%f, "
3940 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3941 "orientation=%f",
3942 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3943 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3944 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3945 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3946 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3948 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3949 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3950 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3951 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003954 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3955 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 return;
3957 }
3958
3959 uint32_t policyFlags = args->policyFlags;
3960 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003961
3962 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003963 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003964 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3965 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003966 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
3969 bool needWake;
3970 { // acquire lock
3971 mLock.lock();
3972
3973 if (shouldSendMotionToInputFilterLocked(args)) {
3974 mLock.unlock();
3975
3976 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003977 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003978 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3979 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003980 args->metaState, args->buttonState, args->classification, transform,
3981 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003982 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3983 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3984 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 policyFlags |= POLICY_FLAG_FILTERED;
3987 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3988 return; // event was consumed by the filter
3989 }
3990
3991 mLock.lock();
3992 }
3993
3994 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003995 std::unique_ptr<MotionEntry> newEntry =
3996 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3997 args->source, args->displayId, policyFlags,
3998 args->action, args->actionButton, args->flags,
3999 args->metaState, args->buttonState,
4000 args->classification, args->edgeFlags,
4001 args->xPrecision, args->yPrecision,
4002 args->xCursorPosition, args->yCursorPosition,
4003 args->downTime, args->pointerCount,
4004 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004006 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4007 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4008 !mInputFilterEnabled) {
4009 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4010 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4011 }
4012
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004013 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 mLock.unlock();
4015 } // release lock
4016
4017 if (needWake) {
4018 mLooper->wake();
4019 }
4020}
4021
Chris Yef59a2f42020-10-16 12:55:26 -07004022void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 if (DEBUG_INBOUND_EVENT_DETAILS) {
4024 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4025 " sensorType=%s",
4026 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004027 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 }
Chris Yef59a2f42020-10-16 12:55:26 -07004029
4030 bool needWake;
4031 { // acquire lock
4032 mLock.lock();
4033
4034 // Just enqueue a new sensor event.
4035 std::unique_ptr<SensorEntry> newEntry =
4036 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4037 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4038 args->sensorType, args->accuracy,
4039 args->accuracyChanged, args->values);
4040
4041 needWake = enqueueInboundEventLocked(std::move(newEntry));
4042 mLock.unlock();
4043 } // release lock
4044
4045 if (needWake) {
4046 mLooper->wake();
4047 }
4048}
4049
Chris Yefb552902021-02-03 17:18:37 -08004050void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004051 if (DEBUG_INBOUND_EVENT_DETAILS) {
4052 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4053 args->deviceId, args->isOn);
4054 }
Chris Yefb552902021-02-03 17:18:37 -08004055 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4056}
4057
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004059 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060}
4061
4062void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004063 if (DEBUG_INBOUND_EVENT_DETAILS) {
4064 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4065 "switchMask=0x%08x",
4066 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068
4069 uint32_t policyFlags = args->policyFlags;
4070 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072}
4073
4074void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004075 if (DEBUG_INBOUND_EVENT_DETAILS) {
4076 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4077 args->deviceId);
4078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
4080 bool needWake;
4081 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004082 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084 std::unique_ptr<DeviceResetEntry> newEntry =
4085 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4086 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 } // release lock
4088
4089 if (needWake) {
4090 mLooper->wake();
4091 }
4092}
4093
Prabir Pradhan7e186182020-11-10 13:56:45 -08004094void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004095 if (DEBUG_INBOUND_EVENT_DETAILS) {
4096 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004097 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004098 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004099
Prabir Pradhan99987712020-11-10 18:43:05 -08004100 bool needWake;
4101 { // acquire lock
4102 std::scoped_lock _l(mLock);
4103 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004104 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004105 needWake = enqueueInboundEventLocked(std::move(entry));
4106 } // release lock
4107
4108 if (needWake) {
4109 mLooper->wake();
4110 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004111}
4112
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004113InputEventInjectionResult InputDispatcher::injectInputEvent(
4114 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4115 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004116 if (DEBUG_INBOUND_EVENT_DETAILS) {
4117 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4118 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4119 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4120 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004121 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
4123 policyFlags |= POLICY_FLAG_INJECTED;
4124 if (hasInjectionPermission(injectorPid, injectorUid)) {
4125 policyFlags |= POLICY_FLAG_TRUSTED;
4126 }
4127
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004128 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004129 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4130 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4131 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4132 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4133 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004134 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004135 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004136 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 }
4138
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004139 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004142 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4143 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004148 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004149 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4150 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4151 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004152 int32_t keyCode = incomingKey.getKeyCode();
4153 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004154 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004156 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004157 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004158 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4159 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4160 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4163 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165
4166 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4167 android::base::Timer t;
4168 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4169 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4170 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4171 std::to_string(t.duration().count()).c_str());
4172 }
4173 }
4174
4175 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004176 std::unique_ptr<KeyEntry> injectedEntry =
4177 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 incomingKey.getDisplayId(), policyFlags, action,
4180 flags, keyCode, incomingKey.getScanCode(), metaState,
4181 incomingKey.getRepeatCount(),
4182 incomingKey.getDownTime());
4183 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
4186
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004188 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4189 int32_t action = motionEvent.getAction();
4190 size_t pointerCount = motionEvent.getPointerCount();
4191 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4192 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004193 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004194 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 }
4198
4199 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004200 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 android::base::Timer t;
4202 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4203 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4204 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4205 std::to_string(t.duration().count()).c_str());
4206 }
4207 }
4208
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004209 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4210 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4211 }
4212
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004214 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4215 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004216 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004217 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4218 resolvedDeviceId, motionEvent.getSource(),
4219 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004220 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004221 motionEvent.getButtonState(),
4222 motionEvent.getClassification(),
4223 motionEvent.getEdgeFlags(),
4224 motionEvent.getXPrecision(),
4225 motionEvent.getYPrecision(),
4226 motionEvent.getRawXCursorPosition(),
4227 motionEvent.getRawYCursorPosition(),
4228 motionEvent.getDownTime(), uint32_t(pointerCount),
4229 pointerProperties, samplePointerCoords,
4230 motionEvent.getXOffset(),
4231 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004232 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004234 sampleEventTimes += 1;
4235 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4238 resolvedDeviceId, motionEvent.getSource(),
4239 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004240 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004241 motionEvent.getMetaState(),
4242 motionEvent.getButtonState(),
4243 motionEvent.getClassification(),
4244 motionEvent.getEdgeFlags(),
4245 motionEvent.getXPrecision(),
4246 motionEvent.getYPrecision(),
4247 motionEvent.getRawXCursorPosition(),
4248 motionEvent.getRawYCursorPosition(),
4249 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004250 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 samplePointerCoords, motionEvent.getXOffset(),
4252 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004253 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 }
4255 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004259 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004260 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
4262
4263 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 injectionState->injectionIsAsync = true;
4266 }
4267
4268 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004269 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
4271 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004272 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004273 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004274 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276
4277 mLock.unlock();
4278
4279 if (needWake) {
4280 mLooper->wake();
4281 }
4282
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004285 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004287 if (syncMode == InputEventInjectionSync::NONE) {
4288 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 } else {
4290 for (;;) {
4291 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 break;
4294 }
4295
4296 nsecs_t remainingTimeout = endTime - now();
4297 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004298 if (DEBUG_INJECTION) {
4299 ALOGD("injectInputEvent - Timed out waiting for injection result "
4300 "to become available.");
4301 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 break;
4304 }
4305
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004306 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4310 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004312 if (DEBUG_INJECTION) {
4313 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4314 injectionState->pendingForegroundDispatches);
4315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 nsecs_t remainingTimeout = endTime - now();
4317 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004318 if (DEBUG_INJECTION) {
4319 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4320 "dispatches to finish.");
4321 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004322 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 break;
4324 }
4325
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004326 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328 }
4329 }
4330
4331 injectionState->release();
4332 } // release lock
4333
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004334 if (DEBUG_INJECTION) {
4335 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4336 injectionResult, injectorPid, injectorUid);
4337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
4339 return injectionResult;
4340}
4341
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004342std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004343 std::array<uint8_t, 32> calculatedHmac;
4344 std::unique_ptr<VerifiedInputEvent> result;
4345 switch (event.getType()) {
4346 case AINPUT_EVENT_TYPE_KEY: {
4347 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4348 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4349 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004350 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004351 break;
4352 }
4353 case AINPUT_EVENT_TYPE_MOTION: {
4354 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4355 VerifiedMotionEvent verifiedMotionEvent =
4356 verifiedMotionEventFromMotionEvent(motionEvent);
4357 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004358 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004359 break;
4360 }
4361 default: {
4362 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4363 return nullptr;
4364 }
4365 }
4366 if (calculatedHmac == INVALID_HMAC) {
4367 return nullptr;
4368 }
4369 if (calculatedHmac != event.getHmac()) {
4370 return nullptr;
4371 }
4372 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004373}
4374
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004376 return injectorUid == 0 ||
4377 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378}
4379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004380void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004384 if (DEBUG_INJECTION) {
4385 ALOGD("Setting input event injection result to %d. "
4386 "injectorPid=%d, injectorUid=%d",
4387 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004390 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 // Log the outcome since the injector did not wait for the injection result.
4392 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 ALOGV("Asynchronous input event injection succeeded.");
4395 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004397 ALOGW("Asynchronous input event injection failed.");
4398 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004399 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004400 ALOGW("Asynchronous input event injection permission denied.");
4401 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 ALOGW("Asynchronous input event injection timed out.");
4404 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 case InputEventInjectionResult::PENDING:
4406 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4407 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 }
4409 }
4410
4411 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004412 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414}
4415
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004416void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4417 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 if (injectionState) {
4419 injectionState->pendingForegroundDispatches += 1;
4420 }
4421}
4422
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004423void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4424 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 if (injectionState) {
4426 injectionState->pendingForegroundDispatches -= 1;
4427
4428 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004429 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 }
4431 }
4432}
4433
chaviw98318de2021-05-19 16:45:23 -05004434const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004435 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004436 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004437 auto it = mWindowHandlesByDisplay.find(displayId);
4438 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004439}
4440
chaviw98318de2021-05-19 16:45:23 -05004441sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004442 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004443 if (windowHandleToken == nullptr) {
4444 return nullptr;
4445 }
4446
Arthur Hungb92218b2018-08-14 12:00:21 +08004447 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004448 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4449 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004450 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004451 return windowHandle;
4452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004455 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456}
4457
chaviw98318de2021-05-19 16:45:23 -05004458sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4459 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004460 if (windowHandleToken == nullptr) {
4461 return nullptr;
4462 }
4463
chaviw98318de2021-05-19 16:45:23 -05004464 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004465 if (windowHandle->getToken() == windowHandleToken) {
4466 return windowHandle;
4467 }
4468 }
4469 return nullptr;
4470}
4471
chaviw98318de2021-05-19 16:45:23 -05004472sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4473 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004474 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004475 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4476 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004477 if (handle->getId() == windowHandle->getId() &&
4478 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004479 if (windowHandle->getInfo()->displayId != it.first) {
4480 ALOGE("Found window %s in display %" PRId32
4481 ", but it should belong to display %" PRId32,
4482 windowHandle->getName().c_str(), it.first,
4483 windowHandle->getInfo()->displayId);
4484 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004485 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004489 return nullptr;
4490}
4491
chaviw98318de2021-05-19 16:45:23 -05004492sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004493 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4494 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495}
4496
chaviw98318de2021-05-19 16:45:23 -05004497bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004498 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4499 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004500 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004501 if (connection != nullptr && noInputChannel) {
4502 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4503 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4504 return false;
4505 }
4506
4507 if (connection == nullptr) {
4508 if (!noInputChannel) {
4509 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4510 }
4511 return false;
4512 }
4513 if (!connection->responsive) {
4514 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4515 return false;
4516 }
4517 return true;
4518}
4519
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004520std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4521 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004522 auto connectionIt = mConnectionsByToken.find(token);
4523 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004524 return nullptr;
4525 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004526 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004527}
4528
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004529void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004530 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4531 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004532 // Remove all handles on a display if there are no windows left.
4533 mWindowHandlesByDisplay.erase(displayId);
4534 return;
4535 }
4536
4537 // Since we compare the pointer of input window handles across window updates, we need
4538 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004539 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4540 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4541 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004542 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004543 }
4544
chaviw98318de2021-05-19 16:45:23 -05004545 std::vector<sp<WindowInfoHandle>> newHandles;
4546 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004547 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004548 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004549 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004550 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4551 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4552 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004553 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004554 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004555 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004556 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004557 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004558 }
4559
4560 if (info->displayId != displayId) {
4561 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4562 handle->getName().c_str(), displayId, info->displayId);
4563 continue;
4564 }
4565
Robert Carredd13602020-04-13 17:24:34 -07004566 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4567 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004568 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004569 oldHandle->updateFrom(handle);
4570 newHandles.push_back(oldHandle);
4571 } else {
4572 newHandles.push_back(handle);
4573 }
4574 }
4575
4576 // Insert or replace
4577 mWindowHandlesByDisplay[displayId] = newHandles;
4578}
4579
Arthur Hung72d8dc32020-03-28 00:48:39 +00004580void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004581 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004582 { // acquire lock
4583 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004584 for (const auto& [displayId, handles] : handlesPerDisplay) {
4585 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004586 }
4587 }
4588 // Wake up poll loop since it may need to make new input dispatching choices.
4589 mLooper->wake();
4590}
4591
Arthur Hungb92218b2018-08-14 12:00:21 +08004592/**
4593 * Called from InputManagerService, update window handle list by displayId that can receive input.
4594 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4595 * If set an empty list, remove all handles from the specific display.
4596 * For focused handle, check if need to change and send a cancel event to previous one.
4597 * For removed handle, check if need to send a cancel event if already in touch.
4598 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004599void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004600 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004601 if (DEBUG_FOCUS) {
4602 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004603 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004604 windowList += iwh->getName() + " ";
4605 }
4606 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004609 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004610 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004611 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004612 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004613 if (noInputWindow && window->getToken() != nullptr) {
4614 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4615 window->getName().c_str());
4616 window->releaseChannel();
4617 }
4618 }
4619
Arthur Hung72d8dc32020-03-28 00:48:39 +00004620 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004621 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004623 // Save the old windows' orientation by ID before it gets updated.
4624 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004625 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004626 oldWindowOrientations.emplace(handle->getId(),
4627 handle->getInfo()->transform.getOrientation());
4628 }
4629
chaviw98318de2021-05-19 16:45:23 -05004630 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004631
chaviw98318de2021-05-19 16:45:23 -05004632 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004633 if (mLastHoverWindowHandle &&
4634 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4635 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004636 mLastHoverWindowHandle = nullptr;
4637 }
4638
Vishnu Nairc519ff72021-01-21 08:23:08 -08004639 std::optional<FocusResolver::FocusChanges> changes =
4640 mFocusResolver.setInputWindows(displayId, windowHandles);
4641 if (changes) {
4642 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004645 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4646 mTouchStatesByDisplay.find(displayId);
4647 if (stateIt != mTouchStatesByDisplay.end()) {
4648 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004649 for (size_t i = 0; i < state.windows.size();) {
4650 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004651 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004652 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004653 ALOGD("Touched window was removed: %s in display %" PRId32,
4654 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004655 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004656 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004657 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4658 if (touchedInputChannel != nullptr) {
4659 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4660 "touched window was removed");
4661 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004663 state.windows.erase(state.windows.begin() + i);
4664 } else {
4665 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 }
4667 }
arthurhungb89ccb02020-12-30 16:19:01 +08004668
arthurhung6d4bed92021-03-17 11:59:33 +08004669 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004670 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004671 if (mDragState &&
4672 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004673 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004674 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004675 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004676 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004677
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004678 if (isPerWindowInputRotationEnabled()) {
4679 // Determine if the orientation of any of the input windows have changed, and cancel all
4680 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004681 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4682 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004683 if (newWindowHandle != nullptr &&
4684 newWindowHandle->getInfo()->transform.getOrientation() !=
4685 oldWindowOrientations[oldWindowHandle->getId()]) {
4686 std::shared_ptr<InputChannel> inputChannel =
4687 getInputChannelLocked(newWindowHandle->getToken());
4688 if (inputChannel != nullptr) {
4689 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4690 "touched window's orientation changed");
4691 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4692 }
4693 }
4694 }
4695 }
4696
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 // Release information for windows that are no longer present.
4698 // This ensures that unused input channels are released promptly.
4699 // Otherwise, they might stick around until the window handle is destroyed
4700 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004701 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004702 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004703 if (DEBUG_FOCUS) {
4704 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004705 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004706 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004707 // To avoid making too many calls into the compat framework, only
4708 // check for window flags when windows are going away.
4709 // TODO(b/157929241) : delete this. This is only needed temporarily
4710 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004711 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004712 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4713 oldWindowHandle->getName().c_str());
4714 if (mCompatService != nullptr) {
4715 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4716 oldWindowHandle->getInfo()->ownerUid);
4717 }
4718 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004719 }
chaviw291d88a2019-02-14 10:33:58 -08004720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721}
4722
4723void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004724 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004725 if (DEBUG_FOCUS) {
4726 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4727 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4728 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004729 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004730 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004731 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 } // release lock
4733
4734 // Wake up poll loop since it may need to make new input dispatching choices.
4735 mLooper->wake();
4736}
4737
Vishnu Nair599f1412021-06-21 10:39:58 -07004738void InputDispatcher::setFocusedApplicationLocked(
4739 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4740 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4741 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4742
4743 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4744 return; // This application is already focused. No need to wake up or change anything.
4745 }
4746
4747 // Set the new application handle.
4748 if (inputApplicationHandle != nullptr) {
4749 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4750 } else {
4751 mFocusedApplicationHandlesByDisplay.erase(displayId);
4752 }
4753
4754 // No matter what the old focused application was, stop waiting on it because it is
4755 // no longer focused.
4756 resetNoFocusedWindowTimeoutLocked();
4757}
4758
Tiger Huang721e26f2018-07-24 22:26:19 +08004759/**
4760 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4761 * the display not specified.
4762 *
4763 * We track any unreleased events for each window. If a window loses the ability to receive the
4764 * released event, we will send a cancel event to it. So when the focused display is changed, we
4765 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4766 * display. The display-specified events won't be affected.
4767 */
4768void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004769 if (DEBUG_FOCUS) {
4770 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4771 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004772 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004773 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004774
4775 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004776 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004777 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004778 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004779 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004780 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004781 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 CancelationOptions
4783 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4784 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004785 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004786 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4787 }
4788 }
4789 mFocusedDisplayId = displayId;
4790
Chris Ye3c2d6f52020-08-09 10:39:48 -07004791 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004792 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004793 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004794
Vishnu Nairad321cd2020-08-20 16:40:21 -07004795 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004796 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004797 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004798 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004799 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004800 }
4801 }
4802 }
4803
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004804 if (DEBUG_FOCUS) {
4805 logDispatchStateLocked();
4806 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004807 } // release lock
4808
4809 // Wake up poll loop since it may need to make new input dispatching choices.
4810 mLooper->wake();
4811}
4812
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004814 if (DEBUG_FOCUS) {
4815 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817
4818 bool changed;
4819 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004820 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821
4822 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4823 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 }
4826
4827 if (mDispatchEnabled && !enabled) {
4828 resetAndDropEverythingLocked("dispatcher is being disabled");
4829 }
4830
4831 mDispatchEnabled = enabled;
4832 mDispatchFrozen = frozen;
4833 changed = true;
4834 } else {
4835 changed = false;
4836 }
4837
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004838 if (DEBUG_FOCUS) {
4839 logDispatchStateLocked();
4840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 } // release lock
4842
4843 if (changed) {
4844 // Wake up poll loop since it may need to make new input dispatching choices.
4845 mLooper->wake();
4846 }
4847}
4848
4849void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004850 if (DEBUG_FOCUS) {
4851 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853
4854 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004855 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856
4857 if (mInputFilterEnabled == enabled) {
4858 return;
4859 }
4860
4861 mInputFilterEnabled = enabled;
4862 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4863 } // release lock
4864
4865 // Wake up poll loop since there might be work to do to drop everything.
4866 mLooper->wake();
4867}
4868
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004869void InputDispatcher::setInTouchMode(bool inTouchMode) {
4870 std::scoped_lock lock(mLock);
4871 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004872 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004873}
4874
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004875void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4876 if (opacity < 0 || opacity > 1) {
4877 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4878 return;
4879 }
4880
4881 std::scoped_lock lock(mLock);
4882 mMaximumObscuringOpacityForTouch = opacity;
4883}
4884
4885void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4886 std::scoped_lock lock(mLock);
4887 mBlockUntrustedTouchesMode = mode;
4888}
4889
Arthur Hungabbb9d82021-09-01 14:52:30 +00004890std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4891 const sp<IBinder>& token) {
4892 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4893 for (TouchedWindow& w : state.windows) {
4894 if (w.windowHandle->getToken() == token) {
4895 return std::make_pair(&state, &w);
4896 }
4897 }
4898 }
4899 return std::make_pair(nullptr, nullptr);
4900}
4901
arthurhungb89ccb02020-12-30 16:19:01 +08004902bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4903 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004904 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004905 if (DEBUG_FOCUS) {
4906 ALOGD("Trivial transfer to same window.");
4907 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004908 return true;
4909 }
4910
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004912 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
Arthur Hungabbb9d82021-09-01 14:52:30 +00004914 // Find the target touch state and touched window by fromToken.
4915 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4916 if (state == nullptr || touchedWindow == nullptr) {
4917 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 return false;
4919 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004920
4921 const int32_t displayId = state->displayId;
4922 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4923 if (toWindowHandle == nullptr) {
4924 ALOGW("Cannot transfer focus because to window not found.");
4925 return false;
4926 }
4927
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004928 if (DEBUG_FOCUS) {
4929 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004930 touchedWindow->windowHandle->getName().c_str(),
4931 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 }
4933
Arthur Hungabbb9d82021-09-01 14:52:30 +00004934 // Erase old window.
4935 int32_t oldTargetFlags = touchedWindow->targetFlags;
4936 BitSet32 pointerIds = touchedWindow->pointerIds;
4937 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938
Arthur Hungabbb9d82021-09-01 14:52:30 +00004939 // Add new window.
4940 int32_t newTargetFlags = oldTargetFlags &
4941 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4942 InputTarget::FLAG_DISPATCH_AS_IS);
4943 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944
Arthur Hungabbb9d82021-09-01 14:52:30 +00004945 // Store the dragging window.
4946 if (isDragDrop) {
4947 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 }
4949
Arthur Hungabbb9d82021-09-01 14:52:30 +00004950 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004951 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4952 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004953 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004954 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004955 CancelationOptions
4956 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4957 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004959 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 }
4961
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004962 if (DEBUG_FOCUS) {
4963 logDispatchStateLocked();
4964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965 } // release lock
4966
4967 // Wake up poll loop since it may need to make new input dispatching choices.
4968 mLooper->wake();
4969 return true;
4970}
4971
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004972// Binder call
4973bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4974 sp<IBinder> fromToken;
4975 { // acquire lock
4976 std::scoped_lock _l(mLock);
4977
Arthur Hungabbb9d82021-09-01 14:52:30 +00004978 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
4979 [](const auto& pair) { return pair.second.windows.size() == 1; });
4980 if (it == mTouchStatesByDisplay.end()) {
4981 ALOGW("Cannot transfer touch state because there is no exact window being touched");
4982 return false;
4983 }
4984 const int32_t displayId = it->first;
4985 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004986 if (toWindowHandle == nullptr) {
4987 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4988 return false;
4989 }
4990
Arthur Hungabbb9d82021-09-01 14:52:30 +00004991 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004992 const TouchedWindow& touchedWindow = state.windows[0];
4993 fromToken = touchedWindow.windowHandle->getToken();
4994 } // release lock
4995
4996 return transferTouchFocus(fromToken, destChannelToken);
4997}
4998
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005000 if (DEBUG_FOCUS) {
5001 ALOGD("Resetting and dropping all events (%s).", reason);
5002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003
5004 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5005 synthesizeCancelationEventsForAllConnectionsLocked(options);
5006
5007 resetKeyRepeatLocked();
5008 releasePendingEventLocked();
5009 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005010 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005012 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005013 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005015 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016}
5017
5018void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005019 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 dumpDispatchStateLocked(dump);
5021
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005022 std::istringstream stream(dump);
5023 std::string line;
5024
5025 while (std::getline(stream, line, '\n')) {
5026 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 }
5028}
5029
Prabir Pradhan99987712020-11-10 18:43:05 -08005030std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5031 std::string dump;
5032
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005033 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5034 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005035
5036 std::string windowName = "None";
5037 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005038 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005039 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5040 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5041 : "token has capture without window";
5042 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005043 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005044
5045 return dump;
5046}
5047
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005048void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005049 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5050 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5051 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005052 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053
Tiger Huang721e26f2018-07-24 22:26:19 +08005054 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5055 dump += StringPrintf(INDENT "FocusedApplications:\n");
5056 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5057 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005058 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005059 const std::chrono::duration timeout =
5060 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005061 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005062 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005063 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005066 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005068
Vishnu Nairc519ff72021-01-21 08:23:08 -08005069 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005070 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005072 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005073 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005074 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5075 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005076 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005077 state.displayId, toString(state.down), toString(state.split),
5078 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005079 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005080 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005081 for (size_t i = 0; i < state.windows.size(); i++) {
5082 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005083 dump += StringPrintf(INDENT4
5084 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5085 i, touchedWindow.windowHandle->getName().c_str(),
5086 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005087 }
5088 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005089 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
5092 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005093 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 }
5095
arthurhung6d4bed92021-03-17 11:59:33 +08005096 if (mDragState) {
5097 dump += StringPrintf(INDENT "DragState:\n");
5098 mDragState->dump(dump, INDENT2);
5099 }
5100
Arthur Hungb92218b2018-08-14 12:00:21 +08005101 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005102 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005103 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005104 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005105 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005106 dump += INDENT2 "Windows:\n";
5107 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005108 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5109 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005111 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005112 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005113 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005114 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005115 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005116 "applicationInfo.name=%s, "
5117 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005118 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005119 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005120 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005121 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005122 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005123 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005124 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005125 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005126 windowInfo->frameLeft, windowInfo->frameTop,
5127 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005128 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005129 windowInfo->applicationInfo.name.c_str(),
5130 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005131 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005132 dump += StringPrintf(", inputFeatures=%s",
5133 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005134 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005135 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005136 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005137 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005138 millis(windowInfo->dispatchingTimeout),
5139 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005140 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005141 toString(windowInfo->touchOcclusionMode).c_str(),
5142 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005143 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005144 }
5145 } else {
5146 dump += INDENT2 "Windows: <none>\n";
5147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 }
5149 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005150 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 }
5152
Michael Wright3dd60e22019-03-27 22:06:44 +00005153 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005154 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005155 const std::vector<Monitor>& monitors = it.second;
5156 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5157 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005158 }
5159 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005160 const std::vector<Monitor>& monitors = it.second;
5161 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5162 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005165 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
5168 nsecs_t currentTime = now();
5169
5170 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005171 if (!mRecentQueue.empty()) {
5172 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005173 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005174 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005175 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005176 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 }
5178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005179 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 }
5181
5182 // Dump event currently being dispatched.
5183 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005184 dump += INDENT "PendingEvent:\n";
5185 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005186 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005187 dump += StringPrintf(", age=%" PRId64 "ms\n",
5188 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005190 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 }
5192
5193 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005194 if (!mInboundQueue.empty()) {
5195 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005196 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005197 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005198 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005199 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200 }
5201 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005202 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 }
5204
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005205 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005206 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005207 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5208 const KeyReplacement& replacement = pair.first;
5209 int32_t newKeyCode = pair.second;
5210 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005211 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005212 }
5213 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005214 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005215 }
5216
Prabir Pradhancef936d2021-07-21 16:17:52 +00005217 if (!mCommandQueue.empty()) {
5218 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5219 } else {
5220 dump += INDENT "CommandQueue: <empty>\n";
5221 }
5222
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005223 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005224 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005225 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005226 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005228 connection->inputChannel->getFd().get(),
5229 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005230 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005233 if (!connection->outboundQueue.empty()) {
5234 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5235 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005236 dump += dumpQueue(connection->outboundQueue, currentTime);
5237
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005239 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 }
5241
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005242 if (!connection->waitQueue.empty()) {
5243 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5244 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005245 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005247 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 }
5249 }
5250 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005251 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 }
5253
5254 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005255 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5256 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005258 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 }
5260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005261 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005262 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5263 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5264 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005265 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005266 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267}
5268
Michael Wright3dd60e22019-03-27 22:06:44 +00005269void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5270 const size_t numMonitors = monitors.size();
5271 for (size_t i = 0; i < numMonitors; i++) {
5272 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005273 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005274 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5275 dump += "\n";
5276 }
5277}
5278
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005279class LooperEventCallback : public LooperCallback {
5280public:
5281 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5282 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5283
5284private:
5285 std::function<int(int events)> mCallback;
5286};
5287
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005288Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005289 if (DEBUG_CHANNEL_CREATION) {
5290 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005293 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005294 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005295 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005296
5297 if (result) {
5298 return base::Error(result) << "Failed to open input channel pair with name " << name;
5299 }
5300
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005302 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005303 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005304 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005305 sp<Connection> connection =
5306 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005308 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5309 ALOGE("Created a new connection, but the token %p is already known", token.get());
5310 }
5311 mConnectionsByToken.emplace(token, connection);
5312
5313 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5314 this, std::placeholders::_1, token);
5315
5316 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 } // release lock
5318
5319 // Wake the looper because some connections have changed.
5320 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005321 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322}
5323
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005324Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5325 bool isGestureMonitor,
5326 const std::string& name,
5327 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005328 std::shared_ptr<InputChannel> serverChannel;
5329 std::unique_ptr<InputChannel> clientChannel;
5330 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5331 if (result) {
5332 return base::Error(result) << "Failed to open input channel pair with name " << name;
5333 }
5334
Michael Wright3dd60e22019-03-27 22:06:44 +00005335 { // acquire lock
5336 std::scoped_lock _l(mLock);
5337
5338 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005339 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5340 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005341 }
5342
Garfield Tan15601662020-09-22 15:32:38 -07005343 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005344 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005345 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005346
5347 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5348 ALOGE("Created a new connection, but the token %p is already known", token.get());
5349 }
5350 mConnectionsByToken.emplace(token, connection);
5351 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5352 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005353
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005354 auto& monitorsByDisplay =
5355 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005356 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005357
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005358 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005359 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5360 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005361 }
Garfield Tan15601662020-09-22 15:32:38 -07005362
Michael Wright3dd60e22019-03-27 22:06:44 +00005363 // Wake the looper because some connections have changed.
5364 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005365 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005366}
5367
Garfield Tan15601662020-09-22 15:32:38 -07005368status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005370 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371
Garfield Tan15601662020-09-22 15:32:38 -07005372 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 if (status) {
5374 return status;
5375 }
5376 } // release lock
5377
5378 // Wake the poll loop because removing the connection may have changed the current
5379 // synchronization state.
5380 mLooper->wake();
5381 return OK;
5382}
5383
Garfield Tan15601662020-09-22 15:32:38 -07005384status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5385 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005386 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005387 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005388 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 return BAD_VALUE;
5390 }
5391
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005392 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005393
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005395 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005398 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399
5400 nsecs_t currentTime = now();
5401 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5402
5403 connection->status = Connection::STATUS_ZOMBIE;
5404 return OK;
5405}
5406
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005407void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5408 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5409 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005410}
5411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005412void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005413 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005414 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005415 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005416 std::vector<Monitor>& monitors = it->second;
5417 const size_t numMonitors = monitors.size();
5418 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005419 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005420 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5421 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005422 monitors.erase(monitors.begin() + i);
5423 break;
5424 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005425 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005426 if (monitors.empty()) {
5427 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005428 } else {
5429 ++it;
5430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 }
5432}
5433
Michael Wright3dd60e22019-03-27 22:06:44 +00005434status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5435 { // acquire lock
5436 std::scoped_lock _l(mLock);
5437 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5438
5439 if (!foundDisplayId) {
5440 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5441 return BAD_VALUE;
5442 }
5443 int32_t displayId = foundDisplayId.value();
5444
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005445 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5446 mTouchStatesByDisplay.find(displayId);
5447 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005448 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5449 return BAD_VALUE;
5450 }
5451
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005452 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005453 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005454 std::optional<int32_t> foundDeviceId;
5455 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005456 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005457 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005458 foundDeviceId = state.deviceId;
5459 }
5460 }
5461 if (!foundDeviceId || !state.down) {
5462 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005463 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005464 return BAD_VALUE;
5465 }
5466 int32_t deviceId = foundDeviceId.value();
5467
5468 // Send cancel events to all the input channels we're stealing from.
5469 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005470 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005471 options.deviceId = deviceId;
5472 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005473 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005474 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005475 std::shared_ptr<InputChannel> channel =
5476 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005477 if (channel != nullptr) {
5478 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005479 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005480 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005481 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005482 canceledWindows += "]";
5483 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5484 canceledWindows.c_str());
5485
Michael Wright3dd60e22019-03-27 22:06:44 +00005486 // Then clear the current touch state so we stop dispatching to them as well.
5487 state.filterNonMonitors();
5488 }
5489 return OK;
5490}
5491
Prabir Pradhan99987712020-11-10 18:43:05 -08005492void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5493 { // acquire lock
5494 std::scoped_lock _l(mLock);
5495 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005496 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005497 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5498 windowHandle != nullptr ? windowHandle->getName().c_str()
5499 : "token without window");
5500 }
5501
Vishnu Nairc519ff72021-01-21 08:23:08 -08005502 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005503 if (focusedToken != windowToken) {
5504 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5505 enabled ? "enable" : "disable");
5506 return;
5507 }
5508
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005509 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005510 ALOGW("Ignoring request to %s Pointer Capture: "
5511 "window has %s requested pointer capture.",
5512 enabled ? "enable" : "disable", enabled ? "already" : "not");
5513 return;
5514 }
5515
Prabir Pradhan99987712020-11-10 18:43:05 -08005516 setPointerCaptureLocked(enabled);
5517 } // release lock
5518
5519 // Wake the thread to process command entries.
5520 mLooper->wake();
5521}
5522
Michael Wright3dd60e22019-03-27 22:06:44 +00005523std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5524 const sp<IBinder>& token) {
5525 for (const auto& it : mGestureMonitorsByDisplay) {
5526 const std::vector<Monitor>& monitors = it.second;
5527 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005528 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005529 return it.first;
5530 }
5531 }
5532 }
5533 return std::nullopt;
5534}
5535
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005536std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5537 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5538 if (gesturePid.has_value()) {
5539 return gesturePid;
5540 }
5541 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5542}
5543
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005544sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005545 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005546 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005547 }
5548
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005549 for (const auto& [token, connection] : mConnectionsByToken) {
5550 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005551 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 }
5553 }
Robert Carr4e670e52018-08-15 13:26:12 -07005554
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005555 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556}
5557
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005558std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5559 sp<Connection> connection = getConnectionLocked(connectionToken);
5560 if (connection == nullptr) {
5561 return "<nullptr>";
5562 }
5563 return connection->getInputChannelName();
5564}
5565
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005566void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005567 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005568 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005569}
5570
Prabir Pradhancef936d2021-07-21 16:17:52 +00005571void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5572 const sp<Connection>& connection, uint32_t seq,
5573 bool handled, nsecs_t consumeTime) {
5574 // Handle post-event policy actions.
5575 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5576 if (dispatchEntryIt == connection->waitQueue.end()) {
5577 return;
5578 }
5579 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5580 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5581 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5582 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5583 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5584 }
5585 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5586 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5587 connection->inputChannel->getConnectionToken(),
5588 dispatchEntry->deliveryTime, consumeTime, finishTime);
5589 }
5590
5591 bool restartEvent;
5592 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5593 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5594 restartEvent =
5595 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5596 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5597 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5598 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5599 handled);
5600 } else {
5601 restartEvent = false;
5602 }
5603
5604 // Dequeue the event and start the next cycle.
5605 // Because the lock might have been released, it is possible that the
5606 // contents of the wait queue to have been drained, so we need to double-check
5607 // a few things.
5608 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5609 if (dispatchEntryIt != connection->waitQueue.end()) {
5610 dispatchEntry = *dispatchEntryIt;
5611 connection->waitQueue.erase(dispatchEntryIt);
5612 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5613 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5614 if (!connection->responsive) {
5615 connection->responsive = isConnectionResponsive(*connection);
5616 if (connection->responsive) {
5617 // The connection was unresponsive, and now it's responsive.
5618 processConnectionResponsiveLocked(*connection);
5619 }
5620 }
5621 traceWaitQueueLength(*connection);
5622 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5623 connection->outboundQueue.push_front(dispatchEntry);
5624 traceOutboundQueueLength(*connection);
5625 } else {
5626 releaseDispatchEntry(dispatchEntry);
5627 }
5628 }
5629
5630 // Start the next dispatch cycle for this connection.
5631 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632}
5633
Prabir Pradhancef936d2021-07-21 16:17:52 +00005634void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5635 const sp<IBinder>& newToken) {
5636 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5637 scoped_unlock unlock(mLock);
5638 mPolicy->notifyFocusChanged(oldToken, newToken);
5639 };
5640 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641}
5642
Prabir Pradhancef936d2021-07-21 16:17:52 +00005643void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5644 auto command = [this, token, x, y]() REQUIRES(mLock) {
5645 scoped_unlock unlock(mLock);
5646 mPolicy->notifyDropWindow(token, x, y);
5647 };
5648 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005649}
5650
Prabir Pradhancef936d2021-07-21 16:17:52 +00005651void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5652 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5653 scoped_unlock unlock(mLock);
5654 mPolicy->notifyUntrustedTouch(obscuringPackage);
5655 };
5656 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005657}
5658
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005659void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5660 if (connection == nullptr) {
5661 LOG_ALWAYS_FATAL("Caller must check for nullness");
5662 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005663 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5664 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005665 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005666 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005667 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005668 return;
5669 }
5670 /**
5671 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5672 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5673 * has changed. This could cause newer entries to time out before the already dispatched
5674 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5675 * processes the events linearly. So providing information about the oldest entry seems to be
5676 * most useful.
5677 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005678 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005679 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5680 std::string reason =
5681 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005682 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005683 ns2ms(currentWait),
5684 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005685 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005686 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005687
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005688 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5689
5690 // Stop waking up for events on this connection, it is already unresponsive
5691 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005692}
5693
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005694void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5695 std::string reason =
5696 StringPrintf("%s does not have a focused window", application->getName().c_str());
5697 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005698
Prabir Pradhancef936d2021-07-21 16:17:52 +00005699 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5700 scoped_unlock unlock(mLock);
5701 mPolicy->notifyNoFocusedWindowAnr(application);
5702 };
5703 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005704}
5705
chaviw98318de2021-05-19 16:45:23 -05005706void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005707 const std::string& reason) {
5708 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5709 updateLastAnrStateLocked(windowLabel, reason);
5710}
5711
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005712void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5713 const std::string& reason) {
5714 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005715 updateLastAnrStateLocked(windowLabel, reason);
5716}
5717
5718void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5719 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005721 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 struct tm tm;
5723 localtime_r(&t, &tm);
5724 char timestr[64];
5725 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005726 mLastAnrState.clear();
5727 mLastAnrState += INDENT "ANR:\n";
5728 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005729 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5730 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005731 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732}
5733
Prabir Pradhancef936d2021-07-21 16:17:52 +00005734void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5735 KeyEntry& entry) {
5736 const KeyEvent event = createKeyEvent(entry);
5737 nsecs_t delay = 0;
5738 { // release lock
5739 scoped_unlock unlock(mLock);
5740 android::base::Timer t;
5741 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5742 entry.policyFlags);
5743 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5744 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5745 std::to_string(t.duration().count()).c_str());
5746 }
5747 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748
5749 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005750 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005751 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005752 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005754 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5755 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757}
5758
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005759void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005760 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5761 scoped_unlock unlock(mLock);
5762 mPolicy->notifyMonitorUnresponsive(pid, reason);
5763 };
5764 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005765}
5766
Prabir Pradhancef936d2021-07-21 16:17:52 +00005767void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005768 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005769 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5770 scoped_unlock unlock(mLock);
5771 mPolicy->notifyWindowUnresponsive(token, reason);
5772 };
5773 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005774}
5775
5776void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005777 auto command = [this, pid]() REQUIRES(mLock) {
5778 scoped_unlock unlock(mLock);
5779 mPolicy->notifyMonitorResponsive(pid);
5780 };
5781 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005782}
5783
Prabir Pradhancef936d2021-07-21 16:17:52 +00005784void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5785 auto command = [this, connectionToken]() REQUIRES(mLock) {
5786 scoped_unlock unlock(mLock);
5787 mPolicy->notifyWindowResponsive(connectionToken);
5788 };
5789 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005790}
5791
5792/**
5793 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5794 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5795 * command entry to the command queue.
5796 */
5797void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5798 std::string reason) {
5799 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5800 if (connection.monitor) {
5801 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5802 reason.c_str());
5803 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5804 if (!pid.has_value()) {
5805 ALOGE("Could not find unresponsive monitor for connection %s",
5806 connection.inputChannel->getName().c_str());
5807 return;
5808 }
5809 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5810 return;
5811 }
5812 // If not a monitor, must be a window
5813 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5814 reason.c_str());
5815 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5816}
5817
5818/**
5819 * Tell the policy that a connection has become responsive so that it can stop ANR.
5820 */
5821void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5822 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5823 if (connection.monitor) {
5824 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5825 if (!pid.has_value()) {
5826 ALOGE("Could not find responsive monitor for connection %s",
5827 connection.inputChannel->getName().c_str());
5828 return;
5829 }
5830 sendMonitorResponsiveCommandLocked(pid.value());
5831 return;
5832 }
5833 // If not a monitor, must be a window
5834 sendWindowResponsiveCommandLocked(connectionToken);
5835}
5836
Prabir Pradhancef936d2021-07-21 16:17:52 +00005837bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005838 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005839 KeyEntry& keyEntry, bool handled) {
5840 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005841 if (!handled) {
5842 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005843 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005844 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005845 return false;
5846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005848 // Get the fallback key state.
5849 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005850 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005851 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005852 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005853 connection->inputState.removeFallbackKey(originalKeyCode);
5854 }
5855
5856 if (handled || !dispatchEntry->hasForegroundTarget()) {
5857 // If the application handles the original key for which we previously
5858 // generated a fallback or if the window is not a foreground window,
5859 // then cancel the associated fallback key, if any.
5860 if (fallbackKeyCode != -1) {
5861 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005862 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5863 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5864 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5865 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5866 keyEntry.policyFlags);
5867 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005868 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005869 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870
5871 mLock.unlock();
5872
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005873 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005874 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875
5876 mLock.lock();
5877
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005878 // Cancel the fallback key.
5879 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 "application handled the original non-fallback key "
5882 "or is no longer a foreground target, "
5883 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884 options.keyCode = fallbackKeyCode;
5885 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005887 connection->inputState.removeFallbackKey(originalKeyCode);
5888 }
5889 } else {
5890 // If the application did not handle a non-fallback key, first check
5891 // that we are in a good state to perform unhandled key event processing
5892 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005893 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005894 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005895 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5896 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5897 "since this is not an initial down. "
5898 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5899 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5900 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005901 return false;
5902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005904 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005905 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5906 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5907 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5908 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5909 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005910 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005911
5912 mLock.unlock();
5913
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005914 bool fallback =
5915 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005916 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005917
5918 mLock.lock();
5919
5920 if (connection->status != Connection::STATUS_NORMAL) {
5921 connection->inputState.removeFallbackKey(originalKeyCode);
5922 return false;
5923 }
5924
5925 // Latch the fallback keycode for this key on an initial down.
5926 // The fallback keycode cannot change at any other point in the lifecycle.
5927 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005929 fallbackKeyCode = event.getKeyCode();
5930 } else {
5931 fallbackKeyCode = AKEYCODE_UNKNOWN;
5932 }
5933 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5934 }
5935
5936 ALOG_ASSERT(fallbackKeyCode != -1);
5937
5938 // Cancel the fallback key if the policy decides not to send it anymore.
5939 // We will continue to dispatch the key to the policy but we will no
5940 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005941 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5942 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005943 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5944 if (fallback) {
5945 ALOGD("Unhandled key event: Policy requested to send key %d"
5946 "as a fallback for %d, but on the DOWN it had requested "
5947 "to send %d instead. Fallback canceled.",
5948 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5949 } else {
5950 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5951 "but on the DOWN it had requested to send %d. "
5952 "Fallback canceled.",
5953 originalKeyCode, fallbackKeyCode);
5954 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956
5957 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5958 "canceling fallback, policy no longer desires it");
5959 options.keyCode = fallbackKeyCode;
5960 synthesizeCancelationEventsForConnectionLocked(connection, options);
5961
5962 fallback = false;
5963 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005964 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005965 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005966 }
5967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005969 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5970 {
5971 std::string msg;
5972 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5973 connection->inputState.getFallbackKeys();
5974 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5975 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5976 }
5977 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5978 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005980 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005981
5982 if (fallback) {
5983 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005984 keyEntry.eventTime = event.getEventTime();
5985 keyEntry.deviceId = event.getDeviceId();
5986 keyEntry.source = event.getSource();
5987 keyEntry.displayId = event.getDisplayId();
5988 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5989 keyEntry.keyCode = fallbackKeyCode;
5990 keyEntry.scanCode = event.getScanCode();
5991 keyEntry.metaState = event.getMetaState();
5992 keyEntry.repeatCount = event.getRepeatCount();
5993 keyEntry.downTime = event.getDownTime();
5994 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005995
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005996 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5997 ALOGD("Unhandled key event: Dispatching fallback key. "
5998 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5999 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6000 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006001 return true; // restart the event
6002 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006003 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6004 ALOGD("Unhandled key event: No fallback key.");
6005 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006006
6007 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006008 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 }
6010 }
6011 return false;
6012}
6013
Prabir Pradhancef936d2021-07-21 16:17:52 +00006014bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006015 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006016 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 return false;
6018}
6019
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020void InputDispatcher::traceInboundQueueLengthLocked() {
6021 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006022 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023 }
6024}
6025
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006026void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027 if (ATRACE_ENABLED()) {
6028 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006029 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6030 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 }
6032}
6033
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006034void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035 if (ATRACE_ENABLED()) {
6036 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006037 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6038 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 }
6040}
6041
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006042void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006043 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006045 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 dumpDispatchStateLocked(dump);
6047
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006048 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006049 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006050 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 }
6052}
6053
6054void InputDispatcher::monitor() {
6055 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006056 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006058 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059}
6060
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006061/**
6062 * Wake up the dispatcher and wait until it processes all events and commands.
6063 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6064 * this method can be safely called from any thread, as long as you've ensured that
6065 * the work you are interested in completing has already been queued.
6066 */
6067bool InputDispatcher::waitForIdle() {
6068 /**
6069 * Timeout should represent the longest possible time that a device might spend processing
6070 * events and commands.
6071 */
6072 constexpr std::chrono::duration TIMEOUT = 100ms;
6073 std::unique_lock lock(mLock);
6074 mLooper->wake();
6075 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6076 return result == std::cv_status::no_timeout;
6077}
6078
Vishnu Naire798b472020-07-23 13:52:21 -07006079/**
6080 * Sets focus to the window identified by the token. This must be called
6081 * after updating any input window handles.
6082 *
6083 * Params:
6084 * request.token - input channel token used to identify the window that should gain focus.
6085 * request.focusedToken - the token that the caller expects currently to be focused. If the
6086 * specified token does not match the currently focused window, this request will be dropped.
6087 * If the specified focused token matches the currently focused window, the call will succeed.
6088 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6089 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6090 * when requesting the focus change. This determines which request gets
6091 * precedence if there is a focus change request from another source such as pointer down.
6092 */
Vishnu Nair958da932020-08-21 17:12:37 -07006093void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6094 { // acquire lock
6095 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006096 std::optional<FocusResolver::FocusChanges> changes =
6097 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6098 if (changes) {
6099 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006100 }
6101 } // release lock
6102 // Wake up poll loop since it may need to make new input dispatching choices.
6103 mLooper->wake();
6104}
6105
Vishnu Nairc519ff72021-01-21 08:23:08 -08006106void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6107 if (changes.oldFocus) {
6108 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006109 if (focusedInputChannel) {
6110 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6111 "focus left window");
6112 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006113 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006114 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006115 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006116 if (changes.newFocus) {
6117 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006118 }
6119
Prabir Pradhan99987712020-11-10 18:43:05 -08006120 // If a window has pointer capture, then it must have focus. We need to ensure that this
6121 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6122 // If the window loses focus before it loses pointer capture, then the window can be in a state
6123 // where it has pointer capture but not focus, violating the contract. Therefore we must
6124 // dispatch the pointer capture event before the focus event. Since focus events are added to
6125 // the front of the queue (above), we add the pointer capture event to the front of the queue
6126 // after the focus events are added. This ensures the pointer capture event ends up at the
6127 // front.
6128 disablePointerCaptureForcedLocked();
6129
Vishnu Nairc519ff72021-01-21 08:23:08 -08006130 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006131 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006132 }
6133}
Vishnu Nair958da932020-08-21 17:12:37 -07006134
Prabir Pradhan99987712020-11-10 18:43:05 -08006135void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006136 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006137 return;
6138 }
6139
6140 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6141
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006142 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006143 setPointerCaptureLocked(false);
6144 }
6145
6146 if (!mWindowTokenWithPointerCapture) {
6147 // No need to send capture changes because no window has capture.
6148 return;
6149 }
6150
6151 if (mPendingEvent != nullptr) {
6152 // Move the pending event to the front of the queue. This will give the chance
6153 // for the pending event to be dropped if it is a captured event.
6154 mInboundQueue.push_front(mPendingEvent);
6155 mPendingEvent = nullptr;
6156 }
6157
6158 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006159 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006160 mInboundQueue.push_front(std::move(entry));
6161}
6162
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006163void InputDispatcher::setPointerCaptureLocked(bool enable) {
6164 mCurrentPointerCaptureRequest.enable = enable;
6165 mCurrentPointerCaptureRequest.seq++;
6166 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006168 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006169 };
6170 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006171}
6172
Vishnu Nair599f1412021-06-21 10:39:58 -07006173void InputDispatcher::displayRemoved(int32_t displayId) {
6174 { // acquire lock
6175 std::scoped_lock _l(mLock);
6176 // Set an empty list to remove all handles from the specific display.
6177 setInputWindowsLocked(/* window handles */ {}, displayId);
6178 setFocusedApplicationLocked(displayId, nullptr);
6179 // Call focus resolver to clean up stale requests. This must be called after input windows
6180 // have been removed for the removed display.
6181 mFocusResolver.displayRemoved(displayId);
6182 } // release lock
6183
6184 // Wake up poll loop since it may need to make new input dispatching choices.
6185 mLooper->wake();
6186}
6187
chaviw15fab6f2021-06-07 14:15:52 -05006188void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6189 // The listener sends the windows as a flattened array. Separate the windows by display for
6190 // more convenient parsing.
6191 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6192
6193 for (const auto& info : windowInfos) {
6194 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6195 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6196 }
6197 setInputWindows(handlesPerDisplay);
6198}
6199
Vishnu Nair062a8672021-09-03 16:07:44 -07006200bool InputDispatcher::shouldDropInput(
6201 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6202 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6203 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6204 isWindowObscuredLocked(windowHandle))) {
6205 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6206 "%" PRId32 ".",
6207 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6208 windowHandle->getInfo()->inputFeatures.string().c_str(),
6209 windowHandle->getInfo()->displayId);
6210 return true;
6211 }
6212 return false;
6213}
6214
Garfield Tane84e6f92019-08-29 17:28:41 -07006215} // namespace android::inputdispatcher