blob: ce383d9f258b7636b97ec19a098dfda7d448c29f [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, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001709 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001710 "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,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001713 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1714 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1715 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001717 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1718 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1719 "x=%f, y=%f, pressure=%f, size=%f, "
1720 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1721 "orientation=%f",
1722 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1723 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1724 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1725 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1726 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1727 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1728 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1729 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1730 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1731 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734}
1735
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001736void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1737 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001740 if (DEBUG_DISPATCH_CYCLE) {
1741 ALOGD("dispatchEventToCurrentInputTargets");
1742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001744 updateInteractionTokensLocked(*eventEntry, inputTargets);
1745
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1747
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001748 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001750 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001751 sp<Connection> connection =
1752 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001753 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001754 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001756 if (DEBUG_FOCUS) {
1757 ALOGD("Dropping event delivery to target with channel '%s' because it "
1758 "is no longer registered with the input dispatcher.",
1759 inputTarget.inputChannel->getName().c_str());
1760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762 }
1763}
1764
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1766 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1767 // If the policy decides to close the app, we will get a channel removal event via
1768 // unregisterInputChannel, and will clean up the connection that way. We are already not
1769 // sending new pointers to the connection when it blocked, but focused events will continue to
1770 // pile up.
1771 ALOGW("Canceling events for %s because it is unresponsive",
1772 connection->inputChannel->getName().c_str());
1773 if (connection->status == Connection::STATUS_NORMAL) {
1774 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1775 "application not responding");
1776 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
1778}
1779
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001780void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001781 if (DEBUG_FOCUS) {
1782 ALOGD("Resetting ANR timeouts.");
1783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784
1785 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001787 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788}
1789
Tiger Huang721e26f2018-07-24 22:26:19 +08001790/**
1791 * Get the display id that the given event should go to. If this event specifies a valid display id,
1792 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1793 * Focused display is the display that the user most recently interacted with.
1794 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001796 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001798 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001799 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1800 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 break;
1802 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001803 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001804 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1805 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 break;
1807 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001808 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001809 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001810 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001811 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001812 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001813 case EventEntry::Type::SENSOR:
1814 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001815 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001816 return ADISPLAY_ID_NONE;
1817 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001818 }
1819 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1820}
1821
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1823 const char* focusedWindowName) {
1824 if (mAnrTracker.empty()) {
1825 // already processed all events that we waited for
1826 mKeyIsWaitingForEventsTimeout = std::nullopt;
1827 return false;
1828 }
1829
1830 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1831 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001832 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001833 mKeyIsWaitingForEventsTimeout = currentTime +
1834 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1835 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 return true;
1837 }
1838
1839 // We still have pending events, and already started the timer
1840 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1841 return true; // Still waiting
1842 }
1843
1844 // Waited too long, and some connection still hasn't processed all motions
1845 // Just send the key to the focused window
1846 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1847 focusedWindowName);
1848 mKeyIsWaitingForEventsTimeout = std::nullopt;
1849 return false;
1850}
1851
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1853 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1854 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001855 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856
Tiger Huang721e26f2018-07-24 22:26:19 +08001857 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001858 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001859 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001860 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1861
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 // If there is no currently focused window and no focused application
1863 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001864 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1865 ALOGI("Dropping %s event because there is no focused window or focused application in "
1866 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001867 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
1870
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001871 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1872 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1873 // start interacting with another application via touch (app switch). This code can be removed
1874 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1875 // an app is expected to have a focused window.
1876 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1877 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1878 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001879 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1880 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1881 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001883 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 ALOGW("Waiting because no window has focus but %s may eventually add a "
1885 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001886 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1890 // Already raised ANR. Drop the event
1891 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001892 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 } else {
1895 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001896 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001897 }
1898 }
1899
1900 // we have a valid, non-null focused window
1901 resetNoFocusedWindowTimeoutLocked();
1902
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001904 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001905 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 }
1907
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 if (focusedWindowHandle->getInfo()->paused) {
1909 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001911 }
1912
1913 // If the event is a key event, then we must wait for all previous events to
1914 // complete before delivering it because previous events may have the
1915 // side-effect of transferring focus to a different window and we want to
1916 // ensure that the following keys are sent to the new window.
1917 //
1918 // Suppose the user touches a button in a window then immediately presses "A".
1919 // If the button causes a pop-up window to appear then we want to ensure that
1920 // the "A" key is delivered to the new pop-up window. This is because users
1921 // often anticipate pending UI changes when typing on a keyboard.
1922 // To obtain this behavior, we must serialize key events with respect to all
1923 // prior input events.
1924 if (entry.type == EventEntry::Type::KEY) {
1925 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1926 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
1930
1931 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001932 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1934 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
1936 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938}
1939
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001940/**
1941 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1942 * that are currently unresponsive.
1943 */
1944std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1945 const std::vector<TouchedMonitor>& monitors) const {
1946 std::vector<TouchedMonitor> responsiveMonitors;
1947 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1948 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1949 sp<Connection> connection = getConnectionLocked(
1950 monitor.monitor.inputChannel->getConnectionToken());
1951 if (connection == nullptr) {
1952 ALOGE("Could not find connection for monitor %s",
1953 monitor.monitor.inputChannel->getName().c_str());
1954 return false;
1955 }
1956 if (!connection->responsive) {
1957 ALOGW("Unresponsive monitor %s will not get the new gesture",
1958 connection->inputChannel->getName().c_str());
1959 return false;
1960 }
1961 return true;
1962 });
1963 return responsiveMonitors;
1964}
1965
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001966InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1967 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1968 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 enum InjectionPermission {
1971 INJECTION_PERMISSION_UNKNOWN,
1972 INJECTION_PERMISSION_GRANTED,
1973 INJECTION_PERMISSION_DENIED
1974 };
1975
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 // For security reasons, we defer updating the touch state until we are sure that
1977 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001978 int32_t displayId = entry.displayId;
1979 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1981
1982 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001983 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001985 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1986 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 // Copy current touch state into tempTouchState.
1989 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1990 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001991 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001992 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001993 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1994 mTouchStatesByDisplay.find(displayId);
1995 if (oldStateIt != mTouchStatesByDisplay.end()) {
1996 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001998 }
1999
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002000 bool isSplit = tempTouchState.split;
2001 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2002 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2003 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002004 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2005 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2006 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2007 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2008 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002009 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 bool wrongDevice = false;
2011 if (newGesture) {
2012 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002014 ALOGI("Dropping event because a pointer for a different device is already down "
2015 "in display %" PRId32,
2016 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002017 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002018 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 switchedDevice = false;
2020 wrongDevice = true;
2021 goto Failed;
2022 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 tempTouchState.reset();
2024 tempTouchState.down = down;
2025 tempTouchState.deviceId = entry.deviceId;
2026 tempTouchState.source = entry.source;
2027 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002029 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002030 ALOGI("Dropping move event because a pointer for a different device is already active "
2031 "in display %" PRId32,
2032 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002033 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002035 switchedDevice = false;
2036 wrongDevice = true;
2037 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 }
2039
2040 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2041 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2042
Garfield Tan00f511d2019-06-12 16:55:40 -07002043 int32_t x;
2044 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 // Always dispatch mouse events to cursor position.
2047 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 x = int32_t(entry.xCursorPosition);
2049 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002050 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2052 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002053 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002054 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002055 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2056 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002057
2058 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002059 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00002060 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 if (newTouchedWindowHandle != nullptr &&
2064 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002065 // New window supports splitting, but we should never split mouse events.
2066 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 } else if (isSplit) {
2068 // New window does not support splitting but we have already split events.
2069 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002070 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
2072
2073 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002074 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002076 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 }
2078
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002079 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2080 ALOGI("Not sending touch event to %s because it is paused",
2081 newTouchedWindowHandle->getName().c_str());
2082 newTouchedWindowHandle = nullptr;
2083 }
2084
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002085 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002087 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2088 if (!isResponsive) {
2089 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2091 newTouchedWindowHandle = nullptr;
2092 }
2093 }
2094
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002095 // Drop events that can't be trusted due to occlusion
2096 if (newTouchedWindowHandle != nullptr &&
2097 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2098 TouchOcclusionInfo occlusionInfo =
2099 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002100 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002101 if (DEBUG_TOUCH_OCCLUSION) {
2102 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2103 for (const auto& log : occlusionInfo.debugInfo) {
2104 ALOGD("%s", log.c_str());
2105 }
2106 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002107 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002108 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2109 ALOGW("Dropping untrusted touch event due to %s/%d",
2110 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2111 newTouchedWindowHandle = nullptr;
2112 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002113 }
2114 }
2115
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 // Also don't send the new touch event to unresponsive gesture monitors
2117 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2118
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2120 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 "(%d, %d) in display %" PRId32 ".",
2122 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002123 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002124 goto Failed;
2125 }
2126
2127 if (newTouchedWindowHandle != nullptr) {
2128 // Set target flags.
2129 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2130 if (isSplit) {
2131 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002133 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2134 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2135 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2136 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2137 }
2138
2139 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002140 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2141 newHoverWindowHandle = nullptr;
2142 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 }
2145
2146 // Update the temporary touch state.
2147 BitSet32 pointerIds;
2148 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002149 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002150 pointerIds.markBit(pointerId);
2151 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002152 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
2154
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 } else {
2157 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2158
2159 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002160 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002161 if (DEBUG_FOCUS) {
2162 ALOGD("Dropping event because the pointer is not down or we previously "
2163 "dropped the pointer down event in display %" PRId32,
2164 displayId);
2165 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002166 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 goto Failed;
2168 }
2169
arthurhung6d4bed92021-03-17 11:59:33 +08002170 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002171
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002173 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002175 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2176 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177
chaviw98318de2021-05-19 16:45:23 -05002178 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002179 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002180 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2182 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002183 if (DEBUG_FOCUS) {
2184 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2185 oldTouchedWindowHandle->getName().c_str(),
2186 newTouchedWindowHandle->getName().c_str(), displayId);
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2190 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2191 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192
2193 // Make a slippery entrance into the new window.
2194 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2195 isSplit = true;
2196 }
2197
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 int32_t targetFlags =
2199 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 if (isSplit) {
2201 targetFlags |= InputTarget::FLAG_SPLIT;
2202 }
2203 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2204 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002205 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2206 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
2208
2209 BitSet32 pointerIds;
2210 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002211 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 }
2215 }
2216 }
2217
2218 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002219 // Let the previous window know that the hover sequence is over, unless we already did it
2220 // when dispatching it as is to newTouchedWindowHandle.
2221 if (mLastHoverWindowHandle != nullptr &&
2222 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2223 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002224 if (DEBUG_HOVER) {
2225 ALOGD("Sending hover exit event to window %s.",
2226 mLastHoverWindowHandle->getName().c_str());
2227 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002228 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2229 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
Garfield Tandf26e862020-07-01 20:18:19 -07002232 // Let the new window know that the hover sequence is starting, unless we already did it
2233 // when dispatching it as is to newTouchedWindowHandle.
2234 if (newHoverWindowHandle != nullptr &&
2235 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2236 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002237 if (DEBUG_HOVER) {
2238 ALOGD("Sending hover enter event to window %s.",
2239 newHoverWindowHandle->getName().c_str());
2240 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002241 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2242 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2243 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
2245 }
2246
2247 // Check permission to inject into all touched foreground windows and ensure there
2248 // is at least one touched foreground window.
2249 {
2250 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2253 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002254 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002255 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 injectionPermission = INJECTION_PERMISSION_DENIED;
2257 goto Failed;
2258 }
2259 }
2260 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002261 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002262 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002263 ALOGI("Dropping event because there is no touched foreground window in display "
2264 "%" PRId32 " or gesture monitor to receive it.",
2265 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002266 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 goto Failed;
2268 }
2269
2270 // Permission granted to injection into all touched foreground windows.
2271 injectionPermission = INJECTION_PERMISSION_GRANTED;
2272 }
2273
2274 // Check whether windows listening for outside touches are owned by the same UID. If it is
2275 // set the policy flag that we will not reveal coordinate information to this window.
2276 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002277 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002279 if (foregroundWindowHandle) {
2280 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002283 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2284 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2285 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002286 InputTarget::FLAG_ZERO_COORDS,
2287 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290 }
2291 }
2292 }
2293
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 // If this is the first pointer going down and the touched window has a wallpaper
2295 // then also add the touched wallpaper windows so they are locked in for the duration
2296 // of the touch gesture.
2297 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2298 // engine only supports touch events. We would need to add a mechanism similar
2299 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2300 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002301 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002302 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002304 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002305 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002306 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2307 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002309 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002310 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311 .addOrUpdateWindow(windowHandle,
2312 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2313 InputTarget::
2314 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2315 InputTarget::FLAG_DISPATCH_AS_IS,
2316 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318 }
2319 }
2320 }
2321
2322 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002323 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002325 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 }
2329
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002330 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002333 }
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Drop the outside or hover touch windows since we will not care about them
2336 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002337 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
2339Failed:
2340 // Check injection permission once and for all.
2341 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002342 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 injectionPermission = INJECTION_PERMISSION_GRANTED;
2344 } else {
2345 injectionPermission = INJECTION_PERMISSION_DENIED;
2346 }
2347 }
2348
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002349 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2350 return injectionResult;
2351 }
2352
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002354 if (!wrongDevice) {
2355 if (switchedDevice) {
2356 if (DEBUG_FOCUS) {
2357 ALOGD("Conflicting pointer actions: Switched to a different device.");
2358 }
2359 *outConflictingPointerActions = true;
2360 }
2361
2362 if (isHoverAction) {
2363 // Started hovering, therefore no longer down.
2364 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002365 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2367 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 *outConflictingPointerActions = true;
2370 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 tempTouchState.reset();
2372 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2373 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2374 tempTouchState.deviceId = entry.deviceId;
2375 tempTouchState.source = entry.source;
2376 tempTouchState.displayId = displayId;
2377 }
2378 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2379 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2380 // All pointers up or canceled.
2381 tempTouchState.reset();
2382 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2383 // First pointer went down.
2384 if (oldState && oldState->down) {
2385 if (DEBUG_FOCUS) {
2386 ALOGD("Conflicting pointer actions: Down received while already down.");
2387 }
2388 *outConflictingPointerActions = true;
2389 }
2390 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2391 // One pointer went up.
2392 if (isSplit) {
2393 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2394 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002396 for (size_t i = 0; i < tempTouchState.windows.size();) {
2397 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2398 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2399 touchedWindow.pointerIds.clearBit(pointerId);
2400 if (touchedWindow.pointerIds.isEmpty()) {
2401 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2402 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002405 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002407 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002408 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002409
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002410 // Save changes unless the action was scroll in which case the temporary touch
2411 // state was only valid for this one action.
2412 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2413 if (tempTouchState.displayId >= 0) {
2414 mTouchStatesByDisplay[displayId] = tempTouchState;
2415 } else {
2416 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002420 // Update hover state.
2421 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 return injectionResult;
2425}
2426
arthurhung6d4bed92021-03-17 11:59:33 +08002427void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002428 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002429 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002430 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002431 if (dropWindow) {
2432 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002433 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002434 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002435 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002436 }
2437 mDragState.reset();
2438}
2439
2440void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2441 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002442 return;
2443 }
2444
arthurhung6d4bed92021-03-17 11:59:33 +08002445 if (!mDragState->isStartDrag) {
2446 mDragState->isStartDrag = true;
2447 mDragState->isStylusButtonDownAtStart =
2448 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2449 }
2450
arthurhungb89ccb02020-12-30 16:19:01 +08002451 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2452 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2453 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2454 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002455 // Handle the special case : stylus button no longer pressed.
2456 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2457 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2458 finishDragAndDrop(entry.displayId, x, y);
2459 return;
2460 }
2461
chaviw98318de2021-05-19 16:45:23 -05002462 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002463 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002464 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002465 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002466 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2467 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2468 if (mDragState->dragHoverWindowHandle != nullptr) {
2469 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2470 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002471 }
arthurhung6d4bed92021-03-17 11:59:33 +08002472 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002473 }
2474 // enqueue drag location if needed.
2475 if (hoverWindowHandle != nullptr) {
2476 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2477 }
arthurhung6d4bed92021-03-17 11:59:33 +08002478 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2479 finishDragAndDrop(entry.displayId, x, y);
2480 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002481 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002482 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002483 }
2484}
2485
chaviw98318de2021-05-19 16:45:23 -05002486void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 int32_t targetFlags, BitSet32 pointerIds,
2488 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002489 std::vector<InputTarget>::iterator it =
2490 std::find_if(inputTargets.begin(), inputTargets.end(),
2491 [&windowHandle](const InputTarget& inputTarget) {
2492 return inputTarget.inputChannel->getConnectionToken() ==
2493 windowHandle->getToken();
2494 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002495
chaviw98318de2021-05-19 16:45:23 -05002496 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002497
2498 if (it == inputTargets.end()) {
2499 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002500 std::shared_ptr<InputChannel> inputChannel =
2501 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002502 if (inputChannel == nullptr) {
2503 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2504 return;
2505 }
2506 inputTarget.inputChannel = inputChannel;
2507 inputTarget.flags = targetFlags;
2508 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002509 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002510 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002511 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002512 inputTargets.push_back(inputTarget);
2513 it = inputTargets.end() - 1;
2514 }
2515
2516 ALOG_ASSERT(it->flags == targetFlags);
2517 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2518
chaviw1ff3d1e2020-07-01 15:53:47 -07002519 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520}
2521
Michael Wright3dd60e22019-03-27 22:06:44 +00002522void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 int32_t displayId, float xOffset,
2524 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002525 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2526 mGlobalMonitorsByDisplay.find(displayId);
2527
2528 if (it != mGlobalMonitorsByDisplay.end()) {
2529 const std::vector<Monitor>& monitors = it->second;
2530 for (const Monitor& monitor : monitors) {
2531 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534}
2535
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2537 float yOffset,
2538 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002539 InputTarget target;
2540 target.inputChannel = monitor.inputChannel;
2541 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002542 ui::Transform t;
2543 t.set(xOffset, yOffset);
2544 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002545 inputTargets.push_back(target);
2546}
2547
chaviw98318de2021-05-19 16:45:23 -05002548bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 const InjectionState* injectionState) {
2550 if (injectionState &&
2551 (windowHandle == nullptr ||
2552 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2553 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002554 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 "owned by uid %d",
2557 injectionState->injectorPid, injectionState->injectorUid,
2558 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 } else {
2560 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
2563 return false;
2564 }
2565 return true;
2566}
2567
Robert Carrc9bf1d32020-04-13 17:21:08 -07002568/**
2569 * Indicate whether one window handle should be considered as obscuring
2570 * another window handle. We only check a few preconditions. Actually
2571 * checking the bounds is left to the caller.
2572 */
chaviw98318de2021-05-19 16:45:23 -05002573static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2574 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002575 // Compare by token so cloned layers aren't counted
2576 if (haveSameToken(windowHandle, otherHandle)) {
2577 return false;
2578 }
2579 auto info = windowHandle->getInfo();
2580 auto otherInfo = otherHandle->getInfo();
2581 if (!otherInfo->visible) {
2582 return false;
chaviw98318de2021-05-19 16:45:23 -05002583 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002584 // Those act as if they were invisible, so we don't need to flag them.
2585 // We do want to potentially flag touchable windows even if they have 0
2586 // opacity, since they can consume touches and alter the effects of the
2587 // user interaction (eg. apps that rely on
2588 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2589 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2590 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002591 } else if (info->ownerUid == otherInfo->ownerUid) {
2592 // If ownerUid is the same we don't generate occlusion events as there
2593 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002594 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002595 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002596 return false;
2597 } else if (otherInfo->displayId != info->displayId) {
2598 return false;
2599 }
2600 return true;
2601}
2602
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002603/**
2604 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2605 * untrusted, one should check:
2606 *
2607 * 1. If result.hasBlockingOcclusion is true.
2608 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2609 * BLOCK_UNTRUSTED.
2610 *
2611 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2612 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2613 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2614 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2615 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2616 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2617 *
2618 * If neither of those is true, then it means the touch can be allowed.
2619 */
2620InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002621 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2622 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002623 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002624 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002625 TouchOcclusionInfo info;
2626 info.hasBlockingOcclusion = false;
2627 info.obscuringOpacity = 0;
2628 info.obscuringUid = -1;
2629 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002630 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002631 if (windowHandle == otherHandle) {
2632 break; // All future windows are below us. Exit early.
2633 }
chaviw98318de2021-05-19 16:45:23 -05002634 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002635 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2636 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002637 if (DEBUG_TOUCH_OCCLUSION) {
2638 info.debugInfo.push_back(
2639 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2640 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002641 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2642 // we perform the checks below to see if the touch can be propagated or not based on the
2643 // window's touch occlusion mode
2644 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2645 info.hasBlockingOcclusion = true;
2646 info.obscuringUid = otherInfo->ownerUid;
2647 info.obscuringPackage = otherInfo->packageName;
2648 break;
2649 }
2650 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2651 uint32_t uid = otherInfo->ownerUid;
2652 float opacity =
2653 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2654 // Given windows A and B:
2655 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2656 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2657 opacityByUid[uid] = opacity;
2658 if (opacity > info.obscuringOpacity) {
2659 info.obscuringOpacity = opacity;
2660 info.obscuringUid = uid;
2661 info.obscuringPackage = otherInfo->packageName;
2662 }
2663 }
2664 }
2665 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002666 if (DEBUG_TOUCH_OCCLUSION) {
2667 info.debugInfo.push_back(
2668 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2669 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002670 return info;
2671}
2672
chaviw98318de2021-05-19 16:45:23 -05002673std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002674 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002675 return StringPrintf(INDENT2
2676 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2677 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2678 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2679 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002680 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002681 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002682 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2683 info->frameTop, info->frameRight, info->frameBottom,
2684 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002685 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2686 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2687 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002688}
2689
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002690bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2691 if (occlusionInfo.hasBlockingOcclusion) {
2692 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2693 occlusionInfo.obscuringUid);
2694 return false;
2695 }
2696 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2697 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2698 "%.2f, maximum allowed = %.2f)",
2699 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2700 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2701 return false;
2702 }
2703 return true;
2704}
2705
chaviw98318de2021-05-19 16:45:23 -05002706bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002707 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002709 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2710 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002711 if (windowHandle == otherHandle) {
2712 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 }
chaviw98318de2021-05-19 16:45:23 -05002714 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002715 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002716 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 return true;
2718 }
2719 }
2720 return false;
2721}
2722
chaviw98318de2021-05-19 16:45:23 -05002723bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002724 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002725 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2726 const WindowInfo* windowInfo = windowHandle->getInfo();
2727 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002728 if (windowHandle == otherHandle) {
2729 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002730 }
chaviw98318de2021-05-19 16:45:23 -05002731 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002732 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002733 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002734 return true;
2735 }
2736 }
2737 return false;
2738}
2739
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002740std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002741 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002742 if (applicationHandle != nullptr) {
2743 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002744 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 } else {
2746 return applicationHandle->getName();
2747 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002748 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002749 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002751 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753}
2754
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002755void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002756 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002757 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2758 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002759 // Focus or pointer capture changed events are passed to apps, but do not represent user
2760 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002761 return;
2762 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002763 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002764 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002765 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002766 const WindowInfo* info = focusedWindowHandle->getInfo();
2767 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002768 if (DEBUG_DISPATCH_CYCLE) {
2769 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 return;
2772 }
2773 }
2774
2775 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002776 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002777 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002778 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2779 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 return;
2781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002783 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 eventType = USER_ACTIVITY_EVENT_TOUCH;
2785 }
2786 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002788 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002789 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2790 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 return;
2792 }
2793 eventType = USER_ACTIVITY_EVENT_BUTTON;
2794 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07002796 case EventEntry::Type::TOUCH_MODE_CHANGED: {
2797 break;
2798 }
2799
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002800 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002801 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002802 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002803 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002804 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2805 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002806 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002807 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002808 break;
2809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811
Prabir Pradhancef936d2021-07-21 16:17:52 +00002812 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2813 REQUIRES(mLock) {
2814 scoped_unlock unlock(mLock);
2815 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2816 };
2817 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818}
2819
2820void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002822 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002823 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002824 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002826 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002827 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002828 ATRACE_NAME(message.c_str());
2829 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002830 if (DEBUG_DISPATCH_CYCLE) {
2831 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2832 "globalScaleFactor=%f, pointerIds=0x%x %s",
2833 connection->getInputChannelName().c_str(), inputTarget.flags,
2834 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2835 inputTarget.getPointerInfoString().c_str());
2836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
2838 // Skip this event if the connection status is not normal.
2839 // We don't want to enqueue additional outbound events if the connection is broken.
2840 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002841 if (DEBUG_DISPATCH_CYCLE) {
2842 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2843 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 return;
2846 }
2847
2848 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002849 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2850 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2851 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002852 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002854 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002855 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002856 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002857 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 if (!splitMotionEntry) {
2859 return; // split event was dropped
2860 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002861 if (DEBUG_FOCUS) {
2862 ALOGD("channel '%s' ~ Split motion event.",
2863 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002864 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002865 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002866 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2867 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 return;
2869 }
2870 }
2871
2872 // Not splitting. Enqueue dispatch entries for the event as is.
2873 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2874}
2875
2876void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002878 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002879 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002880 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002882 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002883 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002884 ATRACE_NAME(message.c_str());
2885 }
2886
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002887 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
2889 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002890 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002892 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002894 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002896 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002898 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002900 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902
2903 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002904 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 startDispatchCycleLocked(currentTime, connection);
2906 }
2907}
2908
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002910 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002911 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002913 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2915 connection->getInputChannelName().c_str(),
2916 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002917 ATRACE_NAME(message.c_str());
2918 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002919 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 if (!(inputTargetFlags & dispatchMode)) {
2921 return;
2922 }
2923 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2924
2925 // This is a new event.
2926 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002927 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002928 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002930 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2931 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002932 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002934 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002935 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002936 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002937 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002938 dispatchEntry->resolvedAction = keyEntry.action;
2939 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2942 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 if (DEBUG_DISPATCH_CYCLE) {
2944 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2945 "event",
2946 connection->getInputChannelName().c_str());
2947 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 return; // skip the inconsistent event
2949 }
2950 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002953 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002955 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2956 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2957 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2958 static_cast<int32_t>(IdGenerator::Source::OTHER);
2959 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2961 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2962 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2963 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2964 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2965 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2966 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2967 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2968 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2969 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2970 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002971 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002972 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 }
2974 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002975 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2976 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002977 if (DEBUG_DISPATCH_CYCLE) {
2978 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2979 "enter event",
2980 connection->getInputChannelName().c_str());
2981 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002982 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2983 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002987 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002988 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2989 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2990 }
2991 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2992 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2996 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002997 if (DEBUG_DISPATCH_CYCLE) {
2998 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2999 "event",
3000 connection->getInputChannelName().c_str());
3001 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 return; // skip the inconsistent event
3003 }
3004
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003005 dispatchEntry->resolvedEventId =
3006 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3007 ? mIdGenerator.nextId()
3008 : motionEntry.id;
3009 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3010 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3011 ") to MotionEvent(id=0x%" PRIx32 ").",
3012 motionEntry.id, dispatchEntry->resolvedEventId);
3013 ATRACE_NAME(message.c_str());
3014 }
3015
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003016 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3017 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3018 // Skip reporting pointer down outside focus to the policy.
3019 break;
3020 }
3021
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003022 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003023 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024
3025 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003027 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003028 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003029 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3030 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003031 break;
3032 }
Chris Yef59a2f42020-10-16 12:55:26 -07003033 case EventEntry::Type::SENSOR: {
3034 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3035 break;
3036 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003037 case EventEntry::Type::CONFIGURATION_CHANGED:
3038 case EventEntry::Type::DEVICE_RESET: {
3039 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003040 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003041 break;
3042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
3044
3045 // Remember that we are waiting for this dispatch to complete.
3046 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003047 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
3049
3050 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003051 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003052 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003053}
3054
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003055/**
3056 * This function is purely for debugging. It helps us understand where the user interaction
3057 * was taking place. For example, if user is touching launcher, we will see a log that user
3058 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3059 * We will see both launcher and wallpaper in that list.
3060 * Once the interaction with a particular set of connections starts, no new logs will be printed
3061 * until the set of interacted connections changes.
3062 *
3063 * The following items are skipped, to reduce the logspam:
3064 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3065 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3066 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3067 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3068 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003069 */
3070void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3071 const std::vector<InputTarget>& targets) {
3072 // Skip ACTION_UP events, and all events other than keys and motions
3073 if (entry.type == EventEntry::Type::KEY) {
3074 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3075 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3076 return;
3077 }
3078 } else if (entry.type == EventEntry::Type::MOTION) {
3079 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3080 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3081 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3082 return;
3083 }
3084 } else {
3085 return; // Not a key or a motion
3086 }
3087
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003088 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003089 std::vector<sp<Connection>> newConnections;
3090 for (const InputTarget& target : targets) {
3091 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3092 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3093 continue; // Skip windows that receive ACTION_OUTSIDE
3094 }
3095
3096 sp<IBinder> token = target.inputChannel->getConnectionToken();
3097 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003098 if (connection == nullptr) {
3099 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003100 }
3101 newConnectionTokens.insert(std::move(token));
3102 newConnections.emplace_back(connection);
3103 }
3104 if (newConnectionTokens == mInteractionConnectionTokens) {
3105 return; // no change
3106 }
3107 mInteractionConnectionTokens = newConnectionTokens;
3108
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003109 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003110 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003111 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003112 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003113 std::string message = "Interaction with: " + targetList;
3114 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003115 message += "<none>";
3116 }
3117 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3118}
3119
chaviwfd6d3512019-03-25 13:23:49 -07003120void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003121 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003122 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003123 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3124 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003125 return;
3126 }
3127
Vishnu Nairc519ff72021-01-21 08:23:08 -08003128 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003129 if (focusedToken == token) {
3130 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003131 return;
3132 }
3133
Prabir Pradhancef936d2021-07-21 16:17:52 +00003134 auto command = [this, token]() REQUIRES(mLock) {
3135 scoped_unlock unlock(mLock);
3136 mPolicy->onPointerDownOutsideFocus(token);
3137 };
3138 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139}
3140
3141void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003143 if (ATRACE_ENABLED()) {
3144 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003146 ATRACE_NAME(message.c_str());
3147 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003148 if (DEBUG_DISPATCH_CYCLE) {
3149 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003152 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3153 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003155 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003156 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003157 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
3159 // Publish the event.
3160 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3162 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003163 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3165 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003168 status = connection->inputPublisher
3169 .publishKeyEvent(dispatchEntry->seq,
3170 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3171 keyEntry.source, keyEntry.displayId,
3172 std::move(hmac), dispatchEntry->resolvedAction,
3173 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3174 keyEntry.scanCode, keyEntry.metaState,
3175 keyEntry.repeatCount, keyEntry.downTime,
3176 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
3179
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003180 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003184 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185
chaviw82357092020-01-28 13:13:06 -08003186 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003187 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3189 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003190 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003191 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3192 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003193 // Don't apply window scale here since we don't want scale to affect raw
3194 // coordinates. The scale will be sent back to the client and applied
3195 // later when requesting relative coordinates.
3196 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3197 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 }
3199 usingCoords = scaledCoords;
3200 }
3201 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 // We don't want the dispatch target to know.
3203 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 scaledCoords[i].clear();
3206 }
3207 usingCoords = scaledCoords;
3208 }
3209 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003211 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212
3213 // Publish the motion event.
3214 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003215 .publishMotionEvent(dispatchEntry->seq,
3216 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003217 motionEntry.deviceId, motionEntry.source,
3218 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003219 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003222 motionEntry.edgeFlags, motionEntry.metaState,
3223 motionEntry.buttonState,
3224 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003225 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003226 motionEntry.xPrecision, motionEntry.yPrecision,
3227 motionEntry.xCursorPosition,
3228 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003229 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003230 dispatchEntry->displaySize.x,
3231 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 motionEntry.downTime, motionEntry.eventTime,
3233 motionEntry.pointerCount,
3234 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 break;
3236 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003237
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003238 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003240 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 focusEntry.id,
3242 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003243 mInTouchMode);
3244 break;
3245 }
3246
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003247 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3248 const TouchModeEntry& touchModeEntry =
3249 static_cast<const TouchModeEntry&>(eventEntry);
3250 status = connection->inputPublisher
3251 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3252 touchModeEntry.inTouchMode);
3253
3254 break;
3255 }
3256
Prabir Pradhan99987712020-11-10 18:43:05 -08003257 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3258 const auto& captureEntry =
3259 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3260 status = connection->inputPublisher
3261 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003262 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003263 break;
3264 }
3265
arthurhungb89ccb02020-12-30 16:19:01 +08003266 case EventEntry::Type::DRAG: {
3267 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3268 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3269 dragEntry.id, dragEntry.x,
3270 dragEntry.y,
3271 dragEntry.isExiting);
3272 break;
3273 }
3274
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003275 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003276 case EventEntry::Type::DEVICE_RESET:
3277 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003278 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003279 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
3284 // Check the result.
3285 if (status) {
3286 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 "This is unexpected because the wait queue is empty, so the pipe "
3290 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003291 "event to it, status=%s(%d)",
3292 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3293 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3295 } else {
3296 // Pipe is full and we are waiting for the app to finish process some events
3297 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003298 if (DEBUG_DISPATCH_CYCLE) {
3299 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3300 "waiting for the application to catch up",
3301 connection->getInputChannelName().c_str());
3302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 }
3304 } else {
3305 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003306 "status=%s(%d)",
3307 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3308 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3310 }
3311 return;
3312 }
3313
3314 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3316 connection->outboundQueue.end(),
3317 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003318 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003319 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003320 if (connection->responsive) {
3321 mAnrTracker.insert(dispatchEntry->timeoutTime,
3322 connection->inputChannel->getConnectionToken());
3323 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003324 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
3326}
3327
chaviw09c8d2d2020-08-24 15:48:26 -07003328std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3329 size_t size;
3330 switch (event.type) {
3331 case VerifiedInputEvent::Type::KEY: {
3332 size = sizeof(VerifiedKeyEvent);
3333 break;
3334 }
3335 case VerifiedInputEvent::Type::MOTION: {
3336 size = sizeof(VerifiedMotionEvent);
3337 break;
3338 }
3339 }
3340 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3341 return mHmacKeyManager.sign(start, size);
3342}
3343
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003344const std::array<uint8_t, 32> InputDispatcher::getSignature(
3345 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3346 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3347 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3348 // Only sign events up and down events as the purely move events
3349 // are tied to their up/down counterparts so signing would be redundant.
3350 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3351 verifiedEvent.actionMasked = actionMasked;
3352 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003353 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003354 }
3355 return INVALID_HMAC;
3356}
3357
3358const std::array<uint8_t, 32> InputDispatcher::getSignature(
3359 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3360 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3361 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3362 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003363 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003364}
3365
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003368 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003369 if (DEBUG_DISPATCH_CYCLE) {
3370 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3371 connection->getInputChannelName().c_str(), seq, toString(handled));
3372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 if (connection->status == Connection::STATUS_BROKEN ||
3375 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 return;
3377 }
3378
3379 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003380 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3381 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3382 };
3383 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384}
3385
3386void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 const sp<Connection>& connection,
3388 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003389 if (DEBUG_DISPATCH_CYCLE) {
3390 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3391 connection->getInputChannelName().c_str(), toString(notify));
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
3394 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003395 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003396 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003397 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003398 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399
3400 // The connection appears to be unrecoverably broken.
3401 // Ignore already broken or zombie connections.
3402 if (connection->status == Connection::STATUS_NORMAL) {
3403 connection->status = Connection::STATUS_BROKEN;
3404
3405 if (notify) {
3406 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003407 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3408 connection->getInputChannelName().c_str());
3409
3410 auto command = [this, connection]() REQUIRES(mLock) {
3411 if (connection->status == Connection::STATUS_ZOMBIE) return;
3412 scoped_unlock unlock(mLock);
3413 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3414 };
3415 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417 }
3418}
3419
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003420void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3421 while (!queue.empty()) {
3422 DispatchEntry* dispatchEntry = queue.front();
3423 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003424 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426}
3427
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003428void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003430 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 }
3432 delete dispatchEntry;
3433}
3434
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003435int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3436 std::scoped_lock _l(mLock);
3437 sp<Connection> connection = getConnectionLocked(connectionToken);
3438 if (connection == nullptr) {
3439 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3440 connectionToken.get(), events);
3441 return 0; // remove the callback
3442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003444 bool notify;
3445 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3446 if (!(events & ALOOPER_EVENT_INPUT)) {
3447 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3448 "events=0x%x",
3449 connection->getInputChannelName().c_str(), events);
3450 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003453 nsecs_t currentTime = now();
3454 bool gotOne = false;
3455 status_t status = OK;
3456 for (;;) {
3457 Result<InputPublisher::ConsumerResponse> result =
3458 connection->inputPublisher.receiveConsumerResponse();
3459 if (!result.ok()) {
3460 status = result.error().code();
3461 break;
3462 }
3463
3464 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3465 const InputPublisher::Finished& finish =
3466 std::get<InputPublisher::Finished>(*result);
3467 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3468 finish.consumeTime);
3469 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003470 if (shouldReportMetricsForConnection(*connection)) {
3471 const InputPublisher::Timeline& timeline =
3472 std::get<InputPublisher::Timeline>(*result);
3473 mLatencyTracker
3474 .trackGraphicsLatency(timeline.inputEventId,
3475 connection->inputChannel->getConnectionToken(),
3476 std::move(timeline.graphicsTimeline));
3477 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003478 }
3479 gotOne = true;
3480 }
3481 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003482 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003483 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 return 1;
3485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003488 notify = status != DEAD_OBJECT || !connection->monitor;
3489 if (notify) {
3490 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3491 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3492 status);
3493 }
3494 } else {
3495 // Monitor channels are never explicitly unregistered.
3496 // We do it automatically when the remote endpoint is closed so don't warn about them.
3497 const bool stillHaveWindowHandle =
3498 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3499 notify = !connection->monitor && stillHaveWindowHandle;
3500 if (notify) {
3501 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3502 connection->getInputChannelName().c_str(), events);
3503 }
3504 }
3505
3506 // Remove the channel.
3507 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3508 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509}
3510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003513 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003514 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516}
3517
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003519 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003520 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3521 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3522}
3523
3524void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3525 const CancelationOptions& options,
3526 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3527 for (const auto& it : monitorsByDisplay) {
3528 const std::vector<Monitor>& monitors = it.second;
3529 for (const Monitor& monitor : monitors) {
3530 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003531 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003532 }
3533}
3534
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003536 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003537 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003538 if (connection == nullptr) {
3539 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003541
3542 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543}
3544
3545void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3546 const sp<Connection>& connection, const CancelationOptions& options) {
3547 if (connection->status == Connection::STATUS_BROKEN) {
3548 return;
3549 }
3550
3551 nsecs_t currentTime = now();
3552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003553 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003554 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003556 if (cancelationEvents.empty()) {
3557 return;
3558 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003559 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3560 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3561 "with reality: %s, mode=%d.",
3562 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3563 options.mode);
3564 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003565
3566 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003567 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003568 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3569 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003570 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003571 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003572 target.globalScaleFactor = windowInfo->globalScaleFactor;
3573 }
3574 target.inputChannel = connection->inputChannel;
3575 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3576
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003577 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003579 switch (cancelationEventEntry->type) {
3580 case EventEntry::Type::KEY: {
3581 logOutboundKeyDetails("cancel - ",
3582 static_cast<const KeyEntry&>(*cancelationEventEntry));
3583 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003585 case EventEntry::Type::MOTION: {
3586 logOutboundMotionDetails("cancel - ",
3587 static_cast<const MotionEntry&>(*cancelationEventEntry));
3588 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003590 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003591 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003592 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3593 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003594 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003595 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003596 break;
3597 }
3598 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003599 case EventEntry::Type::DEVICE_RESET:
3600 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003601 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003602 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003603 break;
3604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
3606
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003607 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3608 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003610
3611 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612}
3613
Svet Ganov5d3bc372020-01-26 23:11:07 -08003614void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3615 const sp<Connection>& connection) {
3616 if (connection->status == Connection::STATUS_BROKEN) {
3617 return;
3618 }
3619
3620 nsecs_t currentTime = now();
3621
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003622 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 connection->inputState.synthesizePointerDownEvents(currentTime);
3624
3625 if (downEvents.empty()) {
3626 return;
3627 }
3628
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003629 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003630 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3631 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003632 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003633
3634 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003635 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003636 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3637 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003638 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003639 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003640 target.globalScaleFactor = windowInfo->globalScaleFactor;
3641 }
3642 target.inputChannel = connection->inputChannel;
3643 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003645 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003646 switch (downEventEntry->type) {
3647 case EventEntry::Type::MOTION: {
3648 logOutboundMotionDetails("down - ",
3649 static_cast<const MotionEntry&>(*downEventEntry));
3650 break;
3651 }
3652
3653 case EventEntry::Type::KEY:
3654 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003655 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003656 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003657 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003658 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003659 case EventEntry::Type::SENSOR:
3660 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003662 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003663 break;
3664 }
3665 }
3666
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003667 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3668 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669 }
3670
3671 startDispatchCycleLocked(currentTime, connection);
3672}
3673
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003674std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3675 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 ALOG_ASSERT(pointerIds.value != 0);
3677
3678 uint32_t splitPointerIndexMap[MAX_POINTERS];
3679 PointerProperties splitPointerProperties[MAX_POINTERS];
3680 PointerCoords splitPointerCoords[MAX_POINTERS];
3681
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003682 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 uint32_t splitPointerCount = 0;
3684
3685 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003686 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003688 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 uint32_t pointerId = uint32_t(pointerProperties.id);
3690 if (pointerIds.hasBit(pointerId)) {
3691 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3692 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3693 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003694 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 splitPointerCount += 1;
3696 }
3697 }
3698
3699 if (splitPointerCount != pointerIds.count()) {
3700 // This is bad. We are missing some of the pointers that we expected to deliver.
3701 // Most likely this indicates that we received an ACTION_MOVE events that has
3702 // different pointer ids than we expected based on the previous ACTION_DOWN
3703 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3704 // in this way.
3705 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003706 "we expected there to be %d pointers. This probably means we received "
3707 "a broken sequence of pointer ids from the input device.",
3708 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003709 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
3711
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003712 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3715 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3717 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003718 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 uint32_t pointerId = uint32_t(pointerProperties.id);
3720 if (pointerIds.hasBit(pointerId)) {
3721 if (pointerIds.count() == 1) {
3722 // The first/last pointer went down/up.
3723 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003725 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3726 ? AMOTION_EVENT_ACTION_CANCEL
3727 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 } else {
3729 // A secondary pointer went down/up.
3730 uint32_t splitPointerIndex = 0;
3731 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3732 splitPointerIndex += 1;
3733 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003734 action = maskedAction |
3735 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737 } else {
3738 // An unrelated pointer changed.
3739 action = AMOTION_EVENT_ACTION_MOVE;
3740 }
3741 }
3742
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003743 int32_t newId = mIdGenerator.nextId();
3744 if (ATRACE_ENABLED()) {
3745 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3746 ") to MotionEvent(id=0x%" PRIx32 ").",
3747 originalMotionEntry.id, newId);
3748 ATRACE_NAME(message.c_str());
3749 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003750 std::unique_ptr<MotionEntry> splitMotionEntry =
3751 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3752 originalMotionEntry.deviceId, originalMotionEntry.source,
3753 originalMotionEntry.displayId,
3754 originalMotionEntry.policyFlags, action,
3755 originalMotionEntry.actionButton,
3756 originalMotionEntry.flags, originalMotionEntry.metaState,
3757 originalMotionEntry.buttonState,
3758 originalMotionEntry.classification,
3759 originalMotionEntry.edgeFlags,
3760 originalMotionEntry.xPrecision,
3761 originalMotionEntry.yPrecision,
3762 originalMotionEntry.xCursorPosition,
3763 originalMotionEntry.yCursorPosition,
3764 originalMotionEntry.downTime, splitPointerCount,
3765 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003767 if (originalMotionEntry.injectionState) {
3768 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 splitMotionEntry->injectionState->refCount += 1;
3770 }
3771
3772 return splitMotionEntry;
3773}
3774
3775void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003776 if (DEBUG_INBOUND_EVENT_DETAILS) {
3777 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
3780 bool needWake;
3781 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003782 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003784 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3785 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3786 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 } // release lock
3788
3789 if (needWake) {
3790 mLooper->wake();
3791 }
3792}
3793
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003794/**
3795 * If one of the meta shortcuts is detected, process them here:
3796 * Meta + Backspace -> generate BACK
3797 * Meta + Enter -> generate HOME
3798 * This will potentially overwrite keyCode and metaState.
3799 */
3800void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003802 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3803 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3804 if (keyCode == AKEYCODE_DEL) {
3805 newKeyCode = AKEYCODE_BACK;
3806 } else if (keyCode == AKEYCODE_ENTER) {
3807 newKeyCode = AKEYCODE_HOME;
3808 }
3809 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003810 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003811 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003812 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003813 keyCode = newKeyCode;
3814 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3815 }
3816 } else if (action == AKEY_EVENT_ACTION_UP) {
3817 // In order to maintain a consistent stream of up and down events, check to see if the key
3818 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3819 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003820 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003821 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003822 auto replacementIt = mReplacedKeys.find(replacement);
3823 if (replacementIt != mReplacedKeys.end()) {
3824 keyCode = replacementIt->second;
3825 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003826 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3827 }
3828 }
3829}
3830
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003832 if (DEBUG_INBOUND_EVENT_DETAILS) {
3833 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3834 "policyFlags=0x%x, action=0x%x, "
3835 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3836 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3837 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3838 args->downTime);
3839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 if (!validateKeyEvent(args->action)) {
3841 return;
3842 }
3843
3844 uint32_t policyFlags = args->policyFlags;
3845 int32_t flags = args->flags;
3846 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003847 // InputDispatcher tracks and generates key repeats on behalf of
3848 // whatever notifies it, so repeatCount should always be set to 0
3849 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3851 policyFlags |= POLICY_FLAG_VIRTUAL;
3852 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 if (policyFlags & POLICY_FLAG_FUNCTION) {
3855 metaState |= AMETA_FUNCTION_ON;
3856 }
3857
3858 policyFlags |= POLICY_FLAG_TRUSTED;
3859
Michael Wright78f24442014-08-06 15:55:28 -07003860 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003861 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003862
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003864 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003865 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3866 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867
Michael Wright2b3c3302018-03-02 17:19:13 +00003868 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003870 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3871 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 bool needWake;
3876 { // acquire lock
3877 mLock.lock();
3878
3879 if (shouldSendKeyToInputFilterLocked(args)) {
3880 mLock.unlock();
3881
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003882 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3884 return; // event was consumed by the filter
3885 }
3886
3887 mLock.lock();
3888 }
3889
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003890 std::unique_ptr<KeyEntry> newEntry =
3891 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3892 args->displayId, policyFlags, args->action, flags,
3893 keyCode, args->scanCode, metaState, repeatCount,
3894 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003896 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 mLock.unlock();
3898 } // release lock
3899
3900 if (needWake) {
3901 mLooper->wake();
3902 }
3903}
3904
3905bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3906 return mInputFilterEnabled;
3907}
3908
3909void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003910 if (DEBUG_INBOUND_EVENT_DETAILS) {
3911 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3912 "displayId=%" PRId32 ", policyFlags=0x%x, "
3913 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3914 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3915 "yCursorPosition=%f, downTime=%" PRId64,
3916 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3917 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3918 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3919 args->xCursorPosition, args->yCursorPosition, args->downTime);
3920 for (uint32_t i = 0; i < args->pointerCount; i++) {
3921 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3922 "x=%f, y=%f, pressure=%f, size=%f, "
3923 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3924 "orientation=%f",
3925 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3926 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3927 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3928 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3929 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3930 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3931 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3932 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3933 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3934 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003937 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3938 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 return;
3940 }
3941
3942 uint32_t policyFlags = args->policyFlags;
3943 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003944
3945 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003946 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003947 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3948 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951
3952 bool needWake;
3953 { // acquire lock
3954 mLock.lock();
3955
3956 if (shouldSendMotionToInputFilterLocked(args)) {
3957 mLock.unlock();
3958
3959 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003960 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003961 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3962 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003963 args->metaState, args->buttonState, args->classification, transform,
3964 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003965 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3966 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3967 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
3969 policyFlags |= POLICY_FLAG_FILTERED;
3970 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3971 return; // event was consumed by the filter
3972 }
3973
3974 mLock.lock();
3975 }
3976
3977 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003978 std::unique_ptr<MotionEntry> newEntry =
3979 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3980 args->source, args->displayId, policyFlags,
3981 args->action, args->actionButton, args->flags,
3982 args->metaState, args->buttonState,
3983 args->classification, args->edgeFlags,
3984 args->xPrecision, args->yPrecision,
3985 args->xCursorPosition, args->yCursorPosition,
3986 args->downTime, args->pointerCount,
3987 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003989 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3990 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3991 !mInputFilterEnabled) {
3992 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3993 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3994 }
3995
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003996 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 mLock.unlock();
3998 } // release lock
3999
4000 if (needWake) {
4001 mLooper->wake();
4002 }
4003}
4004
Chris Yef59a2f42020-10-16 12:55:26 -07004005void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004006 if (DEBUG_INBOUND_EVENT_DETAILS) {
4007 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4008 " sensorType=%s",
4009 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004010 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004011 }
Chris Yef59a2f42020-10-16 12:55:26 -07004012
4013 bool needWake;
4014 { // acquire lock
4015 mLock.lock();
4016
4017 // Just enqueue a new sensor event.
4018 std::unique_ptr<SensorEntry> newEntry =
4019 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4020 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4021 args->sensorType, args->accuracy,
4022 args->accuracyChanged, args->values);
4023
4024 needWake = enqueueInboundEventLocked(std::move(newEntry));
4025 mLock.unlock();
4026 } // release lock
4027
4028 if (needWake) {
4029 mLooper->wake();
4030 }
4031}
4032
Chris Yefb552902021-02-03 17:18:37 -08004033void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 if (DEBUG_INBOUND_EVENT_DETAILS) {
4035 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4036 args->deviceId, args->isOn);
4037 }
Chris Yefb552902021-02-03 17:18:37 -08004038 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4039}
4040
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004042 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043}
4044
4045void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004046 if (DEBUG_INBOUND_EVENT_DETAILS) {
4047 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4048 "switchMask=0x%08x",
4049 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
4052 uint32_t policyFlags = args->policyFlags;
4053 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055}
4056
4057void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004058 if (DEBUG_INBOUND_EVENT_DETAILS) {
4059 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4060 args->deviceId);
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
4063 bool needWake;
4064 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004065 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004067 std::unique_ptr<DeviceResetEntry> newEntry =
4068 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4069 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 } // release lock
4071
4072 if (needWake) {
4073 mLooper->wake();
4074 }
4075}
4076
Prabir Pradhan7e186182020-11-10 13:56:45 -08004077void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004078 if (DEBUG_INBOUND_EVENT_DETAILS) {
4079 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004080 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004081 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004082
Prabir Pradhan99987712020-11-10 18:43:05 -08004083 bool needWake;
4084 { // acquire lock
4085 std::scoped_lock _l(mLock);
4086 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004087 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004088 needWake = enqueueInboundEventLocked(std::move(entry));
4089 } // release lock
4090
4091 if (needWake) {
4092 mLooper->wake();
4093 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004094}
4095
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096InputEventInjectionResult InputDispatcher::injectInputEvent(
4097 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4098 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004099 if (DEBUG_INBOUND_EVENT_DETAILS) {
4100 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4101 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4102 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4103 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004104 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105
4106 policyFlags |= POLICY_FLAG_INJECTED;
4107 if (hasInjectionPermission(injectorPid, injectorUid)) {
4108 policyFlags |= POLICY_FLAG_TRUSTED;
4109 }
4110
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004112 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4113 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4114 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4115 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4116 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004117 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004118 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004120 }
4121
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004122 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004125 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4126 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004128 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004131 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004132 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4133 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4134 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004135 int32_t keyCode = incomingKey.getKeyCode();
4136 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004139 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004140 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004141 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4142 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4143 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4146 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004147 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148
4149 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4150 android::base::Timer t;
4151 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4152 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4153 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4154 std::to_string(t.duration().count()).c_str());
4155 }
4156 }
4157
4158 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004159 std::unique_ptr<KeyEntry> injectedEntry =
4160 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004161 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004162 incomingKey.getDisplayId(), policyFlags, action,
4163 flags, keyCode, incomingKey.getScanCode(), metaState,
4164 incomingKey.getRepeatCount(),
4165 incomingKey.getDownTime());
4166 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004171 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4172 int32_t action = motionEvent.getAction();
4173 size_t pointerCount = motionEvent.getPointerCount();
4174 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4175 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004176 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004177 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 }
4181
4182 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 android::base::Timer t;
4185 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4186 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4187 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4188 std::to_string(t.duration().count()).c_str());
4189 }
4190 }
4191
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004192 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4193 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4194 }
4195
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004197 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4198 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004199 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004200 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4201 resolvedDeviceId, motionEvent.getSource(),
4202 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004203 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004204 motionEvent.getButtonState(),
4205 motionEvent.getClassification(),
4206 motionEvent.getEdgeFlags(),
4207 motionEvent.getXPrecision(),
4208 motionEvent.getYPrecision(),
4209 motionEvent.getRawXCursorPosition(),
4210 motionEvent.getRawYCursorPosition(),
4211 motionEvent.getDownTime(), uint32_t(pointerCount),
4212 pointerProperties, samplePointerCoords,
4213 motionEvent.getXOffset(),
4214 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004215 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004216 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 sampleEventTimes += 1;
4218 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004219 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4221 resolvedDeviceId, motionEvent.getSource(),
4222 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004223 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 motionEvent.getMetaState(),
4225 motionEvent.getButtonState(),
4226 motionEvent.getClassification(),
4227 motionEvent.getEdgeFlags(),
4228 motionEvent.getXPrecision(),
4229 motionEvent.getYPrecision(),
4230 motionEvent.getRawXCursorPosition(),
4231 motionEvent.getRawYCursorPosition(),
4232 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 samplePointerCoords, motionEvent.getXOffset(),
4235 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 }
4238 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004242 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 }
4245
4246 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 injectionState->injectionIsAsync = true;
4249 }
4250
4251 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004252 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
4254 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004255 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004256 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004257 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
4260 mLock.unlock();
4261
4262 if (needWake) {
4263 mLooper->wake();
4264 }
4265
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004268 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 if (syncMode == InputEventInjectionSync::NONE) {
4271 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 } else {
4273 for (;;) {
4274 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004275 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 break;
4277 }
4278
4279 nsecs_t remainingTimeout = endTime - now();
4280 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004281 if (DEBUG_INJECTION) {
4282 ALOGD("injectInputEvent - Timed out waiting for injection result "
4283 "to become available.");
4284 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004285 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 break;
4287 }
4288
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004289 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4293 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004295 if (DEBUG_INJECTION) {
4296 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4297 injectionState->pendingForegroundDispatches);
4298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 nsecs_t remainingTimeout = endTime - now();
4300 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004301 if (DEBUG_INJECTION) {
4302 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4303 "dispatches to finish.");
4304 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 break;
4307 }
4308
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004309 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
4312 }
4313
4314 injectionState->release();
4315 } // release lock
4316
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 if (DEBUG_INJECTION) {
4318 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4319 injectionResult, injectorPid, injectorUid);
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
4322 return injectionResult;
4323}
4324
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004325std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004326 std::array<uint8_t, 32> calculatedHmac;
4327 std::unique_ptr<VerifiedInputEvent> result;
4328 switch (event.getType()) {
4329 case AINPUT_EVENT_TYPE_KEY: {
4330 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4331 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4332 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004333 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004334 break;
4335 }
4336 case AINPUT_EVENT_TYPE_MOTION: {
4337 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4338 VerifiedMotionEvent verifiedMotionEvent =
4339 verifiedMotionEventFromMotionEvent(motionEvent);
4340 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004341 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004342 break;
4343 }
4344 default: {
4345 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4346 return nullptr;
4347 }
4348 }
4349 if (calculatedHmac == INVALID_HMAC) {
4350 return nullptr;
4351 }
4352 if (calculatedHmac != event.getHmac()) {
4353 return nullptr;
4354 }
4355 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004356}
4357
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 return injectorUid == 0 ||
4360 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361}
4362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004363void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004367 if (DEBUG_INJECTION) {
4368 ALOGD("Setting input event injection result to %d. "
4369 "injectorPid=%d, injectorUid=%d",
4370 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 // Log the outcome since the injector did not wait for the injection result.
4375 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004376 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 ALOGV("Asynchronous input event injection succeeded.");
4378 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004379 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 ALOGW("Asynchronous input event injection failed.");
4381 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004382 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 ALOGW("Asynchronous input event injection permission denied.");
4384 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004386 ALOGW("Asynchronous input event injection timed out.");
4387 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 case InputEventInjectionResult::PENDING:
4389 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392 }
4393
4394 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004395 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397}
4398
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004399void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4400 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 if (injectionState) {
4402 injectionState->pendingForegroundDispatches += 1;
4403 }
4404}
4405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004406void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4407 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 if (injectionState) {
4409 injectionState->pendingForegroundDispatches -= 1;
4410
4411 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004412 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414 }
4415}
4416
chaviw98318de2021-05-19 16:45:23 -05004417const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004418 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004419 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004420 auto it = mWindowHandlesByDisplay.find(displayId);
4421 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004422}
4423
chaviw98318de2021-05-19 16:45:23 -05004424sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004425 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004426 if (windowHandleToken == nullptr) {
4427 return nullptr;
4428 }
4429
Arthur Hungb92218b2018-08-14 12:00:21 +08004430 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004431 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4432 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004433 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004434 return windowHandle;
4435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 }
4437 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004438 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439}
4440
chaviw98318de2021-05-19 16:45:23 -05004441sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4442 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004443 if (windowHandleToken == nullptr) {
4444 return nullptr;
4445 }
4446
chaviw98318de2021-05-19 16:45:23 -05004447 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004448 if (windowHandle->getToken() == windowHandleToken) {
4449 return windowHandle;
4450 }
4451 }
4452 return nullptr;
4453}
4454
chaviw98318de2021-05-19 16:45:23 -05004455sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4456 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004457 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004458 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4459 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004460 if (handle->getId() == windowHandle->getId() &&
4461 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004462 if (windowHandle->getInfo()->displayId != it.first) {
4463 ALOGE("Found window %s in display %" PRId32
4464 ", but it should belong to display %" PRId32,
4465 windowHandle->getName().c_str(), it.first,
4466 windowHandle->getInfo()->displayId);
4467 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004468 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 }
4471 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004472 return nullptr;
4473}
4474
chaviw98318de2021-05-19 16:45:23 -05004475sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004476 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4477 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478}
4479
chaviw98318de2021-05-19 16:45:23 -05004480bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004481 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4482 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004483 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004484 if (connection != nullptr && noInputChannel) {
4485 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4486 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4487 return false;
4488 }
4489
4490 if (connection == nullptr) {
4491 if (!noInputChannel) {
4492 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4493 }
4494 return false;
4495 }
4496 if (!connection->responsive) {
4497 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4498 return false;
4499 }
4500 return true;
4501}
4502
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004503std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4504 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004505 auto connectionIt = mConnectionsByToken.find(token);
4506 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004507 return nullptr;
4508 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004509 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004510}
4511
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004512void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004513 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4514 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004515 // Remove all handles on a display if there are no windows left.
4516 mWindowHandlesByDisplay.erase(displayId);
4517 return;
4518 }
4519
4520 // Since we compare the pointer of input window handles across window updates, we need
4521 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004522 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4523 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4524 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004525 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004526 }
4527
chaviw98318de2021-05-19 16:45:23 -05004528 std::vector<sp<WindowInfoHandle>> newHandles;
4529 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004530 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004531 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004532 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004533 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4534 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4535 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004536 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004537 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004538 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004539 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004540 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004541 }
4542
4543 if (info->displayId != displayId) {
4544 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4545 handle->getName().c_str(), displayId, info->displayId);
4546 continue;
4547 }
4548
Robert Carredd13602020-04-13 17:24:34 -07004549 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4550 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004551 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004552 oldHandle->updateFrom(handle);
4553 newHandles.push_back(oldHandle);
4554 } else {
4555 newHandles.push_back(handle);
4556 }
4557 }
4558
4559 // Insert or replace
4560 mWindowHandlesByDisplay[displayId] = newHandles;
4561}
4562
Arthur Hung72d8dc32020-03-28 00:48:39 +00004563void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004564 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004565 { // acquire lock
4566 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004567 for (const auto& [displayId, handles] : handlesPerDisplay) {
4568 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004569 }
4570 }
4571 // Wake up poll loop since it may need to make new input dispatching choices.
4572 mLooper->wake();
4573}
4574
Arthur Hungb92218b2018-08-14 12:00:21 +08004575/**
4576 * Called from InputManagerService, update window handle list by displayId that can receive input.
4577 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4578 * If set an empty list, remove all handles from the specific display.
4579 * For focused handle, check if need to change and send a cancel event to previous one.
4580 * For removed handle, check if need to send a cancel event if already in touch.
4581 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004582void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004583 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004584 if (DEBUG_FOCUS) {
4585 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004586 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004587 windowList += iwh->getName() + " ";
4588 }
4589 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004592 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004593 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004594 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004595 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004596 if (noInputWindow && window->getToken() != nullptr) {
4597 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4598 window->getName().c_str());
4599 window->releaseChannel();
4600 }
4601 }
4602
Arthur Hung72d8dc32020-03-28 00:48:39 +00004603 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004604 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004606 // Save the old windows' orientation by ID before it gets updated.
4607 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004608 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004609 oldWindowOrientations.emplace(handle->getId(),
4610 handle->getInfo()->transform.getOrientation());
4611 }
4612
chaviw98318de2021-05-19 16:45:23 -05004613 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004614
chaviw98318de2021-05-19 16:45:23 -05004615 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004616 if (mLastHoverWindowHandle &&
4617 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4618 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619 mLastHoverWindowHandle = nullptr;
4620 }
4621
Vishnu Nairc519ff72021-01-21 08:23:08 -08004622 std::optional<FocusResolver::FocusChanges> changes =
4623 mFocusResolver.setInputWindows(displayId, windowHandles);
4624 if (changes) {
4625 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004628 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4629 mTouchStatesByDisplay.find(displayId);
4630 if (stateIt != mTouchStatesByDisplay.end()) {
4631 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004632 for (size_t i = 0; i < state.windows.size();) {
4633 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004634 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004635 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004636 ALOGD("Touched window was removed: %s in display %" PRId32,
4637 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004638 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004639 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004640 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4641 if (touchedInputChannel != nullptr) {
4642 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4643 "touched window was removed");
4644 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004645 // Since we are about to drop the touch, cancel the events for the wallpaper as
4646 // well.
4647 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4648 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4649 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4650 if (wallpaper != nullptr) {
4651 sp<Connection> wallpaperConnection =
4652 getConnectionLocked(wallpaper->getToken());
4653 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4654 options);
4655 }
4656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004658 state.windows.erase(state.windows.begin() + i);
4659 } else {
4660 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 }
4662 }
arthurhungb89ccb02020-12-30 16:19:01 +08004663
arthurhung6d4bed92021-03-17 11:59:33 +08004664 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004665 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004666 if (mDragState &&
4667 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004668 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004669 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004670 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004671 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004672
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004673 if (isPerWindowInputRotationEnabled()) {
4674 // Determine if the orientation of any of the input windows have changed, and cancel all
4675 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004676 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4677 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004678 if (newWindowHandle != nullptr &&
4679 newWindowHandle->getInfo()->transform.getOrientation() !=
4680 oldWindowOrientations[oldWindowHandle->getId()]) {
4681 std::shared_ptr<InputChannel> inputChannel =
4682 getInputChannelLocked(newWindowHandle->getToken());
4683 if (inputChannel != nullptr) {
4684 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4685 "touched window's orientation changed");
4686 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4687 }
4688 }
4689 }
4690 }
4691
Arthur Hung72d8dc32020-03-28 00:48:39 +00004692 // Release information for windows that are no longer present.
4693 // This ensures that unused input channels are released promptly.
4694 // Otherwise, they might stick around until the window handle is destroyed
4695 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004696 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004697 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004698 if (DEBUG_FOCUS) {
4699 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004700 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004701 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004702 // To avoid making too many calls into the compat framework, only
4703 // check for window flags when windows are going away.
4704 // TODO(b/157929241) : delete this. This is only needed temporarily
4705 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004706 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004707 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4708 oldWindowHandle->getName().c_str());
4709 if (mCompatService != nullptr) {
4710 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4711 oldWindowHandle->getInfo()->ownerUid);
4712 }
4713 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004714 }
chaviw291d88a2019-02-14 10:33:58 -08004715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716}
4717
4718void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004719 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004720 if (DEBUG_FOCUS) {
4721 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4722 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4723 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004724 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004725 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004726 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 } // release lock
4728
4729 // Wake up poll loop since it may need to make new input dispatching choices.
4730 mLooper->wake();
4731}
4732
Vishnu Nair599f1412021-06-21 10:39:58 -07004733void InputDispatcher::setFocusedApplicationLocked(
4734 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4735 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4736 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4737
4738 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4739 return; // This application is already focused. No need to wake up or change anything.
4740 }
4741
4742 // Set the new application handle.
4743 if (inputApplicationHandle != nullptr) {
4744 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4745 } else {
4746 mFocusedApplicationHandlesByDisplay.erase(displayId);
4747 }
4748
4749 // No matter what the old focused application was, stop waiting on it because it is
4750 // no longer focused.
4751 resetNoFocusedWindowTimeoutLocked();
4752}
4753
Tiger Huang721e26f2018-07-24 22:26:19 +08004754/**
4755 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4756 * the display not specified.
4757 *
4758 * We track any unreleased events for each window. If a window loses the ability to receive the
4759 * released event, we will send a cancel event to it. So when the focused display is changed, we
4760 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4761 * display. The display-specified events won't be affected.
4762 */
4763void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004764 if (DEBUG_FOCUS) {
4765 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4766 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004767 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004768 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004769
4770 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004771 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004772 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004773 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004774 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004775 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004776 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 CancelationOptions
4778 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4779 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004780 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004781 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4782 }
4783 }
4784 mFocusedDisplayId = displayId;
4785
Chris Ye3c2d6f52020-08-09 10:39:48 -07004786 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004787 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004788 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004789
Vishnu Nairad321cd2020-08-20 16:40:21 -07004790 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004791 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004792 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004793 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004794 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004795 }
4796 }
4797 }
4798
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004799 if (DEBUG_FOCUS) {
4800 logDispatchStateLocked();
4801 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004802 } // release lock
4803
4804 // Wake up poll loop since it may need to make new input dispatching choices.
4805 mLooper->wake();
4806}
4807
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004809 if (DEBUG_FOCUS) {
4810 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812
4813 bool changed;
4814 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004815 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
4817 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4818 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004819 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 }
4821
4822 if (mDispatchEnabled && !enabled) {
4823 resetAndDropEverythingLocked("dispatcher is being disabled");
4824 }
4825
4826 mDispatchEnabled = enabled;
4827 mDispatchFrozen = frozen;
4828 changed = true;
4829 } else {
4830 changed = false;
4831 }
4832
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004833 if (DEBUG_FOCUS) {
4834 logDispatchStateLocked();
4835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 } // release lock
4837
4838 if (changed) {
4839 // Wake up poll loop since it may need to make new input dispatching choices.
4840 mLooper->wake();
4841 }
4842}
4843
4844void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004845 if (DEBUG_FOCUS) {
4846 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
4849 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004850 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851
4852 if (mInputFilterEnabled == enabled) {
4853 return;
4854 }
4855
4856 mInputFilterEnabled = enabled;
4857 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4858 } // release lock
4859
4860 // Wake up poll loop since there might be work to do to drop everything.
4861 mLooper->wake();
4862}
4863
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004864void InputDispatcher::setInTouchMode(bool inTouchMode) {
4865 std::scoped_lock lock(mLock);
4866 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004867 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004868}
4869
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004870void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4871 if (opacity < 0 || opacity > 1) {
4872 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4873 return;
4874 }
4875
4876 std::scoped_lock lock(mLock);
4877 mMaximumObscuringOpacityForTouch = opacity;
4878}
4879
4880void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4881 std::scoped_lock lock(mLock);
4882 mBlockUntrustedTouchesMode = mode;
4883}
4884
Arthur Hungabbb9d82021-09-01 14:52:30 +00004885std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4886 const sp<IBinder>& token) {
4887 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4888 for (TouchedWindow& w : state.windows) {
4889 if (w.windowHandle->getToken() == token) {
4890 return std::make_pair(&state, &w);
4891 }
4892 }
4893 }
4894 return std::make_pair(nullptr, nullptr);
4895}
4896
arthurhungb89ccb02020-12-30 16:19:01 +08004897bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4898 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004899 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004900 if (DEBUG_FOCUS) {
4901 ALOGD("Trivial transfer to same window.");
4902 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004903 return true;
4904 }
4905
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
Arthur Hungabbb9d82021-09-01 14:52:30 +00004909 // Find the target touch state and touched window by fromToken.
4910 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4911 if (state == nullptr || touchedWindow == nullptr) {
4912 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 return false;
4914 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004915
4916 const int32_t displayId = state->displayId;
4917 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4918 if (toWindowHandle == nullptr) {
4919 ALOGW("Cannot transfer focus because to window not found.");
4920 return false;
4921 }
4922
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004923 if (DEBUG_FOCUS) {
4924 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004925 touchedWindow->windowHandle->getName().c_str(),
4926 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 }
4928
Arthur Hungabbb9d82021-09-01 14:52:30 +00004929 // Erase old window.
4930 int32_t oldTargetFlags = touchedWindow->targetFlags;
4931 BitSet32 pointerIds = touchedWindow->pointerIds;
4932 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
Arthur Hungabbb9d82021-09-01 14:52:30 +00004934 // Add new window.
4935 int32_t newTargetFlags = oldTargetFlags &
4936 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4937 InputTarget::FLAG_DISPATCH_AS_IS);
4938 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939
Arthur Hungabbb9d82021-09-01 14:52:30 +00004940 // Store the dragging window.
4941 if (isDragDrop) {
4942 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943 }
4944
Arthur Hungabbb9d82021-09-01 14:52:30 +00004945 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004946 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4947 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004948 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004949 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 CancelationOptions
4951 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4952 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004954 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 }
4956
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004957 if (DEBUG_FOCUS) {
4958 logDispatchStateLocked();
4959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 } // release lock
4961
4962 // Wake up poll loop since it may need to make new input dispatching choices.
4963 mLooper->wake();
4964 return true;
4965}
4966
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004967// Binder call
4968bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4969 sp<IBinder> fromToken;
4970 { // acquire lock
4971 std::scoped_lock _l(mLock);
4972
Arthur Hungabbb9d82021-09-01 14:52:30 +00004973 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
4974 [](const auto& pair) { return pair.second.windows.size() == 1; });
4975 if (it == mTouchStatesByDisplay.end()) {
4976 ALOGW("Cannot transfer touch state because there is no exact window being touched");
4977 return false;
4978 }
4979 const int32_t displayId = it->first;
4980 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004981 if (toWindowHandle == nullptr) {
4982 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4983 return false;
4984 }
4985
Arthur Hungabbb9d82021-09-01 14:52:30 +00004986 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004987 const TouchedWindow& touchedWindow = state.windows[0];
4988 fromToken = touchedWindow.windowHandle->getToken();
4989 } // release lock
4990
4991 return transferTouchFocus(fromToken, destChannelToken);
4992}
4993
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004995 if (DEBUG_FOCUS) {
4996 ALOGD("Resetting and dropping all events (%s).", reason);
4997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
4999 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5000 synthesizeCancelationEventsForAllConnectionsLocked(options);
5001
5002 resetKeyRepeatLocked();
5003 releasePendingEventLocked();
5004 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005005 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005007 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005008 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005010 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011}
5012
5013void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005014 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 dumpDispatchStateLocked(dump);
5016
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005017 std::istringstream stream(dump);
5018 std::string line;
5019
5020 while (std::getline(stream, line, '\n')) {
5021 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 }
5023}
5024
Prabir Pradhan99987712020-11-10 18:43:05 -08005025std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5026 std::string dump;
5027
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005028 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5029 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005030
5031 std::string windowName = "None";
5032 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005033 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005034 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5035 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5036 : "token has capture without window";
5037 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005038 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005039
5040 return dump;
5041}
5042
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005043void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005044 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5045 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5046 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005047 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048
Tiger Huang721e26f2018-07-24 22:26:19 +08005049 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5050 dump += StringPrintf(INDENT "FocusedApplications:\n");
5051 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5052 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005053 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005054 const std::chrono::duration timeout =
5055 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005056 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005057 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005058 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005061 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005063
Vishnu Nairc519ff72021-01-21 08:23:08 -08005064 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005065 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005067 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005068 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005069 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5070 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005071 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005072 state.displayId, toString(state.down), toString(state.split),
5073 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005074 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005075 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005076 for (size_t i = 0; i < state.windows.size(); i++) {
5077 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005078 dump += StringPrintf(INDENT4
5079 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5080 i, touchedWindow.windowHandle->getName().c_str(),
5081 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005082 }
5083 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005084 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005088 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 }
5090
arthurhung6d4bed92021-03-17 11:59:33 +08005091 if (mDragState) {
5092 dump += StringPrintf(INDENT "DragState:\n");
5093 mDragState->dump(dump, INDENT2);
5094 }
5095
Arthur Hungb92218b2018-08-14 12:00:21 +08005096 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005097 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005098 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005099 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005100 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005101 dump += INDENT2 "Windows:\n";
5102 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005103 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5104 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005106 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005107 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005108 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005109 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005110 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005111 "applicationInfo.name=%s, "
5112 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005113 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005114 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005115 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005116 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005117 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005118 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005119 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005120 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005121 windowInfo->frameLeft, windowInfo->frameTop,
5122 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005123 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005124 windowInfo->applicationInfo.name.c_str(),
5125 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005126 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005127 dump += StringPrintf(", inputFeatures=%s",
5128 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005129 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005130 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005131 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005132 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005133 millis(windowInfo->dispatchingTimeout),
5134 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005135 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005136 toString(windowInfo->touchOcclusionMode).c_str(),
5137 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005138 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005139 }
5140 } else {
5141 dump += INDENT2 "Windows: <none>\n";
5142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005145 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147
Michael Wright3dd60e22019-03-27 22:06:44 +00005148 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005149 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005150 const std::vector<Monitor>& monitors = it.second;
5151 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5152 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005153 }
5154 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005155 const std::vector<Monitor>& monitors = it.second;
5156 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5157 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005160 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 }
5162
5163 nsecs_t currentTime = now();
5164
5165 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005166 if (!mRecentQueue.empty()) {
5167 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005168 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005169 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005170 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005171 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 }
5173 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005174 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 }
5176
5177 // Dump event currently being dispatched.
5178 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005179 dump += INDENT "PendingEvent:\n";
5180 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005181 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005182 dump += StringPrintf(", age=%" PRId64 "ms\n",
5183 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005185 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 }
5187
5188 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005189 if (!mInboundQueue.empty()) {
5190 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005191 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005192 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005193 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005194 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 }
5196 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005197 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 }
5199
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005200 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005201 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005202 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5203 const KeyReplacement& replacement = pair.first;
5204 int32_t newKeyCode = pair.second;
5205 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005206 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005207 }
5208 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005209 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005210 }
5211
Prabir Pradhancef936d2021-07-21 16:17:52 +00005212 if (!mCommandQueue.empty()) {
5213 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5214 } else {
5215 dump += INDENT "CommandQueue: <empty>\n";
5216 }
5217
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005218 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005219 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005220 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005221 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005223 connection->inputChannel->getFd().get(),
5224 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005225 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005226 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005228 if (!connection->outboundQueue.empty()) {
5229 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5230 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005231 dump += dumpQueue(connection->outboundQueue, currentTime);
5232
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005234 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 }
5236
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005237 if (!connection->waitQueue.empty()) {
5238 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5239 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005240 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005242 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 }
5244 }
5245 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005246 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 }
5248
5249 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005250 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5251 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005253 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 }
5255
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005256 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005257 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5258 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5259 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005260 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005261 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262}
5263
Michael Wright3dd60e22019-03-27 22:06:44 +00005264void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5265 const size_t numMonitors = monitors.size();
5266 for (size_t i = 0; i < numMonitors; i++) {
5267 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005268 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005269 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5270 dump += "\n";
5271 }
5272}
5273
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005274class LooperEventCallback : public LooperCallback {
5275public:
5276 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5277 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5278
5279private:
5280 std::function<int(int events)> mCallback;
5281};
5282
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005283Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005284 if (DEBUG_CHANNEL_CREATION) {
5285 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005288 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005289 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005290 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005291
5292 if (result) {
5293 return base::Error(result) << "Failed to open input channel pair with name " << name;
5294 }
5295
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005297 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005298 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005299 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005300 sp<Connection> connection =
5301 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005303 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5304 ALOGE("Created a new connection, but the token %p is already known", token.get());
5305 }
5306 mConnectionsByToken.emplace(token, connection);
5307
5308 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5309 this, std::placeholders::_1, token);
5310
5311 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 } // release lock
5313
5314 // Wake the looper because some connections have changed.
5315 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005316 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317}
5318
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005319Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5320 bool isGestureMonitor,
5321 const std::string& name,
5322 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005323 std::shared_ptr<InputChannel> serverChannel;
5324 std::unique_ptr<InputChannel> clientChannel;
5325 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5326 if (result) {
5327 return base::Error(result) << "Failed to open input channel pair with name " << name;
5328 }
5329
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 { // acquire lock
5331 std::scoped_lock _l(mLock);
5332
5333 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005334 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5335 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005336 }
5337
Garfield Tan15601662020-09-22 15:32:38 -07005338 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005339 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005340 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005341
5342 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5343 ALOGE("Created a new connection, but the token %p is already known", token.get());
5344 }
5345 mConnectionsByToken.emplace(token, connection);
5346 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5347 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005349 auto& monitorsByDisplay =
5350 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005351 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005352
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005353 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005354 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5355 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005356 }
Garfield Tan15601662020-09-22 15:32:38 -07005357
Michael Wright3dd60e22019-03-27 22:06:44 +00005358 // Wake the looper because some connections have changed.
5359 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005360 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005361}
5362
Garfield Tan15601662020-09-22 15:32:38 -07005363status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005365 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
Garfield Tan15601662020-09-22 15:32:38 -07005367 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 if (status) {
5369 return status;
5370 }
5371 } // release lock
5372
5373 // Wake the poll loop because removing the connection may have changed the current
5374 // synchronization state.
5375 mLooper->wake();
5376 return OK;
5377}
5378
Garfield Tan15601662020-09-22 15:32:38 -07005379status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5380 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005381 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005382 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005383 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 return BAD_VALUE;
5385 }
5386
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005387 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005388
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005390 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 }
5392
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005393 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394
5395 nsecs_t currentTime = now();
5396 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5397
5398 connection->status = Connection::STATUS_ZOMBIE;
5399 return OK;
5400}
5401
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005402void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5403 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5404 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005405}
5406
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005407void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005408 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005409 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005410 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005411 std::vector<Monitor>& monitors = it->second;
5412 const size_t numMonitors = monitors.size();
5413 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005414 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005415 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5416 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005417 monitors.erase(monitors.begin() + i);
5418 break;
5419 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005420 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005421 if (monitors.empty()) {
5422 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005423 } else {
5424 ++it;
5425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 }
5427}
5428
Michael Wright3dd60e22019-03-27 22:06:44 +00005429status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5430 { // acquire lock
5431 std::scoped_lock _l(mLock);
5432 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5433
5434 if (!foundDisplayId) {
5435 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5436 return BAD_VALUE;
5437 }
5438 int32_t displayId = foundDisplayId.value();
5439
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005440 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5441 mTouchStatesByDisplay.find(displayId);
5442 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005443 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5444 return BAD_VALUE;
5445 }
5446
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005447 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005448 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005449 std::optional<int32_t> foundDeviceId;
5450 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005451 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005452 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005453 foundDeviceId = state.deviceId;
5454 }
5455 }
5456 if (!foundDeviceId || !state.down) {
5457 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005458 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005459 return BAD_VALUE;
5460 }
5461 int32_t deviceId = foundDeviceId.value();
5462
5463 // Send cancel events to all the input channels we're stealing from.
5464 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005465 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005466 options.deviceId = deviceId;
5467 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005468 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005469 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005470 std::shared_ptr<InputChannel> channel =
5471 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005472 if (channel != nullptr) {
5473 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005474 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005475 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005476 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005477 canceledWindows += "]";
5478 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5479 canceledWindows.c_str());
5480
Michael Wright3dd60e22019-03-27 22:06:44 +00005481 // Then clear the current touch state so we stop dispatching to them as well.
5482 state.filterNonMonitors();
5483 }
5484 return OK;
5485}
5486
Prabir Pradhan99987712020-11-10 18:43:05 -08005487void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5488 { // acquire lock
5489 std::scoped_lock _l(mLock);
5490 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005491 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005492 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5493 windowHandle != nullptr ? windowHandle->getName().c_str()
5494 : "token without window");
5495 }
5496
Vishnu Nairc519ff72021-01-21 08:23:08 -08005497 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005498 if (focusedToken != windowToken) {
5499 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5500 enabled ? "enable" : "disable");
5501 return;
5502 }
5503
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005504 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005505 ALOGW("Ignoring request to %s Pointer Capture: "
5506 "window has %s requested pointer capture.",
5507 enabled ? "enable" : "disable", enabled ? "already" : "not");
5508 return;
5509 }
5510
Prabir Pradhan99987712020-11-10 18:43:05 -08005511 setPointerCaptureLocked(enabled);
5512 } // release lock
5513
5514 // Wake the thread to process command entries.
5515 mLooper->wake();
5516}
5517
Michael Wright3dd60e22019-03-27 22:06:44 +00005518std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5519 const sp<IBinder>& token) {
5520 for (const auto& it : mGestureMonitorsByDisplay) {
5521 const std::vector<Monitor>& monitors = it.second;
5522 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005523 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005524 return it.first;
5525 }
5526 }
5527 }
5528 return std::nullopt;
5529}
5530
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005531std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5532 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5533 if (gesturePid.has_value()) {
5534 return gesturePid;
5535 }
5536 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5537}
5538
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005539sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005540 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005541 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005542 }
5543
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005544 for (const auto& [token, connection] : mConnectionsByToken) {
5545 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005546 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 }
5548 }
Robert Carr4e670e52018-08-15 13:26:12 -07005549
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005550 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551}
5552
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005553std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5554 sp<Connection> connection = getConnectionLocked(connectionToken);
5555 if (connection == nullptr) {
5556 return "<nullptr>";
5557 }
5558 return connection->getInputChannelName();
5559}
5560
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005561void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005563 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005564}
5565
Prabir Pradhancef936d2021-07-21 16:17:52 +00005566void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5567 const sp<Connection>& connection, uint32_t seq,
5568 bool handled, nsecs_t consumeTime) {
5569 // Handle post-event policy actions.
5570 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5571 if (dispatchEntryIt == connection->waitQueue.end()) {
5572 return;
5573 }
5574 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5575 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5576 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5577 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5578 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5579 }
5580 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5581 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5582 connection->inputChannel->getConnectionToken(),
5583 dispatchEntry->deliveryTime, consumeTime, finishTime);
5584 }
5585
5586 bool restartEvent;
5587 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5588 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5589 restartEvent =
5590 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5591 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5592 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5593 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5594 handled);
5595 } else {
5596 restartEvent = false;
5597 }
5598
5599 // Dequeue the event and start the next cycle.
5600 // Because the lock might have been released, it is possible that the
5601 // contents of the wait queue to have been drained, so we need to double-check
5602 // a few things.
5603 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5604 if (dispatchEntryIt != connection->waitQueue.end()) {
5605 dispatchEntry = *dispatchEntryIt;
5606 connection->waitQueue.erase(dispatchEntryIt);
5607 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5608 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5609 if (!connection->responsive) {
5610 connection->responsive = isConnectionResponsive(*connection);
5611 if (connection->responsive) {
5612 // The connection was unresponsive, and now it's responsive.
5613 processConnectionResponsiveLocked(*connection);
5614 }
5615 }
5616 traceWaitQueueLength(*connection);
5617 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5618 connection->outboundQueue.push_front(dispatchEntry);
5619 traceOutboundQueueLength(*connection);
5620 } else {
5621 releaseDispatchEntry(dispatchEntry);
5622 }
5623 }
5624
5625 // Start the next dispatch cycle for this connection.
5626 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627}
5628
Prabir Pradhancef936d2021-07-21 16:17:52 +00005629void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5630 const sp<IBinder>& newToken) {
5631 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5632 scoped_unlock unlock(mLock);
5633 mPolicy->notifyFocusChanged(oldToken, newToken);
5634 };
5635 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636}
5637
Prabir Pradhancef936d2021-07-21 16:17:52 +00005638void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5639 auto command = [this, token, x, y]() REQUIRES(mLock) {
5640 scoped_unlock unlock(mLock);
5641 mPolicy->notifyDropWindow(token, x, y);
5642 };
5643 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005644}
5645
Prabir Pradhancef936d2021-07-21 16:17:52 +00005646void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5647 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5648 scoped_unlock unlock(mLock);
5649 mPolicy->notifyUntrustedTouch(obscuringPackage);
5650 };
5651 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005652}
5653
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005654void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5655 if (connection == nullptr) {
5656 LOG_ALWAYS_FATAL("Caller must check for nullness");
5657 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005658 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5659 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005660 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005661 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005662 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005663 return;
5664 }
5665 /**
5666 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5667 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5668 * has changed. This could cause newer entries to time out before the already dispatched
5669 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5670 * processes the events linearly. So providing information about the oldest entry seems to be
5671 * most useful.
5672 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005673 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005674 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5675 std::string reason =
5676 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005677 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005678 ns2ms(currentWait),
5679 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005680 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005681 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005682
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005683 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5684
5685 // Stop waking up for events on this connection, it is already unresponsive
5686 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005687}
5688
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005689void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5690 std::string reason =
5691 StringPrintf("%s does not have a focused window", application->getName().c_str());
5692 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005693
Prabir Pradhancef936d2021-07-21 16:17:52 +00005694 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5695 scoped_unlock unlock(mLock);
5696 mPolicy->notifyNoFocusedWindowAnr(application);
5697 };
5698 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005699}
5700
chaviw98318de2021-05-19 16:45:23 -05005701void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005702 const std::string& reason) {
5703 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5704 updateLastAnrStateLocked(windowLabel, reason);
5705}
5706
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005707void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5708 const std::string& reason) {
5709 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005710 updateLastAnrStateLocked(windowLabel, reason);
5711}
5712
5713void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5714 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005716 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 struct tm tm;
5718 localtime_r(&t, &tm);
5719 char timestr[64];
5720 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005721 mLastAnrState.clear();
5722 mLastAnrState += INDENT "ANR:\n";
5723 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005724 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5725 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005726 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727}
5728
Prabir Pradhancef936d2021-07-21 16:17:52 +00005729void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5730 KeyEntry& entry) {
5731 const KeyEvent event = createKeyEvent(entry);
5732 nsecs_t delay = 0;
5733 { // release lock
5734 scoped_unlock unlock(mLock);
5735 android::base::Timer t;
5736 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5737 entry.policyFlags);
5738 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5739 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5740 std::to_string(t.duration().count()).c_str());
5741 }
5742 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743
5744 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005745 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005746 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005747 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005749 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5750 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752}
5753
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005754void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005755 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5756 scoped_unlock unlock(mLock);
5757 mPolicy->notifyMonitorUnresponsive(pid, reason);
5758 };
5759 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005760}
5761
Prabir Pradhancef936d2021-07-21 16:17:52 +00005762void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005763 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005764 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5765 scoped_unlock unlock(mLock);
5766 mPolicy->notifyWindowUnresponsive(token, reason);
5767 };
5768 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005769}
5770
5771void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005772 auto command = [this, pid]() REQUIRES(mLock) {
5773 scoped_unlock unlock(mLock);
5774 mPolicy->notifyMonitorResponsive(pid);
5775 };
5776 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005777}
5778
Prabir Pradhancef936d2021-07-21 16:17:52 +00005779void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5780 auto command = [this, connectionToken]() REQUIRES(mLock) {
5781 scoped_unlock unlock(mLock);
5782 mPolicy->notifyWindowResponsive(connectionToken);
5783 };
5784 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005785}
5786
5787/**
5788 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5789 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5790 * command entry to the command queue.
5791 */
5792void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5793 std::string reason) {
5794 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5795 if (connection.monitor) {
5796 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5797 reason.c_str());
5798 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5799 if (!pid.has_value()) {
5800 ALOGE("Could not find unresponsive monitor for connection %s",
5801 connection.inputChannel->getName().c_str());
5802 return;
5803 }
5804 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5805 return;
5806 }
5807 // If not a monitor, must be a window
5808 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5809 reason.c_str());
5810 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5811}
5812
5813/**
5814 * Tell the policy that a connection has become responsive so that it can stop ANR.
5815 */
5816void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5817 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5818 if (connection.monitor) {
5819 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5820 if (!pid.has_value()) {
5821 ALOGE("Could not find responsive monitor for connection %s",
5822 connection.inputChannel->getName().c_str());
5823 return;
5824 }
5825 sendMonitorResponsiveCommandLocked(pid.value());
5826 return;
5827 }
5828 // If not a monitor, must be a window
5829 sendWindowResponsiveCommandLocked(connectionToken);
5830}
5831
Prabir Pradhancef936d2021-07-21 16:17:52 +00005832bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005833 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005834 KeyEntry& keyEntry, bool handled) {
5835 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005836 if (!handled) {
5837 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005838 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005839 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005840 return false;
5841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005843 // Get the fallback key state.
5844 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005845 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005846 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005847 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005848 connection->inputState.removeFallbackKey(originalKeyCode);
5849 }
5850
5851 if (handled || !dispatchEntry->hasForegroundTarget()) {
5852 // If the application handles the original key for which we previously
5853 // generated a fallback or if the window is not a foreground window,
5854 // then cancel the associated fallback key, if any.
5855 if (fallbackKeyCode != -1) {
5856 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005857 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5858 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5859 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5860 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5861 keyEntry.policyFlags);
5862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005863 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005864 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865
5866 mLock.unlock();
5867
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005868 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005869 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870
5871 mLock.lock();
5872
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005873 // Cancel the fallback key.
5874 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005876 "application handled the original non-fallback key "
5877 "or is no longer a foreground target, "
5878 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 options.keyCode = fallbackKeyCode;
5880 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005882 connection->inputState.removeFallbackKey(originalKeyCode);
5883 }
5884 } else {
5885 // If the application did not handle a non-fallback key, first check
5886 // that we are in a good state to perform unhandled key event processing
5887 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005888 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005890 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5891 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5892 "since this is not an initial down. "
5893 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5894 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5895 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005896 return false;
5897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005899 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005900 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5901 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5902 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5903 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5904 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005905 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005906
5907 mLock.unlock();
5908
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005909 bool fallback =
5910 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912
5913 mLock.lock();
5914
5915 if (connection->status != Connection::STATUS_NORMAL) {
5916 connection->inputState.removeFallbackKey(originalKeyCode);
5917 return false;
5918 }
5919
5920 // Latch the fallback keycode for this key on an initial down.
5921 // The fallback keycode cannot change at any other point in the lifecycle.
5922 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005924 fallbackKeyCode = event.getKeyCode();
5925 } else {
5926 fallbackKeyCode = AKEYCODE_UNKNOWN;
5927 }
5928 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5929 }
5930
5931 ALOG_ASSERT(fallbackKeyCode != -1);
5932
5933 // Cancel the fallback key if the policy decides not to send it anymore.
5934 // We will continue to dispatch the key to the policy but we will no
5935 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005936 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5937 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005938 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5939 if (fallback) {
5940 ALOGD("Unhandled key event: Policy requested to send key %d"
5941 "as a fallback for %d, but on the DOWN it had requested "
5942 "to send %d instead. Fallback canceled.",
5943 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5944 } else {
5945 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5946 "but on the DOWN it had requested to send %d. "
5947 "Fallback canceled.",
5948 originalKeyCode, fallbackKeyCode);
5949 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951
5952 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5953 "canceling fallback, policy no longer desires it");
5954 options.keyCode = fallbackKeyCode;
5955 synthesizeCancelationEventsForConnectionLocked(connection, options);
5956
5957 fallback = false;
5958 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005959 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005960 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961 }
5962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005964 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5965 {
5966 std::string msg;
5967 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5968 connection->inputState.getFallbackKeys();
5969 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5970 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5971 }
5972 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5973 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005975 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976
5977 if (fallback) {
5978 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005979 keyEntry.eventTime = event.getEventTime();
5980 keyEntry.deviceId = event.getDeviceId();
5981 keyEntry.source = event.getSource();
5982 keyEntry.displayId = event.getDisplayId();
5983 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5984 keyEntry.keyCode = fallbackKeyCode;
5985 keyEntry.scanCode = event.getScanCode();
5986 keyEntry.metaState = event.getMetaState();
5987 keyEntry.repeatCount = event.getRepeatCount();
5988 keyEntry.downTime = event.getDownTime();
5989 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005990
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005991 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5992 ALOGD("Unhandled key event: Dispatching fallback key. "
5993 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5994 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
5995 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005996 return true; // restart the event
5997 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005998 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5999 ALOGD("Unhandled key event: No fallback key.");
6000 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006001
6002 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006003 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006004 }
6005 }
6006 return false;
6007}
6008
Prabir Pradhancef936d2021-07-21 16:17:52 +00006009bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006010 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006011 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012 return false;
6013}
6014
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015void InputDispatcher::traceInboundQueueLengthLocked() {
6016 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006017 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 }
6019}
6020
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006021void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 if (ATRACE_ENABLED()) {
6023 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006024 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6025 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 }
6027}
6028
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006029void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030 if (ATRACE_ENABLED()) {
6031 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006032 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6033 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034 }
6035}
6036
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006037void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006038 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006040 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 dumpDispatchStateLocked(dump);
6042
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006043 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006044 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006045 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 }
6047}
6048
6049void InputDispatcher::monitor() {
6050 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006051 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006053 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006054}
6055
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006056/**
6057 * Wake up the dispatcher and wait until it processes all events and commands.
6058 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6059 * this method can be safely called from any thread, as long as you've ensured that
6060 * the work you are interested in completing has already been queued.
6061 */
6062bool InputDispatcher::waitForIdle() {
6063 /**
6064 * Timeout should represent the longest possible time that a device might spend processing
6065 * events and commands.
6066 */
6067 constexpr std::chrono::duration TIMEOUT = 100ms;
6068 std::unique_lock lock(mLock);
6069 mLooper->wake();
6070 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6071 return result == std::cv_status::no_timeout;
6072}
6073
Vishnu Naire798b472020-07-23 13:52:21 -07006074/**
6075 * Sets focus to the window identified by the token. This must be called
6076 * after updating any input window handles.
6077 *
6078 * Params:
6079 * request.token - input channel token used to identify the window that should gain focus.
6080 * request.focusedToken - the token that the caller expects currently to be focused. If the
6081 * specified token does not match the currently focused window, this request will be dropped.
6082 * If the specified focused token matches the currently focused window, the call will succeed.
6083 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6084 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6085 * when requesting the focus change. This determines which request gets
6086 * precedence if there is a focus change request from another source such as pointer down.
6087 */
Vishnu Nair958da932020-08-21 17:12:37 -07006088void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6089 { // acquire lock
6090 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006091 std::optional<FocusResolver::FocusChanges> changes =
6092 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6093 if (changes) {
6094 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006095 }
6096 } // release lock
6097 // Wake up poll loop since it may need to make new input dispatching choices.
6098 mLooper->wake();
6099}
6100
Vishnu Nairc519ff72021-01-21 08:23:08 -08006101void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6102 if (changes.oldFocus) {
6103 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006104 if (focusedInputChannel) {
6105 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6106 "focus left window");
6107 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006108 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006109 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006110 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006111 if (changes.newFocus) {
6112 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006113 }
6114
Prabir Pradhan99987712020-11-10 18:43:05 -08006115 // If a window has pointer capture, then it must have focus. We need to ensure that this
6116 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6117 // If the window loses focus before it loses pointer capture, then the window can be in a state
6118 // where it has pointer capture but not focus, violating the contract. Therefore we must
6119 // dispatch the pointer capture event before the focus event. Since focus events are added to
6120 // the front of the queue (above), we add the pointer capture event to the front of the queue
6121 // after the focus events are added. This ensures the pointer capture event ends up at the
6122 // front.
6123 disablePointerCaptureForcedLocked();
6124
Vishnu Nairc519ff72021-01-21 08:23:08 -08006125 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006126 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006127 }
6128}
Vishnu Nair958da932020-08-21 17:12:37 -07006129
Prabir Pradhan99987712020-11-10 18:43:05 -08006130void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006131 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006132 return;
6133 }
6134
6135 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6136
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006137 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006138 setPointerCaptureLocked(false);
6139 }
6140
6141 if (!mWindowTokenWithPointerCapture) {
6142 // No need to send capture changes because no window has capture.
6143 return;
6144 }
6145
6146 if (mPendingEvent != nullptr) {
6147 // Move the pending event to the front of the queue. This will give the chance
6148 // for the pending event to be dropped if it is a captured event.
6149 mInboundQueue.push_front(mPendingEvent);
6150 mPendingEvent = nullptr;
6151 }
6152
6153 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006154 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006155 mInboundQueue.push_front(std::move(entry));
6156}
6157
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006158void InputDispatcher::setPointerCaptureLocked(bool enable) {
6159 mCurrentPointerCaptureRequest.enable = enable;
6160 mCurrentPointerCaptureRequest.seq++;
6161 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006162 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006163 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006164 };
6165 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006166}
6167
Vishnu Nair599f1412021-06-21 10:39:58 -07006168void InputDispatcher::displayRemoved(int32_t displayId) {
6169 { // acquire lock
6170 std::scoped_lock _l(mLock);
6171 // Set an empty list to remove all handles from the specific display.
6172 setInputWindowsLocked(/* window handles */ {}, displayId);
6173 setFocusedApplicationLocked(displayId, nullptr);
6174 // Call focus resolver to clean up stale requests. This must be called after input windows
6175 // have been removed for the removed display.
6176 mFocusResolver.displayRemoved(displayId);
6177 } // release lock
6178
6179 // Wake up poll loop since it may need to make new input dispatching choices.
6180 mLooper->wake();
6181}
6182
chaviw15fab6f2021-06-07 14:15:52 -05006183void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6184 // The listener sends the windows as a flattened array. Separate the windows by display for
6185 // more convenient parsing.
6186 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6187
6188 for (const auto& info : windowInfos) {
6189 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6190 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6191 }
6192 setInputWindows(handlesPerDisplay);
6193}
6194
Garfield Tane84e6f92019-08-29 17:28:41 -07006195} // namespace android::inputdispatcher