blob: 92ba52c3f4c656461a65ffe15c27448bebc4e413 [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>
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080031#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000033#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010035#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
Michael Wright44753b12020-07-08 13:48:11 +010038#include <cerrno>
39#include <cinttypes>
40#include <climits>
41#include <cstddef>
42#include <ctime>
43#include <queue>
44#include <sstream>
45
46#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070047#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#define INDENT " "
50#define INDENT2 " "
51#define INDENT3 " "
52#define INDENT4 " "
53
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080054using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000055using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056using android::base::StringPrintf;
chaviw98318de2021-05-19 16:45:23 -050057using android::gui::FocusRequest;
58using android::gui::TouchOcclusionMode;
59using android::gui::WindowInfo;
60using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080061using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100062using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080063using android::os::InputEventInjectionResult;
64using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100065using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066
Garfield Tane84e6f92019-08-29 17:28:41 -070067namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080068
Prabir Pradhancef936d2021-07-21 16:17:52 +000069namespace {
70
Prabir Pradhan61a5d242021-07-26 16:41:09 +000071// Log detailed debug messages about each inbound event notification to the dispatcher.
72constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
73
74// Log detailed debug messages about each outbound event processed by the dispatcher.
75constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
76
77// Log debug messages about the dispatch cycle.
78constexpr bool DEBUG_DISPATCH_CYCLE = false;
79
80// Log debug messages about channel creation
81constexpr bool DEBUG_CHANNEL_CREATION = false;
82
83// Log debug messages about input event injection.
84constexpr bool DEBUG_INJECTION = false;
85
86// Log debug messages about input focus tracking.
87constexpr bool DEBUG_FOCUS = false;
88
89// Log debug messages about touch occlusion
90// STOPSHIP(b/169067926): Set to false
91constexpr bool DEBUG_TOUCH_OCCLUSION = true;
92
93// Log debug messages about the app switch latency optimization.
94constexpr bool DEBUG_APP_SWITCH = false;
95
96// Log debug messages about hover events.
97constexpr bool DEBUG_HOVER = false;
98
Prabir Pradhancef936d2021-07-21 16:17:52 +000099// Temporarily releases a held mutex for the lifetime of the instance.
100// Named to match std::scoped_lock
101class scoped_unlock {
102public:
103 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
104 ~scoped_unlock() { mMutex.lock(); }
105
106private:
107 std::mutex& mMutex;
108};
109
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700110// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
111// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000112bool isPerWindowInputRotationEnabled() {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700113 static const bool PER_WINDOW_INPUT_ROTATION =
Vadim Tryshev7719c7d2021-08-27 17:28:43 +0000114 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700115
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700116 return PER_WINDOW_INPUT_ROTATION;
117}
118
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119// Default input dispatching timeout if there is no focused application or paused window
120// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800121const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
122 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
123 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124
125// Amount of time to allow for all pending events to be processed when an app switch
126// key is on the way. This is used to preempt input dispatch and drop input events
127// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000128constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129
130// Amount of time to allow for an event to be dispatched (measured since its eventTime)
131// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000132constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134// 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 +0000135constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
136
137// Log a warning when an interception call takes longer than this to process.
138constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700140// Additional key latency in case a connection is still processing some motion events.
141// This will help with the case when a user touched a button that opens a new window,
142// and gives us the chance to dispatch the key to this new window.
143constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
144
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000146constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
147
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000148// Event log tags. See EventLogTags.logtags for reference
149constexpr int LOGTAG_INPUT_INTERACTION = 62000;
150constexpr int LOGTAG_INPUT_FOCUS = 62001;
151
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000152inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153 return systemTime(SYSTEM_TIME_MONOTONIC);
154}
155
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000156inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 return value ? "true" : "false";
158}
159
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000160inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000161 if (binder == nullptr) {
162 return "<null>";
163 }
164 return StringPrintf("%p", binder.get());
165}
166
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000167inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
169 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170}
171
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000172bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AKEY_EVENT_ACTION_DOWN:
175 case AKEY_EVENT_ACTION_UP:
176 return true;
177 default:
178 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 }
180}
181
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000182bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 ALOGE("Key event has invalid action code 0x%x", action);
185 return false;
186 }
187 return true;
188}
189
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000190bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700192 case AMOTION_EVENT_ACTION_DOWN:
193 case AMOTION_EVENT_ACTION_UP:
194 case AMOTION_EVENT_ACTION_CANCEL:
195 case AMOTION_EVENT_ACTION_MOVE:
196 case AMOTION_EVENT_ACTION_OUTSIDE:
197 case AMOTION_EVENT_ACTION_HOVER_ENTER:
198 case AMOTION_EVENT_ACTION_HOVER_MOVE:
199 case AMOTION_EVENT_ACTION_HOVER_EXIT:
200 case AMOTION_EVENT_ACTION_SCROLL:
201 return true;
202 case AMOTION_EVENT_ACTION_POINTER_DOWN:
203 case AMOTION_EVENT_ACTION_POINTER_UP: {
204 int32_t index = getMotionEventActionPointerIndex(action);
205 return index >= 0 && index < pointerCount;
206 }
207 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
208 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
209 return actionButton != 0;
210 default:
211 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213}
214
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000215int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500216 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
217}
218
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000219bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
220 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700221 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 ALOGE("Motion event has invalid action code 0x%x", action);
223 return false;
224 }
225 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000226 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700227 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 return false;
229 }
230 BitSet32 pointerIdBits;
231 for (size_t i = 0; i < pointerCount; i++) {
232 int32_t id = pointerProperties[i].id;
233 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700234 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
235 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 return false;
237 }
238 if (pointerIdBits.hasBit(id)) {
239 ALOGE("Motion event has duplicate pointer id %d", id);
240 return false;
241 }
242 pointerIdBits.markBit(id);
243 }
244 return true;
245}
246
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000247std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000249 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 }
251
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000252 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 bool first = true;
254 Region::const_iterator cur = region.begin();
255 Region::const_iterator const tail = region.end();
256 while (cur != tail) {
257 if (first) {
258 first = false;
259 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800260 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800262 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 cur++;
264 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000265 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266}
267
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000268std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500269 constexpr size_t maxEntries = 50; // max events to print
270 constexpr size_t skipBegin = maxEntries / 2;
271 const size_t skipEnd = queue.size() - maxEntries / 2;
272 // skip from maxEntries / 2 ... size() - maxEntries/2
273 // only print from 0 .. skipBegin and then from skipEnd .. size()
274
275 std::string dump;
276 for (size_t i = 0; i < queue.size(); i++) {
277 const DispatchEntry& entry = *queue[i];
278 if (i >= skipBegin && i < skipEnd) {
279 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
280 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
281 continue;
282 }
283 dump.append(INDENT4);
284 dump += entry.eventEntry->getDescription();
285 dump += StringPrintf(", seq=%" PRIu32
286 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
287 entry.seq, entry.targetFlags, entry.resolvedAction,
288 ns2ms(currentTime - entry.eventEntry->eventTime));
289 if (entry.deliveryTime != 0) {
290 // This entry was delivered, so add information on how long we've been waiting
291 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
292 }
293 dump.append("\n");
294 }
295 return dump;
296}
297
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700298/**
299 * Find the entry in std::unordered_map by key, and return it.
300 * If the entry is not found, return a default constructed entry.
301 *
302 * Useful when the entries are vectors, since an empty vector will be returned
303 * if the entry is not found.
304 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
305 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700306template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000307V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700308 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700309 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800310}
311
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000312bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700313 if (first == second) {
314 return true;
315 }
316
317 if (first == nullptr || second == nullptr) {
318 return false;
319 }
320
321 return first->getToken() == second->getToken();
322}
323
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000324bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000325 if (first == nullptr || second == nullptr) {
326 return false;
327 }
328 return first->applicationInfo.token != nullptr &&
329 first->applicationInfo.token == second->applicationInfo.token;
330}
331
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000332bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800333 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
334}
335
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000336std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
337 std::shared_ptr<EventEntry> eventEntry,
338 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900339 if (eventEntry->type == EventEntry::Type::MOTION) {
340 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700341 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
342 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900343 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700344 // Use identity transform for joystick and position-based (touchpad) events because they
345 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900346 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700347 1.0f /*globalScaleFactor*/,
Evan Rosky09576692021-07-01 12:22:09 -0700348 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700349 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900350 }
351 }
352
chaviw1ff3d1e2020-07-01 15:53:47 -0700353 if (inputTarget.useDefaultPointerTransform()) {
354 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700356 inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700357 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700358 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359 }
360
361 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
362 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
363
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700364 std::vector<PointerCoords> pointerCoords;
365 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 // Use the first pointer information to normalize all other pointers. This could be any pointer
368 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 // uses the transform for the normalized pointer.
370 const ui::Transform& firstPointerTransform =
371 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
372 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373
374 // Iterate through all pointers in the event to normalize against the first.
375 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
376 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
377 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700378 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379
380 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700381 // First, apply the current pointer's transform to update the coordinates into
382 // window space.
383 pointerCoords[pointerIndex].transform(currTransform);
384 // Next, apply the inverse transform of the normalized coordinates so the
385 // current coordinates are transformed into the normalized coordinate space.
386 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387 }
388
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700389 std::unique_ptr<MotionEntry> combinedMotionEntry =
390 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
391 motionEntry.deviceId, motionEntry.source,
392 motionEntry.displayId, motionEntry.policyFlags,
393 motionEntry.action, motionEntry.actionButton,
394 motionEntry.flags, motionEntry.metaState,
395 motionEntry.buttonState, motionEntry.classification,
396 motionEntry.edgeFlags, motionEntry.xPrecision,
397 motionEntry.yPrecision, motionEntry.xCursorPosition,
398 motionEntry.yCursorPosition, motionEntry.downTime,
399 motionEntry.pointerCount, motionEntry.pointerProperties,
400 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000401
402 if (motionEntry.injectionState) {
403 combinedMotionEntry->injectionState = motionEntry.injectionState;
404 combinedMotionEntry->injectionState->refCount += 1;
405 }
406
407 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700408 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700409 firstPointerTransform, inputTarget.globalScaleFactor,
Evan Rosky09576692021-07-01 12:22:09 -0700410 inputTarget.displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -0700411 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412 return dispatchEntry;
413}
414
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000415void addGestureMonitors(const std::vector<Monitor>& monitors,
416 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
417 float yOffset = 0) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700418 if (monitors.empty()) {
419 return;
420 }
421 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
422 for (const Monitor& monitor : monitors) {
423 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
424 }
425}
426
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000427status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
428 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700429 std::unique_ptr<InputChannel> uniqueServerChannel;
430 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
431
432 serverChannel = std::move(uniqueServerChannel);
433 return result;
434}
435
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500436template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000437bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500438 if (lhs == nullptr && rhs == nullptr) {
439 return true;
440 }
441 if (lhs == nullptr || rhs == nullptr) {
442 return false;
443 }
444 return *lhs == *rhs;
445}
446
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000447sp<IPlatformCompatNative> getCompatService() {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000448 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
449 if (service == nullptr) {
450 ALOGE("Failed to link to compat service");
451 return nullptr;
452 }
453 return interface_cast<IPlatformCompatNative>(service);
454}
455
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000456KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000457 KeyEvent event;
458 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
459 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
460 entry.repeatCount, entry.downTime, entry.eventTime);
461 return event;
462}
463
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000464std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000465 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
466 const sp<IBinder>& token) {
467 for (const auto& it : monitorsByDisplay) {
468 const std::vector<Monitor>& monitors = it.second;
469 for (const Monitor& monitor : monitors) {
470 if (monitor.inputChannel->getConnectionToken() == token) {
471 return monitor.pid;
472 }
473 }
474 }
475 return std::nullopt;
476}
477
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000478bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000479 // Do not keep track of gesture monitors. They receive every event and would disproportionately
480 // affect the statistics.
481 if (connection.monitor) {
482 return false;
483 }
484 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
485 if (!connection.responsive) {
486 return false;
487 }
488 return true;
489}
490
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000491bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000492 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
493 const int32_t& inputEventId = eventEntry.id;
494 if (inputEventId != dispatchEntry.resolvedEventId) {
495 // Event was transmuted
496 return false;
497 }
498 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
499 return false;
500 }
501 // Only track latency for events that originated from hardware
502 if (eventEntry.isSynthesized()) {
503 return false;
504 }
505 const EventEntry::Type& inputEventEntryType = eventEntry.type;
506 if (inputEventEntryType == EventEntry::Type::KEY) {
507 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
508 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
509 return false;
510 }
511 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
512 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
513 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
514 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
515 return false;
516 }
517 } else {
518 // Not a key or a motion
519 return false;
520 }
521 if (!shouldReportMetricsForConnection(connection)) {
522 return false;
523 }
524 return true;
525}
526
Prabir Pradhancef936d2021-07-21 16:17:52 +0000527/**
528 * Connection is responsive if it has no events in the waitQueue that are older than the
529 * current time.
530 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000531bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000532 const nsecs_t currentTime = now();
533 for (const DispatchEntry* entry : connection.waitQueue) {
534 if (entry->timeoutTime < currentTime) {
535 return false;
536 }
537 }
538 return true;
539}
540
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000541} // namespace
542
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543// --- InputDispatcher ---
544
Garfield Tan00f511d2019-06-12 16:55:40 -0700545InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
546 : mPolicy(policy),
547 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700548 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800549 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700550 mAppSwitchSawKeyDown(false),
551 mAppSwitchDueTime(LONG_LONG_MAX),
552 mNextUnblockedEvent(nullptr),
553 mDispatchEnabled(false),
554 mDispatchFrozen(false),
555 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800556 // mInTouchMode will be initialized by the WindowManager to the default device config.
557 // To avoid leaking stack in case that call never comes, and for tests,
558 // initialize it here anyways.
559 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100560 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000561 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800562 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000563 mLatencyAggregator(),
564 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000565 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800567 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568
Yi Kong9b14ac62018-07-17 13:48:38 -0700569 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
571 policy->getDispatcherConfiguration(&mConfig);
572}
573
574InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000575 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Prabir Pradhancef936d2021-07-21 16:17:52 +0000577 resetKeyRepeatLocked();
578 releasePendingEventLocked();
579 drainInboundQueueLocked();
580 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000582 while (!mConnectionsByToken.empty()) {
583 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000584 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
585 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 }
587}
588
chaviw15fab6f2021-06-07 14:15:52 -0500589void InputDispatcher::onFirstRef() {
590 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
591}
592
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700593status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700594 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595 return ALREADY_EXISTS;
596 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 mThread = std::make_unique<InputThread>(
598 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
599 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600}
601
602status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700603 if (mThread && mThread->isCallingThread()) {
604 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700605 return INVALID_OPERATION;
606 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700607 mThread.reset();
608 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputDispatcher::dispatchOnce() {
612 nsecs_t nextWakeupTime = LONG_LONG_MAX;
613 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800614 std::scoped_lock _l(mLock);
615 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616
617 // Run a dispatch loop if there are no pending commands.
618 // The dispatch loop might enqueue commands to run afterwards.
619 if (!haveCommandsLocked()) {
620 dispatchOnceInnerLocked(&nextWakeupTime);
621 }
622
623 // Run all pending commands if there are any.
624 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000625 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 nextWakeupTime = LONG_LONG_MIN;
627 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800628
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700629 // If we are still waiting for ack on some events,
630 // we might have to wake up earlier to check if an app is anr'ing.
631 const nsecs_t nextAnrCheck = processAnrsLocked();
632 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
633
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800634 // We are about to enter an infinitely long sleep, because we have no commands or
635 // pending or queued events
636 if (nextWakeupTime == LONG_LONG_MAX) {
637 mDispatcherEnteredIdle.notify_all();
638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 } // release lock
640
641 // Wait for callback or timeout or wake. (make sure we round up, not down)
642 nsecs_t currentTime = now();
643 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
644 mLooper->pollOnce(timeoutMillis);
645}
646
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700647/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500648 * Raise ANR if there is no focused window.
649 * Before the ANR is raised, do a final state check:
650 * 1. The currently focused application must be the same one we are waiting for.
651 * 2. Ensure we still don't have a focused window.
652 */
653void InputDispatcher::processNoFocusedWindowAnrLocked() {
654 // Check if the application that we are waiting for is still focused.
655 std::shared_ptr<InputApplicationHandle> focusedApplication =
656 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
657 if (focusedApplication == nullptr ||
658 focusedApplication->getApplicationToken() !=
659 mAwaitedFocusedApplication->getApplicationToken()) {
660 // Unexpected because we should have reset the ANR timer when focused application changed
661 ALOGE("Waited for a focused window, but focused application has already changed to %s",
662 focusedApplication->getName().c_str());
663 return; // The focused application has changed.
664 }
665
chaviw98318de2021-05-19 16:45:23 -0500666 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500667 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
668 if (focusedWindowHandle != nullptr) {
669 return; // We now have a focused window. No need for ANR.
670 }
671 onAnrLocked(mAwaitedFocusedApplication);
672}
673
674/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700675 * Check if any of the connections' wait queues have events that are too old.
676 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
677 * Return the time at which we should wake up next.
678 */
679nsecs_t InputDispatcher::processAnrsLocked() {
680 const nsecs_t currentTime = now();
681 nsecs_t nextAnrCheck = LONG_LONG_MAX;
682 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
683 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
684 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500685 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700686 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500687 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700688 return LONG_LONG_MIN;
689 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500690 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
692 }
693 }
694
695 // Check if any connection ANRs are due
696 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
697 if (currentTime < nextAnrCheck) { // most likely scenario
698 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
699 }
700
701 // If we reached here, we have an unresponsive connection.
702 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
703 if (connection == nullptr) {
704 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
705 return nextAnrCheck;
706 }
707 connection->responsive = false;
708 // Stop waking up for this unresponsive connection
709 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000710 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700711 return LONG_LONG_MIN;
712}
713
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500714std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500715 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500717 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700718 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500719 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700720}
721
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
723 nsecs_t currentTime = now();
724
Jeff Browndc5992e2014-04-11 01:27:26 -0700725 // Reset the key repeat timer whenever normal dispatch is suspended while the
726 // device is in a non-interactive state. This is to ensure that we abort a key
727 // repeat if the device is just coming out of sleep.
728 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 resetKeyRepeatLocked();
730 }
731
732 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
733 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100734 if (DEBUG_FOCUS) {
735 ALOGD("Dispatch frozen. Waiting some more.");
736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 return;
738 }
739
740 // Optimize latency of app switches.
741 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
742 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
743 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
744 if (mAppSwitchDueTime < *nextWakeupTime) {
745 *nextWakeupTime = mAppSwitchDueTime;
746 }
747
748 // Ready to start a new event.
749 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700750 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700751 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 if (isAppSwitchDue) {
753 // The inbound queue is empty so the app switch key we were waiting
754 // for will never arrive. Stop waiting for it.
755 resetPendingAppSwitchLocked(false);
756 isAppSwitchDue = false;
757 }
758
759 // Synthesize a key repeat if appropriate.
760 if (mKeyRepeatState.lastKeyEntry) {
761 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
762 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
763 } else {
764 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
765 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
766 }
767 }
768 }
769
770 // Nothing to do if there is no pending event.
771 if (!mPendingEvent) {
772 return;
773 }
774 } else {
775 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700776 mPendingEvent = mInboundQueue.front();
777 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 traceInboundQueueLengthLocked();
779 }
780
781 // Poke user activity for this event.
782 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700783 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 }
786
787 // Now we have an event to dispatch.
788 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700789 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700791 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700793 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700799 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 }
801
802 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700803 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700804 const ConfigurationChangedEntry& typedEntry =
805 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700807 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 break;
809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700812 const DeviceResetEntry& typedEntry =
813 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 break;
817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100819 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 std::shared_ptr<FocusEntry> typedEntry =
821 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100822 dispatchFocusLocked(currentTime, typedEntry);
823 done = true;
824 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
825 break;
826 }
827
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700828 case EventEntry::Type::TOUCH_MODE_CHANGED: {
829 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
830 dispatchTouchModeChangeLocked(currentTime, typedEntry);
831 done = true;
832 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
833 break;
834 }
835
Prabir Pradhan99987712020-11-10 18:43:05 -0800836 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
837 const auto typedEntry =
838 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
839 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
840 done = true;
841 break;
842 }
843
arthurhungb89ccb02020-12-30 16:19:01 +0800844 case EventEntry::Type::DRAG: {
845 std::shared_ptr<DragEntry> typedEntry =
846 std::static_pointer_cast<DragEntry>(mPendingEvent);
847 dispatchDragLocked(currentTime, typedEntry);
848 done = true;
849 break;
850 }
851
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700852 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700853 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700855 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 resetPendingAppSwitchLocked(true);
857 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700858 } else if (dropReason == DropReason::NOT_DROPPED) {
859 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 }
861 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700862 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700863 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
866 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700868 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 break;
870 }
871
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700872 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 std::shared_ptr<MotionEntry> motionEntry =
874 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
876 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700878 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
882 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700884 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 }
Chris Yef59a2f42020-10-16 12:55:26 -0700887
888 case EventEntry::Type::SENSOR: {
889 std::shared_ptr<SensorEntry> sensorEntry =
890 std::static_pointer_cast<SensorEntry>(mPendingEvent);
891 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
892 dropReason = DropReason::APP_SWITCH;
893 }
894 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
895 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
896 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
897 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
898 dropReason = DropReason::STALE;
899 }
900 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
901 done = true;
902 break;
903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905
906 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700907 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700908 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
Michael Wright3a981722015-06-10 15:26:13 +0100910 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911
912 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
915}
916
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700917/**
918 * Return true if the events preceding this incoming motion event should be dropped
919 * Return false otherwise (the default behaviour)
920 */
921bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700922 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700923 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700924
925 // Optimize case where the current application is unresponsive and the user
926 // decides to touch a window in a different application.
927 // If the application takes too long to catch up then we drop all events preceding
928 // the touch into the other window.
929 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 int32_t displayId = motionEntry.displayId;
931 int32_t x = static_cast<int32_t>(
932 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
933 int32_t y = static_cast<int32_t>(
934 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500935 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700936 findTouchedWindowAtLocked(displayId, x, y, nullptr);
937 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 touchedWindowHandle->getApplicationToken() !=
939 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700940 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700941 ALOGI("Pruning input queue because user touched a different application while waiting "
942 "for %s",
943 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700944 return true;
945 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946
947 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600948 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
950 sp<Connection> connection =
951 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000952 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700953 // This monitor could take more input. Drop all events preceding this
954 // event, so that gesture monitor could get a chance to receive the stream
955 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
956 "responsive gesture monitor that may handle the event",
957 mAwaitedFocusedApplication->getName().c_str());
958 return true;
959 }
960 }
961 }
962
963 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
964 // yet been processed by some connections, the dispatcher will wait for these motion
965 // events to be processed before dispatching the key event. This is because these motion events
966 // may cause a new window to be launched, which the user might expect to receive focus.
967 // To prevent waiting forever for such events, just send the key to the currently focused window
968 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
969 ALOGD("Received a new pointer down event, stop waiting for events to process and "
970 "just send the pending key event to the focused window.");
971 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700972 }
973 return false;
974}
975
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700977 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 mInboundQueue.push_back(std::move(newEntry));
979 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 traceInboundQueueLengthLocked();
981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700983 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 // Optimize app switch latency.
985 // If the application takes too long to catch up then we drop all events preceding
986 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700989 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700991 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000993 if (DEBUG_APP_SWITCH) {
994 ALOGD("App switch is pending!");
995 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700996 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700997 mAppSwitchSawKeyDown = false;
998 needWake = true;
999 }
1000 }
1001 }
1002 break;
1003 }
1004
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001005 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001006 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1007 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001008 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001012 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001013 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1014 break;
1015 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001016 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001017 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001018 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001019 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001020 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1021 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001022 // nothing to do
1023 break;
1024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 }
1026
1027 return needWake;
1028}
1029
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001030void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001031 // Do not store sensor event in recent queue to avoid flooding the queue.
1032 if (entry->type != EventEntry::Type::SENSOR) {
1033 mRecentQueue.push_back(entry);
1034 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001035 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001036 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
1038}
1039
chaviw98318de2021-05-19 16:45:23 -05001040sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1041 int32_t y, TouchState* touchState,
1042 bool addOutsideTargets,
1043 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001044 if (addOutsideTargets && touchState == nullptr) {
1045 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001048 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1049 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001050 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001051 continue;
1052 }
chaviw98318de2021-05-19 16:45:23 -05001053 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001055 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056
1057 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001058 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1059 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1060 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1062 // Found window.
1063 return windowHandle;
1064 }
1065 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001066
chaviw98318de2021-05-19 16:45:23 -05001067 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001068 touchState->addOrUpdateWindow(windowHandle,
1069 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1070 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001075 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
Garfield Tane84e6f92019-08-29 17:28:41 -07001078std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001079 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001080 std::vector<TouchedMonitor> touchedMonitors;
1081
1082 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1083 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001084 return touchedMonitors;
1085}
1086
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001087void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 const char* reason;
1089 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001090 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001091 if (DEBUG_INBOUND_EVENT_DETAILS) {
1092 ALOGD("Dropped event because policy consumed it.");
1093 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 reason = "inbound event was dropped because the policy consumed it";
1095 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 case DropReason::DISABLED:
1097 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 ALOGI("Dropped event because input dispatch is disabled.");
1099 }
1100 reason = "inbound event was dropped because input dispatch is disabled";
1101 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001102 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 ALOGI("Dropped event because of pending overdue app switch.");
1104 reason = "inbound event was dropped because of pending overdue app switch";
1105 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001106 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001107 ALOGI("Dropped event because the current application is not responding and the user "
1108 "has started interacting with a different application.");
1109 reason = "inbound event was dropped because the current application is not responding "
1110 "and the user has started interacting with a different application";
1111 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001112 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 ALOGI("Dropped event because it is stale.");
1114 reason = "inbound event was dropped because it is stale";
1115 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001116 case DropReason::NO_POINTER_CAPTURE:
1117 ALOGI("Dropped event because there is no window with Pointer Capture.");
1118 reason = "inbound event was dropped because there is no window with Pointer Capture";
1119 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001120 case DropReason::NOT_DROPPED: {
1121 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 }
1125
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001126 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001127 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1129 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001133 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1134 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1136 synthesizeCancelationEventsForAllConnectionsLocked(options);
1137 } else {
1138 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1139 synthesizeCancelationEventsForAllConnectionsLocked(options);
1140 }
1141 break;
1142 }
Chris Yef59a2f42020-10-16 12:55:26 -07001143 case EventEntry::Type::SENSOR: {
1144 break;
1145 }
arthurhungb89ccb02020-12-30 16:19:01 +08001146 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1147 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001148 break;
1149 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001150 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001151 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 case EventEntry::Type::CONFIGURATION_CHANGED:
1153 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001154 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001155 break;
1156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158}
1159
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001160static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1162 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163}
1164
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001165bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1166 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1167 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1168 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169}
1170
1171bool InputDispatcher::isAppSwitchPendingLocked() {
1172 return mAppSwitchDueTime != LONG_LONG_MAX;
1173}
1174
1175void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1176 mAppSwitchDueTime = LONG_LONG_MAX;
1177
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001178 if (DEBUG_APP_SWITCH) {
1179 if (handled) {
1180 ALOGD("App switch has arrived.");
1181 } else {
1182 ALOGD("App switch was abandoned.");
1183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185}
1186
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001188 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189}
1190
Prabir Pradhancef936d2021-07-21 16:17:52 +00001191bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 return false;
1194 }
1195
1196 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001197 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001198 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001199 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1200 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001201 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 return true;
1203}
1204
Prabir Pradhancef936d2021-07-21 16:17:52 +00001205void InputDispatcher::postCommandLocked(Command&& command) {
1206 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207}
1208
1209void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001210 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001212 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 releaseInboundEventLocked(entry);
1214 }
1215 traceInboundQueueLengthLocked();
1216}
1217
1218void InputDispatcher::releasePendingEventLocked() {
1219 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001221 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223}
1224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001227 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001228 if (DEBUG_DISPATCH_CYCLE) {
1229 ALOGD("Injected inbound event was dropped.");
1230 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001234 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
1236 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237}
1238
1239void InputDispatcher::resetKeyRepeatLocked() {
1240 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001241 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 }
1243}
1244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1246 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Michael Wright2e732952014-09-24 13:26:59 -07001248 uint32_t policyFlags = entry->policyFlags &
1249 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 std::shared_ptr<KeyEntry> newEntry =
1252 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1253 entry->source, entry->displayId, policyFlags, entry->action,
1254 entry->flags, entry->keyCode, entry->scanCode,
1255 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 newEntry->syntheticRepeat = true;
1258 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261}
1262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001265 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1266 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268
1269 // Reset key repeating in case a keyboard device was added or removed or something.
1270 resetKeyRepeatLocked();
1271
1272 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001273 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1274 scoped_unlock unlock(mLock);
1275 mPolicy->notifyConfigurationChanged(eventTime);
1276 };
1277 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 return true;
1279}
1280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1282 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001283 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1284 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1285 entry.deviceId);
1286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
liushenxiang42232912021-05-21 20:24:09 +08001288 // Reset key repeating in case a keyboard device was disabled or enabled.
1289 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1290 resetKeyRepeatLocked();
1291 }
1292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 synthesizeCancelationEventsForAllConnectionsLocked(options);
1296 return true;
1297}
1298
Vishnu Nairad321cd2020-08-20 16:40:21 -07001299void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001300 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001301 if (mPendingEvent != nullptr) {
1302 // Move the pending event to the front of the queue. This will give the chance
1303 // for the pending event to get dispatched to the newly focused window
1304 mInboundQueue.push_front(mPendingEvent);
1305 mPendingEvent = nullptr;
1306 }
1307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308 std::unique_ptr<FocusEntry> focusEntry =
1309 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1310 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001311
1312 // This event should go to the front of the queue, but behind all other focus events
1313 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001315 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316 [](const std::shared_ptr<EventEntry>& event) {
1317 return event->type == EventEntry::Type::FOCUS;
1318 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001319
1320 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001322}
1323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001325 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001326 if (channel == nullptr) {
1327 return; // Window has gone away
1328 }
1329 InputTarget target;
1330 target.inputChannel = channel;
1331 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1332 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001333 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1334 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001335 std::string reason = std::string("reason=").append(entry->reason);
1336 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001337 dispatchEventLocked(currentTime, entry, {target});
1338}
1339
Prabir Pradhan99987712020-11-10 18:43:05 -08001340void InputDispatcher::dispatchPointerCaptureChangedLocked(
1341 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1342 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001343 dropReason = DropReason::NOT_DROPPED;
1344
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001346 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001347
1348 if (entry->pointerCaptureRequest.enable) {
1349 // Enable Pointer Capture.
1350 if (haveWindowWithPointerCapture &&
1351 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1352 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1353 "to the window.");
1354 }
1355 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 // This can happen if a window requests capture and immediately releases capture.
1357 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001358 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001359 return;
1360 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001361 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1362 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1363 return;
1364 }
1365
Vishnu Nairc519ff72021-01-21 08:23:08 -08001366 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001367 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1368 mWindowTokenWithPointerCapture = token;
1369 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001370 // Disable Pointer Capture.
1371 // We do not check if the sequence number matches for requests to disable Pointer Capture
1372 // for two reasons:
1373 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1374 // to disable capture with the same sequence number: one generated by
1375 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1376 // Capture being disabled in InputReader.
1377 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1378 // actual Pointer Capture state that affects events being generated by input devices is
1379 // in InputReader.
1380 if (!haveWindowWithPointerCapture) {
1381 // Pointer capture was already forcefully disabled because of focus change.
1382 dropReason = DropReason::NOT_DROPPED;
1383 return;
1384 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001385 token = mWindowTokenWithPointerCapture;
1386 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001387 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001388 setPointerCaptureLocked(false);
1389 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 }
1391
1392 auto channel = getInputChannelLocked(token);
1393 if (channel == nullptr) {
1394 // Window has gone away, clean up Pointer Capture state.
1395 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001396 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001397 setPointerCaptureLocked(false);
1398 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001399 return;
1400 }
1401 InputTarget target;
1402 target.inputChannel = channel;
1403 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1404 entry->dispatchInProgress = true;
1405 dispatchEventLocked(currentTime, entry, {target});
1406
1407 dropReason = DropReason::NOT_DROPPED;
1408}
1409
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001410void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1411 const std::shared_ptr<TouchModeEntry>& entry) {
1412 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1413 getWindowHandlesLocked(mFocusedDisplayId);
1414 if (windowHandles.empty()) {
1415 return;
1416 }
1417 const std::vector<InputTarget> inputTargets =
1418 getInputTargetsFromWindowHandlesLocked(windowHandles);
1419 if (inputTargets.empty()) {
1420 return;
1421 }
1422 entry->dispatchInProgress = true;
1423 dispatchEventLocked(currentTime, entry, inputTargets);
1424}
1425
1426std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1427 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1428 std::vector<InputTarget> inputTargets;
1429 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1430 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1431 const sp<IBinder>& token = handle->getToken();
1432 if (token == nullptr) {
1433 continue;
1434 }
1435 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1436 if (channel == nullptr) {
1437 continue; // Window has gone away
1438 }
1439 InputTarget target;
1440 target.inputChannel = channel;
1441 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1442 inputTargets.push_back(target);
1443 }
1444 return inputTargets;
1445}
1446
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001447bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001448 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 if (!entry->dispatchInProgress) {
1451 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1452 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1453 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1454 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001455 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 // We have seen two identical key downs in a row which indicates that the device
1457 // driver is automatically generating key repeats itself. We take note of the
1458 // repeat here, but we disable our own next key repeat timer since it is clear that
1459 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001460 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1461 // Make sure we don't get key down from a different device. If a different
1462 // device Id has same key pressed down, the new device Id will replace the
1463 // current one to hold the key repeat with repeat count reset.
1464 // In the future when got a KEY_UP on the device id, drop it and do not
1465 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1467 resetKeyRepeatLocked();
1468 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1469 } else {
1470 // Not a repeat. Save key down state in case we do see a repeat later.
1471 resetKeyRepeatLocked();
1472 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1473 }
1474 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001475 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1476 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001477 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001478 if (DEBUG_INBOUND_EVENT_DETAILS) {
1479 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1480 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 resetKeyRepeatLocked();
1483 }
1484
1485 if (entry->repeatCount == 1) {
1486 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1487 } else {
1488 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1489 }
1490
1491 entry->dispatchInProgress = true;
1492
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001493 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 }
1495
1496 // Handle case where the policy asked us to try again later last time.
1497 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1498 if (currentTime < entry->interceptKeyWakeupTime) {
1499 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1500 *nextWakeupTime = entry->interceptKeyWakeupTime;
1501 }
1502 return false; // wait until next wakeup
1503 }
1504 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1505 entry->interceptKeyWakeupTime = 0;
1506 }
1507
1508 // Give the policy a chance to intercept the key.
1509 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1510 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001511 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001512 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001513
1514 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1515 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1516 };
1517 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 return false; // wait for the command to run
1519 } else {
1520 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1521 }
1522 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001523 if (*dropReason == DropReason::NOT_DROPPED) {
1524 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526 }
1527
1528 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001529 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001530 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1532 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001533 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 return true;
1535 }
1536
1537 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001538 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001540 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001541 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 return false;
1543 }
1544
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001545 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001546 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 return true;
1548 }
1549
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001550 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001551 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552
1553 // Dispatch the key.
1554 dispatchEventLocked(currentTime, entry, inputTargets);
1555 return true;
1556}
1557
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001558void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001559 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1560 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1561 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1562 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1563 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1564 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1565 entry.metaState, entry.repeatCount, entry.downTime);
1566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567}
1568
Prabir Pradhancef936d2021-07-21 16:17:52 +00001569void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1570 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001571 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001572 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1573 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1574 "source=0x%x, sensorType=%s",
1575 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1576 NamedEnum::string(entry->sensorType).c_str());
1577 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001578 auto command = [this, entry]() REQUIRES(mLock) {
1579 scoped_unlock unlock(mLock);
1580
1581 if (entry->accuracyChanged) {
1582 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1583 }
1584 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1585 entry->hwTimestamp, entry->values);
1586 };
1587 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001588}
1589
1590bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001591 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1592 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1593 NamedEnum::string(sensorType).c_str());
1594 }
Chris Yef59a2f42020-10-16 12:55:26 -07001595 { // acquire lock
1596 std::scoped_lock _l(mLock);
1597
1598 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1599 std::shared_ptr<EventEntry> entry = *it;
1600 if (entry->type == EventEntry::Type::SENSOR) {
1601 it = mInboundQueue.erase(it);
1602 releaseInboundEventLocked(entry);
1603 }
1604 }
1605 }
1606 return true;
1607}
1608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001609bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001611 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001613 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 entry->dispatchInProgress = true;
1615
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001616 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 }
1618
1619 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001620 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001621 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001622 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1623 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 return true;
1625 }
1626
1627 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1628
1629 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001630 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631
1632 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001633 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 if (isPointerEvent) {
1635 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001636 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001637 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001638 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 } else {
1640 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001641 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001642 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001644 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 return false;
1646 }
1647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001648 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001649 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001650 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1651 return true;
1652 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001653 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001654 CancelationOptions::Mode mode(isPointerEvent
1655 ? CancelationOptions::CANCEL_POINTER_EVENTS
1656 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1657 CancelationOptions options(mode, "input event injection failed");
1658 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 return true;
1660 }
1661
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001662 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001663 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
1665 // Dispatch the motion.
1666 if (conflictingPointerActions) {
1667 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 synthesizeCancelationEventsForAllConnectionsLocked(options);
1670 }
1671 dispatchEventLocked(currentTime, entry, inputTargets);
1672 return true;
1673}
1674
chaviw98318de2021-05-19 16:45:23 -05001675void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001676 bool isExiting, const MotionEntry& motionEntry) {
1677 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1678 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1679 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1680 PointerCoords pointerCoords;
1681 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1682 pointerCoords.transform(windowHandle->getInfo()->transform);
1683
1684 std::unique_ptr<DragEntry> dragEntry =
1685 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1686 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1687 pointerCoords.getY());
1688
1689 enqueueInboundEventLocked(std::move(dragEntry));
1690}
1691
1692void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1693 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1694 if (channel == nullptr) {
1695 return; // Window has gone away
1696 }
1697 InputTarget target;
1698 target.inputChannel = channel;
1699 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1700 entry->dispatchInProgress = true;
1701 dispatchEventLocked(currentTime, entry, {target});
1702}
1703
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001704void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001705 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1706 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1707 ", policyFlags=0x%x, "
1708 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1709 "metaState=0x%x, buttonState=0x%x,"
1710 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1711 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1712 entry.policyFlags, entry.action, entry.actionButton, entry.flags, entry.metaState,
1713 entry.buttonState, entry.edgeFlags, entry.xPrecision, entry.yPrecision,
1714 entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001716 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1717 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1718 "x=%f, y=%f, pressure=%f, size=%f, "
1719 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1720 "orientation=%f",
1721 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1722 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1723 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1724 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1725 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1726 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1727 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1728 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1729 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1730 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733}
1734
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001735void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1736 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001737 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001738 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001739 if (DEBUG_DISPATCH_CYCLE) {
1740 ALOGD("dispatchEventToCurrentInputTargets");
1741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001743 updateInteractionTokensLocked(*eventEntry, inputTargets);
1744
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1746
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001749 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001750 sp<Connection> connection =
1751 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001752 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001753 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001755 if (DEBUG_FOCUS) {
1756 ALOGD("Dropping event delivery to target with channel '%s' because it "
1757 "is no longer registered with the input dispatcher.",
1758 inputTarget.inputChannel->getName().c_str());
1759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 }
1761 }
1762}
1763
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1765 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1766 // If the policy decides to close the app, we will get a channel removal event via
1767 // unregisterInputChannel, and will clean up the connection that way. We are already not
1768 // sending new pointers to the connection when it blocked, but focused events will continue to
1769 // pile up.
1770 ALOGW("Canceling events for %s because it is unresponsive",
1771 connection->inputChannel->getName().c_str());
1772 if (connection->status == Connection::STATUS_NORMAL) {
1773 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1774 "application not responding");
1775 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 }
1777}
1778
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001779void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001780 if (DEBUG_FOCUS) {
1781 ALOGD("Resetting ANR timeouts.");
1782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783
1784 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001785 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001786 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787}
1788
Tiger Huang721e26f2018-07-24 22:26:19 +08001789/**
1790 * Get the display id that the given event should go to. If this event specifies a valid display id,
1791 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1792 * Focused display is the display that the user most recently interacted with.
1793 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001794int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001795 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001797 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001798 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1799 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 break;
1801 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001802 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001803 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1804 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 break;
1806 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001807 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001808 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001809 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001810 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001811 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001812 case EventEntry::Type::SENSOR:
1813 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001814 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001815 return ADISPLAY_ID_NONE;
1816 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001817 }
1818 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1819}
1820
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1822 const char* focusedWindowName) {
1823 if (mAnrTracker.empty()) {
1824 // already processed all events that we waited for
1825 mKeyIsWaitingForEventsTimeout = std::nullopt;
1826 return false;
1827 }
1828
1829 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1830 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001831 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001832 mKeyIsWaitingForEventsTimeout = currentTime +
1833 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1834 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001835 return true;
1836 }
1837
1838 // We still have pending events, and already started the timer
1839 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1840 return true; // Still waiting
1841 }
1842
1843 // Waited too long, and some connection still hasn't processed all motions
1844 // Just send the key to the focused window
1845 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1846 focusedWindowName);
1847 mKeyIsWaitingForEventsTimeout = std::nullopt;
1848 return false;
1849}
1850
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1852 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1853 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001854 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855
Tiger Huang721e26f2018-07-24 22:26:19 +08001856 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001857 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001858 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001859 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1860
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 // If there is no currently focused window and no focused application
1862 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001863 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1864 ALOGI("Dropping %s event because there is no focused window or focused application in "
1865 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001866 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001867 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
1869
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001870 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1871 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1872 // start interacting with another application via touch (app switch). This code can be removed
1873 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1874 // an app is expected to have a focused window.
1875 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1876 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1877 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001878 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1879 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1880 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001882 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001883 ALOGW("Waiting because no window has focus but %s may eventually add a "
1884 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001885 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001886 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001887 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1889 // Already raised ANR. Drop the event
1890 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001891 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 } else {
1894 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001896 }
1897 }
1898
1899 // we have a valid, non-null focused window
1900 resetNoFocusedWindowTimeoutLocked();
1901
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001903 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 }
1906
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 if (focusedWindowHandle->getInfo()->paused) {
1908 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910 }
1911
1912 // If the event is a key event, then we must wait for all previous events to
1913 // complete before delivering it because previous events may have the
1914 // side-effect of transferring focus to a different window and we want to
1915 // ensure that the following keys are sent to the new window.
1916 //
1917 // Suppose the user touches a button in a window then immediately presses "A".
1918 // If the button causes a pop-up window to appear then we want to ensure that
1919 // the "A" key is delivered to the new pop-up window. This is because users
1920 // often anticipate pending UI changes when typing on a keyboard.
1921 // To obtain this behavior, we must serialize key events with respect to all
1922 // prior input events.
1923 if (entry.type == EventEntry::Type::KEY) {
1924 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1925 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001926 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
1929
1930 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001931 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001932 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1933 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934
1935 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937}
1938
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001939/**
1940 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1941 * that are currently unresponsive.
1942 */
1943std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1944 const std::vector<TouchedMonitor>& monitors) const {
1945 std::vector<TouchedMonitor> responsiveMonitors;
1946 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1947 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1948 sp<Connection> connection = getConnectionLocked(
1949 monitor.monitor.inputChannel->getConnectionToken());
1950 if (connection == nullptr) {
1951 ALOGE("Could not find connection for monitor %s",
1952 monitor.monitor.inputChannel->getName().c_str());
1953 return false;
1954 }
1955 if (!connection->responsive) {
1956 ALOGW("Unresponsive monitor %s will not get the new gesture",
1957 connection->inputChannel->getName().c_str());
1958 return false;
1959 }
1960 return true;
1961 });
1962 return responsiveMonitors;
1963}
1964
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1966 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1967 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001968 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 enum InjectionPermission {
1970 INJECTION_PERMISSION_UNKNOWN,
1971 INJECTION_PERMISSION_GRANTED,
1972 INJECTION_PERMISSION_DENIED
1973 };
1974
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 // For security reasons, we defer updating the touch state until we are sure that
1976 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001977 int32_t displayId = entry.displayId;
1978 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1980
1981 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001982 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001984 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1985 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001987 // Copy current touch state into tempTouchState.
1988 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1989 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001990 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001992 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1993 mTouchStatesByDisplay.find(displayId);
1994 if (oldStateIt != mTouchStatesByDisplay.end()) {
1995 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001997 }
1998
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 bool isSplit = tempTouchState.split;
2000 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2001 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2002 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2004 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2005 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2006 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2007 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002008 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 bool wrongDevice = false;
2010 if (newGesture) {
2011 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002012 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002013 ALOGI("Dropping event because a pointer for a different device is already down "
2014 "in display %" PRId32,
2015 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002016 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002017 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 switchedDevice = false;
2019 wrongDevice = true;
2020 goto Failed;
2021 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002022 tempTouchState.reset();
2023 tempTouchState.down = down;
2024 tempTouchState.deviceId = entry.deviceId;
2025 tempTouchState.source = entry.source;
2026 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002028 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002029 ALOGI("Dropping move event because a pointer for a different device is already active "
2030 "in display %" PRId32,
2031 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002032 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002033 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002034 switchedDevice = false;
2035 wrongDevice = true;
2036 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 }
2038
2039 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2040 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2041
Garfield Tan00f511d2019-06-12 16:55:40 -07002042 int32_t x;
2043 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002045 // Always dispatch mouse events to cursor position.
2046 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002047 x = int32_t(entry.xCursorPosition);
2048 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002049 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002050 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2051 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002052 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002054 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2055 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002056
2057 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002058 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 if (newTouchedWindowHandle != nullptr &&
2063 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002064 // New window supports splitting, but we should never split mouse events.
2065 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 } else if (isSplit) {
2067 // New window does not support splitting but we have already split events.
2068 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002069 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
2071
2072 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002073 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002075 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002076 }
2077
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2079 ALOGI("Not sending touch event to %s because it is paused",
2080 newTouchedWindowHandle->getName().c_str());
2081 newTouchedWindowHandle = nullptr;
2082 }
2083
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002084 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002086 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2087 if (!isResponsive) {
2088 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2090 newTouchedWindowHandle = nullptr;
2091 }
2092 }
2093
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002094 // Drop events that can't be trusted due to occlusion
2095 if (newTouchedWindowHandle != nullptr &&
2096 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2097 TouchOcclusionInfo occlusionInfo =
2098 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002099 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002100 if (DEBUG_TOUCH_OCCLUSION) {
2101 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2102 for (const auto& log : occlusionInfo.debugInfo) {
2103 ALOGD("%s", log.c_str());
2104 }
2105 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002106 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002107 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2108 ALOGW("Dropping untrusted touch event due to %s/%d",
2109 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2110 newTouchedWindowHandle = nullptr;
2111 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002112 }
2113 }
2114
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002115 // Also don't send the new touch event to unresponsive gesture monitors
2116 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2117
Michael Wright3dd60e22019-03-27 22:06:44 +00002118 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2119 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 "(%d, %d) in display %" PRId32 ".",
2121 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002122 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002123 goto Failed;
2124 }
2125
2126 if (newTouchedWindowHandle != nullptr) {
2127 // Set target flags.
2128 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2129 if (isSplit) {
2130 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002132 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2133 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2134 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2135 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2136 }
2137
2138 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002139 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2140 newHoverWindowHandle = nullptr;
2141 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002142 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 }
2144
2145 // Update the temporary touch state.
2146 BitSet32 pointerIds;
2147 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002148 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 pointerIds.markBit(pointerId);
2150 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002151 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002154 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 } else {
2156 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2157
2158 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002159 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002160 if (DEBUG_FOCUS) {
2161 ALOGD("Dropping event because the pointer is not down or we previously "
2162 "dropped the pointer down event in display %" PRId32,
2163 displayId);
2164 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002165 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 goto Failed;
2167 }
2168
arthurhung6d4bed92021-03-17 11:59:33 +08002169 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002170
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2175 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176
chaviw98318de2021-05-19 16:45:23 -05002177 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002179 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2181 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002182 if (DEBUG_FOCUS) {
2183 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2184 oldTouchedWindowHandle->getName().c_str(),
2185 newTouchedWindowHandle->getName().c_str(), displayId);
2186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2189 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2190 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191
2192 // Make a slippery entrance into the new window.
2193 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2194 isSplit = true;
2195 }
2196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 int32_t targetFlags =
2198 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 if (isSplit) {
2200 targetFlags |= InputTarget::FLAG_SPLIT;
2201 }
2202 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2203 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002204 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2205 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 }
2207
2208 BitSet32 pointerIds;
2209 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002210 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
2214 }
2215 }
2216
2217 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002218 // Let the previous window know that the hover sequence is over, unless we already did it
2219 // when dispatching it as is to newTouchedWindowHandle.
2220 if (mLastHoverWindowHandle != nullptr &&
2221 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2222 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002223 if (DEBUG_HOVER) {
2224 ALOGD("Sending hover exit event to window %s.",
2225 mLastHoverWindowHandle->getName().c_str());
2226 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2228 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Garfield Tandf26e862020-07-01 20:18:19 -07002231 // Let the new window know that the hover sequence is starting, unless we already did it
2232 // when dispatching it as is to newTouchedWindowHandle.
2233 if (newHoverWindowHandle != nullptr &&
2234 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2235 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002236 if (DEBUG_HOVER) {
2237 ALOGD("Sending hover enter event to window %s.",
2238 newHoverWindowHandle->getName().c_str());
2239 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002240 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2241 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2242 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 }
2244 }
2245
2246 // Check permission to inject into all touched foreground windows and ensure there
2247 // is at least one touched foreground window.
2248 {
2249 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2252 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002253 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002254 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 injectionPermission = INJECTION_PERMISSION_DENIED;
2256 goto Failed;
2257 }
2258 }
2259 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002260 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002261 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002262 ALOGI("Dropping event because there is no touched foreground window in display "
2263 "%" PRId32 " or gesture monitor to receive it.",
2264 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002265 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 goto Failed;
2267 }
2268
2269 // Permission granted to injection into all touched foreground windows.
2270 injectionPermission = INJECTION_PERMISSION_GRANTED;
2271 }
2272
2273 // Check whether windows listening for outside touches are owned by the same UID. If it is
2274 // set the policy flag that we will not reveal coordinate information to this window.
2275 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002276 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002277 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 if (foregroundWindowHandle) {
2279 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002281 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002282 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2283 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2284 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002285 InputTarget::FLAG_ZERO_COORDS,
2286 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
2289 }
2290 }
2291 }
2292
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 // If this is the first pointer going down and the touched window has a wallpaper
2294 // then also add the touched wallpaper windows so they are locked in for the duration
2295 // of the touch gesture.
2296 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2297 // engine only supports touch events. We would need to add a mechanism similar
2298 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2299 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002300 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002301 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002302 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002303 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002304 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002305 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2306 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002308 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002309 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 .addOrUpdateWindow(windowHandle,
2311 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2312 InputTarget::
2313 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2314 InputTarget::FLAG_DISPATCH_AS_IS,
2315 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317 }
2318 }
2319 }
2320
2321 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002322 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002324 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002326 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002329 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002330 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002332 }
2333
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 // Drop the outside or hover touch windows since we will not care about them
2335 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
2338Failed:
2339 // Check injection permission once and for all.
2340 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002341 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 injectionPermission = INJECTION_PERMISSION_GRANTED;
2343 } else {
2344 injectionPermission = INJECTION_PERMISSION_DENIED;
2345 }
2346 }
2347
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002348 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2349 return injectionResult;
2350 }
2351
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002353 if (!wrongDevice) {
2354 if (switchedDevice) {
2355 if (DEBUG_FOCUS) {
2356 ALOGD("Conflicting pointer actions: Switched to a different device.");
2357 }
2358 *outConflictingPointerActions = true;
2359 }
2360
2361 if (isHoverAction) {
2362 // Started hovering, therefore no longer down.
2363 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002364 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002365 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2366 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 *outConflictingPointerActions = true;
2369 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002370 tempTouchState.reset();
2371 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2372 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2373 tempTouchState.deviceId = entry.deviceId;
2374 tempTouchState.source = entry.source;
2375 tempTouchState.displayId = displayId;
2376 }
2377 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2378 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2379 // All pointers up or canceled.
2380 tempTouchState.reset();
2381 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2382 // First pointer went down.
2383 if (oldState && oldState->down) {
2384 if (DEBUG_FOCUS) {
2385 ALOGD("Conflicting pointer actions: Down received while already down.");
2386 }
2387 *outConflictingPointerActions = true;
2388 }
2389 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2390 // One pointer went up.
2391 if (isSplit) {
2392 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2393 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002395 for (size_t i = 0; i < tempTouchState.windows.size();) {
2396 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2397 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2398 touchedWindow.pointerIds.clearBit(pointerId);
2399 if (touchedWindow.pointerIds.isEmpty()) {
2400 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2401 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002404 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002406 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002407 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002408
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002409 // Save changes unless the action was scroll in which case the temporary touch
2410 // state was only valid for this one action.
2411 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2412 if (tempTouchState.displayId >= 0) {
2413 mTouchStatesByDisplay[displayId] = tempTouchState;
2414 } else {
2415 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002419 // Update hover state.
2420 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 return injectionResult;
2424}
2425
arthurhung6d4bed92021-03-17 11:59:33 +08002426void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002427 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002428 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002429 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002430 if (dropWindow) {
2431 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002432 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002433 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002434 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002435 }
2436 mDragState.reset();
2437}
2438
2439void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2440 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002441 return;
2442 }
2443
arthurhung6d4bed92021-03-17 11:59:33 +08002444 if (!mDragState->isStartDrag) {
2445 mDragState->isStartDrag = true;
2446 mDragState->isStylusButtonDownAtStart =
2447 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2448 }
2449
arthurhungb89ccb02020-12-30 16:19:01 +08002450 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2451 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2452 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2453 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002454 // Handle the special case : stylus button no longer pressed.
2455 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2456 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2457 finishDragAndDrop(entry.displayId, x, y);
2458 return;
2459 }
2460
chaviw98318de2021-05-19 16:45:23 -05002461 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002462 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002463 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002464 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002465 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2466 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2467 if (mDragState->dragHoverWindowHandle != nullptr) {
2468 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2469 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002470 }
arthurhung6d4bed92021-03-17 11:59:33 +08002471 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002472 }
2473 // enqueue drag location if needed.
2474 if (hoverWindowHandle != nullptr) {
2475 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2476 }
arthurhung6d4bed92021-03-17 11:59:33 +08002477 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2478 finishDragAndDrop(entry.displayId, x, y);
2479 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002480 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002481 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002482 }
2483}
2484
chaviw98318de2021-05-19 16:45:23 -05002485void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486 int32_t targetFlags, BitSet32 pointerIds,
2487 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002488 std::vector<InputTarget>::iterator it =
2489 std::find_if(inputTargets.begin(), inputTargets.end(),
2490 [&windowHandle](const InputTarget& inputTarget) {
2491 return inputTarget.inputChannel->getConnectionToken() ==
2492 windowHandle->getToken();
2493 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002494
chaviw98318de2021-05-19 16:45:23 -05002495 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002496
2497 if (it == inputTargets.end()) {
2498 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002499 std::shared_ptr<InputChannel> inputChannel =
2500 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002501 if (inputChannel == nullptr) {
2502 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2503 return;
2504 }
2505 inputTarget.inputChannel = inputChannel;
2506 inputTarget.flags = targetFlags;
2507 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002508 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002509 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002510 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002511 inputTargets.push_back(inputTarget);
2512 it = inputTargets.end() - 1;
2513 }
2514
2515 ALOG_ASSERT(it->flags == targetFlags);
2516 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2517
chaviw1ff3d1e2020-07-01 15:53:47 -07002518 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519}
2520
Michael Wright3dd60e22019-03-27 22:06:44 +00002521void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 int32_t displayId, float xOffset,
2523 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002524 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2525 mGlobalMonitorsByDisplay.find(displayId);
2526
2527 if (it != mGlobalMonitorsByDisplay.end()) {
2528 const std::vector<Monitor>& monitors = it->second;
2529 for (const Monitor& monitor : monitors) {
2530 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 }
2533}
2534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2536 float yOffset,
2537 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002538 InputTarget target;
2539 target.inputChannel = monitor.inputChannel;
2540 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002541 ui::Transform t;
2542 t.set(xOffset, yOffset);
2543 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002544 inputTargets.push_back(target);
2545}
2546
chaviw98318de2021-05-19 16:45:23 -05002547bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002548 const InjectionState* injectionState) {
2549 if (injectionState &&
2550 (windowHandle == nullptr ||
2551 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2552 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002553 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 "owned by uid %d",
2556 injectionState->injectorPid, injectionState->injectorUid,
2557 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 } else {
2559 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 }
2562 return false;
2563 }
2564 return true;
2565}
2566
Robert Carrc9bf1d32020-04-13 17:21:08 -07002567/**
2568 * Indicate whether one window handle should be considered as obscuring
2569 * another window handle. We only check a few preconditions. Actually
2570 * checking the bounds is left to the caller.
2571 */
chaviw98318de2021-05-19 16:45:23 -05002572static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2573 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002574 // Compare by token so cloned layers aren't counted
2575 if (haveSameToken(windowHandle, otherHandle)) {
2576 return false;
2577 }
2578 auto info = windowHandle->getInfo();
2579 auto otherInfo = otherHandle->getInfo();
2580 if (!otherInfo->visible) {
2581 return false;
chaviw98318de2021-05-19 16:45:23 -05002582 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002583 // Those act as if they were invisible, so we don't need to flag them.
2584 // We do want to potentially flag touchable windows even if they have 0
2585 // opacity, since they can consume touches and alter the effects of the
2586 // user interaction (eg. apps that rely on
2587 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2588 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2589 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002590 } else if (info->ownerUid == otherInfo->ownerUid) {
2591 // If ownerUid is the same we don't generate occlusion events as there
2592 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002593 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002594 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002595 return false;
2596 } else if (otherInfo->displayId != info->displayId) {
2597 return false;
2598 }
2599 return true;
2600}
2601
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002602/**
2603 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2604 * untrusted, one should check:
2605 *
2606 * 1. If result.hasBlockingOcclusion is true.
2607 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2608 * BLOCK_UNTRUSTED.
2609 *
2610 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2611 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2612 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2613 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2614 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2615 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2616 *
2617 * If neither of those is true, then it means the touch can be allowed.
2618 */
2619InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002620 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2621 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002622 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002623 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002624 TouchOcclusionInfo info;
2625 info.hasBlockingOcclusion = false;
2626 info.obscuringOpacity = 0;
2627 info.obscuringUid = -1;
2628 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002629 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002630 if (windowHandle == otherHandle) {
2631 break; // All future windows are below us. Exit early.
2632 }
chaviw98318de2021-05-19 16:45:23 -05002633 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002634 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2635 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002636 if (DEBUG_TOUCH_OCCLUSION) {
2637 info.debugInfo.push_back(
2638 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2639 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002640 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2641 // we perform the checks below to see if the touch can be propagated or not based on the
2642 // window's touch occlusion mode
2643 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2644 info.hasBlockingOcclusion = true;
2645 info.obscuringUid = otherInfo->ownerUid;
2646 info.obscuringPackage = otherInfo->packageName;
2647 break;
2648 }
2649 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2650 uint32_t uid = otherInfo->ownerUid;
2651 float opacity =
2652 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2653 // Given windows A and B:
2654 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2655 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2656 opacityByUid[uid] = opacity;
2657 if (opacity > info.obscuringOpacity) {
2658 info.obscuringOpacity = opacity;
2659 info.obscuringUid = uid;
2660 info.obscuringPackage = otherInfo->packageName;
2661 }
2662 }
2663 }
2664 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002665 if (DEBUG_TOUCH_OCCLUSION) {
2666 info.debugInfo.push_back(
2667 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2668 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002669 return info;
2670}
2671
chaviw98318de2021-05-19 16:45:23 -05002672std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002673 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002674 return StringPrintf(INDENT2
2675 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2676 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2677 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2678 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002679 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002680 NamedEnum::string(info->type, "%" PRId32).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",
Chris Yef59a2f42020-10-16 12:55:26 -07002807 NamedEnum::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",
Chris Yef59a2f42020-10-16 12:55:26 -07002852 NamedEnum::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",
Chris Yef59a2f42020-10-16 12:55:26 -07003040 NamedEnum::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",
Chris Yef59a2f42020-10-16 12:55:26 -07003279 NamedEnum::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",
Chris Yef59a2f42020-10-16 12:55:26 -07003595 NamedEnum::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",
Chris Yef59a2f42020-10-16 12:55:26 -07003602 NamedEnum::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",
Chris Yef59a2f42020-10-16 12:55:26 -07003662 NamedEnum::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,
4010 NamedEnum::string(args->sensorType).c_str());
4011 }
Chris Yef59a2f42020-10-16 12:55:26 -07004012
4013 bool needWake;
4014 { // acquire lock
4015 mLock.lock();
4016
4017 // Just enqueue a new sensor event.
4018 std::unique_ptr<SensorEntry> newEntry =
4019 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4020 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4021 args->sensorType, args->accuracy,
4022 args->accuracyChanged, args->values);
4023
4024 needWake = enqueueInboundEventLocked(std::move(newEntry));
4025 mLock.unlock();
4026 } // release lock
4027
4028 if (needWake) {
4029 mLooper->wake();
4030 }
4031}
4032
Chris Yefb552902021-02-03 17:18:37 -08004033void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 if (DEBUG_INBOUND_EVENT_DETAILS) {
4035 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4036 args->deviceId, args->isOn);
4037 }
Chris Yefb552902021-02-03 17:18:37 -08004038 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4039}
4040
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004042 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043}
4044
4045void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004046 if (DEBUG_INBOUND_EVENT_DETAILS) {
4047 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4048 "switchMask=0x%08x",
4049 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
4052 uint32_t policyFlags = args->policyFlags;
4053 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055}
4056
4057void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004058 if (DEBUG_INBOUND_EVENT_DETAILS) {
4059 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4060 args->deviceId);
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
4063 bool needWake;
4064 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004065 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004067 std::unique_ptr<DeviceResetEntry> newEntry =
4068 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4069 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 } // release lock
4071
4072 if (needWake) {
4073 mLooper->wake();
4074 }
4075}
4076
Prabir Pradhan7e186182020-11-10 13:56:45 -08004077void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004078 if (DEBUG_INBOUND_EVENT_DETAILS) {
4079 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004080 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004081 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004082
Prabir Pradhan99987712020-11-10 18:43:05 -08004083 bool needWake;
4084 { // acquire lock
4085 std::scoped_lock _l(mLock);
4086 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004087 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004088 needWake = enqueueInboundEventLocked(std::move(entry));
4089 } // release lock
4090
4091 if (needWake) {
4092 mLooper->wake();
4093 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004094}
4095
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096InputEventInjectionResult InputDispatcher::injectInputEvent(
4097 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4098 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004099 if (DEBUG_INBOUND_EVENT_DETAILS) {
4100 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4101 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4102 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4103 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004104 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105
4106 policyFlags |= POLICY_FLAG_INJECTED;
4107 if (hasInjectionPermission(injectorPid, injectorUid)) {
4108 policyFlags |= POLICY_FLAG_TRUSTED;
4109 }
4110
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004111 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004112 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4113 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4114 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4115 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4116 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004117 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004118 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004120 }
4121
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004122 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004125 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4126 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004128 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004131 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004132 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4133 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4134 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004135 int32_t keyCode = incomingKey.getKeyCode();
4136 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004139 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004140 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004141 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4142 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4143 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4146 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004147 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148
4149 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4150 android::base::Timer t;
4151 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4152 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4153 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4154 std::to_string(t.duration().count()).c_str());
4155 }
4156 }
4157
4158 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004159 std::unique_ptr<KeyEntry> injectedEntry =
4160 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004161 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004162 incomingKey.getDisplayId(), policyFlags, action,
4163 flags, keyCode, incomingKey.getScanCode(), metaState,
4164 incomingKey.getRepeatCount(),
4165 incomingKey.getDownTime());
4166 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004171 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4172 int32_t action = motionEvent.getAction();
4173 size_t pointerCount = motionEvent.getPointerCount();
4174 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4175 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004176 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004177 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 }
4181
4182 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 android::base::Timer t;
4185 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4186 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4187 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4188 std::to_string(t.duration().count()).c_str());
4189 }
4190 }
4191
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004192 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4193 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4194 }
4195
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004197 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4198 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004199 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004200 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4201 resolvedDeviceId, motionEvent.getSource(),
4202 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004203 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004204 motionEvent.getButtonState(),
4205 motionEvent.getClassification(),
4206 motionEvent.getEdgeFlags(),
4207 motionEvent.getXPrecision(),
4208 motionEvent.getYPrecision(),
4209 motionEvent.getRawXCursorPosition(),
4210 motionEvent.getRawYCursorPosition(),
4211 motionEvent.getDownTime(), uint32_t(pointerCount),
4212 pointerProperties, samplePointerCoords,
4213 motionEvent.getXOffset(),
4214 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004215 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004216 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 sampleEventTimes += 1;
4218 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004219 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4221 resolvedDeviceId, motionEvent.getSource(),
4222 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004223 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 motionEvent.getMetaState(),
4225 motionEvent.getButtonState(),
4226 motionEvent.getClassification(),
4227 motionEvent.getEdgeFlags(),
4228 motionEvent.getXPrecision(),
4229 motionEvent.getYPrecision(),
4230 motionEvent.getRawXCursorPosition(),
4231 motionEvent.getRawYCursorPosition(),
4232 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 samplePointerCoords, motionEvent.getXOffset(),
4235 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 }
4238 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004242 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 }
4245
4246 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 injectionState->injectionIsAsync = true;
4249 }
4250
4251 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004252 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
4254 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004255 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004256 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004257 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
4260 mLock.unlock();
4261
4262 if (needWake) {
4263 mLooper->wake();
4264 }
4265
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004268 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 if (syncMode == InputEventInjectionSync::NONE) {
4271 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 } else {
4273 for (;;) {
4274 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004275 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 break;
4277 }
4278
4279 nsecs_t remainingTimeout = endTime - now();
4280 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004281 if (DEBUG_INJECTION) {
4282 ALOGD("injectInputEvent - Timed out waiting for injection result "
4283 "to become available.");
4284 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004285 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 break;
4287 }
4288
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004289 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4293 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004295 if (DEBUG_INJECTION) {
4296 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4297 injectionState->pendingForegroundDispatches);
4298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 nsecs_t remainingTimeout = endTime - now();
4300 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004301 if (DEBUG_INJECTION) {
4302 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4303 "dispatches to finish.");
4304 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 break;
4307 }
4308
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004309 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 }
4312 }
4313
4314 injectionState->release();
4315 } // release lock
4316
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 if (DEBUG_INJECTION) {
4318 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4319 injectionResult, injectorPid, injectorUid);
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
4322 return injectionResult;
4323}
4324
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004325std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004326 std::array<uint8_t, 32> calculatedHmac;
4327 std::unique_ptr<VerifiedInputEvent> result;
4328 switch (event.getType()) {
4329 case AINPUT_EVENT_TYPE_KEY: {
4330 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4331 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4332 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004333 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004334 break;
4335 }
4336 case AINPUT_EVENT_TYPE_MOTION: {
4337 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4338 VerifiedMotionEvent verifiedMotionEvent =
4339 verifiedMotionEventFromMotionEvent(motionEvent);
4340 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004341 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004342 break;
4343 }
4344 default: {
4345 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4346 return nullptr;
4347 }
4348 }
4349 if (calculatedHmac == INVALID_HMAC) {
4350 return nullptr;
4351 }
4352 if (calculatedHmac != event.getHmac()) {
4353 return nullptr;
4354 }
4355 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004356}
4357
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 return injectorUid == 0 ||
4360 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361}
4362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004363void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004367 if (DEBUG_INJECTION) {
4368 ALOGD("Setting input event injection result to %d. "
4369 "injectorPid=%d, injectorUid=%d",
4370 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004373 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 // Log the outcome since the injector did not wait for the injection result.
4375 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004376 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 ALOGV("Asynchronous input event injection succeeded.");
4378 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004379 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 ALOGW("Asynchronous input event injection failed.");
4381 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004382 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 ALOGW("Asynchronous input event injection permission denied.");
4384 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004386 ALOGW("Asynchronous input event injection timed out.");
4387 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 case InputEventInjectionResult::PENDING:
4389 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392 }
4393
4394 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004395 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397}
4398
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004399void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4400 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 if (injectionState) {
4402 injectionState->pendingForegroundDispatches += 1;
4403 }
4404}
4405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004406void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4407 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 if (injectionState) {
4409 injectionState->pendingForegroundDispatches -= 1;
4410
4411 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004412 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414 }
4415}
4416
chaviw98318de2021-05-19 16:45:23 -05004417const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004418 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004419 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004420 auto it = mWindowHandlesByDisplay.find(displayId);
4421 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004422}
4423
chaviw98318de2021-05-19 16:45:23 -05004424sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004425 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004426 if (windowHandleToken == nullptr) {
4427 return nullptr;
4428 }
4429
Arthur Hungb92218b2018-08-14 12:00:21 +08004430 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004431 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4432 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004433 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004434 return windowHandle;
4435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 }
4437 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004438 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439}
4440
chaviw98318de2021-05-19 16:45:23 -05004441sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4442 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004443 if (windowHandleToken == nullptr) {
4444 return nullptr;
4445 }
4446
chaviw98318de2021-05-19 16:45:23 -05004447 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004448 if (windowHandle->getToken() == windowHandleToken) {
4449 return windowHandle;
4450 }
4451 }
4452 return nullptr;
4453}
4454
chaviw98318de2021-05-19 16:45:23 -05004455sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4456 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004457 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004458 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4459 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004460 if (handle->getId() == windowHandle->getId() &&
4461 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004462 if (windowHandle->getInfo()->displayId != it.first) {
4463 ALOGE("Found window %s in display %" PRId32
4464 ", but it should belong to display %" PRId32,
4465 windowHandle->getName().c_str(), it.first,
4466 windowHandle->getInfo()->displayId);
4467 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004468 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 }
4471 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004472 return nullptr;
4473}
4474
chaviw98318de2021-05-19 16:45:23 -05004475sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004476 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4477 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478}
4479
chaviw98318de2021-05-19 16:45:23 -05004480bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004481 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4482 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004483 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004484 if (connection != nullptr && noInputChannel) {
4485 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4486 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4487 return false;
4488 }
4489
4490 if (connection == nullptr) {
4491 if (!noInputChannel) {
4492 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4493 }
4494 return false;
4495 }
4496 if (!connection->responsive) {
4497 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4498 return false;
4499 }
4500 return true;
4501}
4502
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004503std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4504 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004505 auto connectionIt = mConnectionsByToken.find(token);
4506 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004507 return nullptr;
4508 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004509 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004510}
4511
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004512void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004513 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4514 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004515 // Remove all handles on a display if there are no windows left.
4516 mWindowHandlesByDisplay.erase(displayId);
4517 return;
4518 }
4519
4520 // Since we compare the pointer of input window handles across window updates, we need
4521 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004522 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4523 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4524 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004525 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004526 }
4527
chaviw98318de2021-05-19 16:45:23 -05004528 std::vector<sp<WindowInfoHandle>> newHandles;
4529 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004530 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004531 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004532 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004533 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4534 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4535 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004536 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004537 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004538 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004539 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004540 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004541 }
4542
4543 if (info->displayId != displayId) {
4544 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4545 handle->getName().c_str(), displayId, info->displayId);
4546 continue;
4547 }
4548
Robert Carredd13602020-04-13 17:24:34 -07004549 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4550 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004551 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004552 oldHandle->updateFrom(handle);
4553 newHandles.push_back(oldHandle);
4554 } else {
4555 newHandles.push_back(handle);
4556 }
4557 }
4558
4559 // Insert or replace
4560 mWindowHandlesByDisplay[displayId] = newHandles;
4561}
4562
Arthur Hung72d8dc32020-03-28 00:48:39 +00004563void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004564 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004565 { // acquire lock
4566 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004567 for (const auto& [displayId, handles] : handlesPerDisplay) {
4568 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004569 }
4570 }
4571 // Wake up poll loop since it may need to make new input dispatching choices.
4572 mLooper->wake();
4573}
4574
Arthur Hungb92218b2018-08-14 12:00:21 +08004575/**
4576 * Called from InputManagerService, update window handle list by displayId that can receive input.
4577 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4578 * If set an empty list, remove all handles from the specific display.
4579 * For focused handle, check if need to change and send a cancel event to previous one.
4580 * For removed handle, check if need to send a cancel event if already in touch.
4581 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004582void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004583 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004584 if (DEBUG_FOCUS) {
4585 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004586 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004587 windowList += iwh->getName() + " ";
4588 }
4589 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004592 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004593 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004594 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004595 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004596 if (noInputWindow && window->getToken() != nullptr) {
4597 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4598 window->getName().c_str());
4599 window->releaseChannel();
4600 }
4601 }
4602
Arthur Hung72d8dc32020-03-28 00:48:39 +00004603 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004604 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004606 // Save the old windows' orientation by ID before it gets updated.
4607 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004608 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004609 oldWindowOrientations.emplace(handle->getId(),
4610 handle->getInfo()->transform.getOrientation());
4611 }
4612
chaviw98318de2021-05-19 16:45:23 -05004613 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004614
chaviw98318de2021-05-19 16:45:23 -05004615 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004616 if (mLastHoverWindowHandle &&
4617 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4618 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619 mLastHoverWindowHandle = nullptr;
4620 }
4621
Vishnu Nairc519ff72021-01-21 08:23:08 -08004622 std::optional<FocusResolver::FocusChanges> changes =
4623 mFocusResolver.setInputWindows(displayId, windowHandles);
4624 if (changes) {
4625 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004628 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4629 mTouchStatesByDisplay.find(displayId);
4630 if (stateIt != mTouchStatesByDisplay.end()) {
4631 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004632 for (size_t i = 0; i < state.windows.size();) {
4633 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004634 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004635 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004636 ALOGD("Touched window was removed: %s in display %" PRId32,
4637 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004638 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004639 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004640 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4641 if (touchedInputChannel != nullptr) {
4642 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4643 "touched window was removed");
4644 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004646 state.windows.erase(state.windows.begin() + i);
4647 } else {
4648 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 }
4650 }
arthurhungb89ccb02020-12-30 16:19:01 +08004651
arthurhung6d4bed92021-03-17 11:59:33 +08004652 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004653 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004654 if (mDragState &&
4655 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004656 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004657 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004658 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004659 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004660
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004661 if (isPerWindowInputRotationEnabled()) {
4662 // Determine if the orientation of any of the input windows have changed, and cancel all
4663 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004664 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4665 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004666 if (newWindowHandle != nullptr &&
4667 newWindowHandle->getInfo()->transform.getOrientation() !=
4668 oldWindowOrientations[oldWindowHandle->getId()]) {
4669 std::shared_ptr<InputChannel> inputChannel =
4670 getInputChannelLocked(newWindowHandle->getToken());
4671 if (inputChannel != nullptr) {
4672 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4673 "touched window's orientation changed");
4674 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4675 }
4676 }
4677 }
4678 }
4679
Arthur Hung72d8dc32020-03-28 00:48:39 +00004680 // Release information for windows that are no longer present.
4681 // This ensures that unused input channels are released promptly.
4682 // Otherwise, they might stick around until the window handle is destroyed
4683 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004684 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004685 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004686 if (DEBUG_FOCUS) {
4687 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004688 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004689 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004690 // To avoid making too many calls into the compat framework, only
4691 // check for window flags when windows are going away.
4692 // TODO(b/157929241) : delete this. This is only needed temporarily
4693 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004694 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004695 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4696 oldWindowHandle->getName().c_str());
4697 if (mCompatService != nullptr) {
4698 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4699 oldWindowHandle->getInfo()->ownerUid);
4700 }
4701 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004702 }
chaviw291d88a2019-02-14 10:33:58 -08004703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704}
4705
4706void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004707 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004708 if (DEBUG_FOCUS) {
4709 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4710 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4711 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004712 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004714 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 } // release lock
4716
4717 // Wake up poll loop since it may need to make new input dispatching choices.
4718 mLooper->wake();
4719}
4720
Vishnu Nair599f1412021-06-21 10:39:58 -07004721void InputDispatcher::setFocusedApplicationLocked(
4722 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4723 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4724 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4725
4726 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4727 return; // This application is already focused. No need to wake up or change anything.
4728 }
4729
4730 // Set the new application handle.
4731 if (inputApplicationHandle != nullptr) {
4732 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4733 } else {
4734 mFocusedApplicationHandlesByDisplay.erase(displayId);
4735 }
4736
4737 // No matter what the old focused application was, stop waiting on it because it is
4738 // no longer focused.
4739 resetNoFocusedWindowTimeoutLocked();
4740}
4741
Tiger Huang721e26f2018-07-24 22:26:19 +08004742/**
4743 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4744 * the display not specified.
4745 *
4746 * We track any unreleased events for each window. If a window loses the ability to receive the
4747 * released event, we will send a cancel event to it. So when the focused display is changed, we
4748 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4749 * display. The display-specified events won't be affected.
4750 */
4751void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004752 if (DEBUG_FOCUS) {
4753 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4754 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004755 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004756 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004757
4758 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004759 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004760 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004761 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004762 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004763 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004764 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004765 CancelationOptions
4766 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4767 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004768 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004769 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4770 }
4771 }
4772 mFocusedDisplayId = displayId;
4773
Chris Ye3c2d6f52020-08-09 10:39:48 -07004774 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004775 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004776 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004777
Vishnu Nairad321cd2020-08-20 16:40:21 -07004778 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004779 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004780 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004781 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004782 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004783 }
4784 }
4785 }
4786
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004787 if (DEBUG_FOCUS) {
4788 logDispatchStateLocked();
4789 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004790 } // release lock
4791
4792 // Wake up poll loop since it may need to make new input dispatching choices.
4793 mLooper->wake();
4794}
4795
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004797 if (DEBUG_FOCUS) {
4798 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
4801 bool changed;
4802 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004803 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804
4805 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4806 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809
4810 if (mDispatchEnabled && !enabled) {
4811 resetAndDropEverythingLocked("dispatcher is being disabled");
4812 }
4813
4814 mDispatchEnabled = enabled;
4815 mDispatchFrozen = frozen;
4816 changed = true;
4817 } else {
4818 changed = false;
4819 }
4820
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004821 if (DEBUG_FOCUS) {
4822 logDispatchStateLocked();
4823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 } // release lock
4825
4826 if (changed) {
4827 // Wake up poll loop since it may need to make new input dispatching choices.
4828 mLooper->wake();
4829 }
4830}
4831
4832void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004833 if (DEBUG_FOCUS) {
4834 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
4837 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004838 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839
4840 if (mInputFilterEnabled == enabled) {
4841 return;
4842 }
4843
4844 mInputFilterEnabled = enabled;
4845 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4846 } // release lock
4847
4848 // Wake up poll loop since there might be work to do to drop everything.
4849 mLooper->wake();
4850}
4851
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004852void InputDispatcher::setInTouchMode(bool inTouchMode) {
4853 std::scoped_lock lock(mLock);
4854 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004855 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004856}
4857
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004858void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4859 if (opacity < 0 || opacity > 1) {
4860 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4861 return;
4862 }
4863
4864 std::scoped_lock lock(mLock);
4865 mMaximumObscuringOpacityForTouch = opacity;
4866}
4867
4868void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4869 std::scoped_lock lock(mLock);
4870 mBlockUntrustedTouchesMode = mode;
4871}
4872
arthurhungb89ccb02020-12-30 16:19:01 +08004873bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4874 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004875 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004876 if (DEBUG_FOCUS) {
4877 ALOGD("Trivial transfer to same window.");
4878 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004879 return true;
4880 }
4881
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004883 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884
chaviw98318de2021-05-19 16:45:23 -05004885 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4886 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004887 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004888 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 return false;
4890 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004891 if (DEBUG_FOCUS) {
4892 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4893 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004896 if (DEBUG_FOCUS) {
4897 ALOGD("Cannot transfer focus because windows are on different displays.");
4898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 return false;
4900 }
4901
4902 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004903 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4904 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004905 for (size_t i = 0; i < state.windows.size(); i++) {
4906 const TouchedWindow& touchedWindow = state.windows[i];
4907 if (touchedWindow.windowHandle == fromWindowHandle) {
4908 int32_t oldTargetFlags = touchedWindow.targetFlags;
4909 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004911 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004913 int32_t newTargetFlags = oldTargetFlags &
4914 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4915 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004916 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917
arthurhungb89ccb02020-12-30 16:19:01 +08004918 // Store the dragging window.
4919 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004920 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004921 }
4922
Jeff Brownf086ddb2014-02-11 14:28:48 -08004923 found = true;
4924 goto Found;
4925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 }
4927 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004930 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004931 if (DEBUG_FOCUS) {
4932 ALOGD("Focus transfer failed because from window did not have focus.");
4933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 return false;
4935 }
4936
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004937 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4938 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004939 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004940 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004941 CancelationOptions
4942 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4943 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004945 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
4947
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004948 if (DEBUG_FOCUS) {
4949 logDispatchStateLocked();
4950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 } // release lock
4952
4953 // Wake up poll loop since it may need to make new input dispatching choices.
4954 mLooper->wake();
4955 return true;
4956}
4957
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004958// Binder call
4959bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4960 sp<IBinder> fromToken;
4961 { // acquire lock
4962 std::scoped_lock _l(mLock);
4963
chaviw98318de2021-05-19 16:45:23 -05004964 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004965 if (toWindowHandle == nullptr) {
4966 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4967 return false;
4968 }
4969
4970 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4971
4972 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4973 if (touchStateIt == mTouchStatesByDisplay.end()) {
4974 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4975 displayId);
4976 return false;
4977 }
4978
4979 TouchState& state = touchStateIt->second;
4980 if (state.windows.size() != 1) {
4981 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4982 state.windows.size());
4983 return false;
4984 }
4985 const TouchedWindow& touchedWindow = state.windows[0];
4986 fromToken = touchedWindow.windowHandle->getToken();
4987 } // release lock
4988
4989 return transferTouchFocus(fromToken, destChannelToken);
4990}
4991
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004993 if (DEBUG_FOCUS) {
4994 ALOGD("Resetting and dropping all events (%s).", reason);
4995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996
4997 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4998 synthesizeCancelationEventsForAllConnectionsLocked(options);
4999
5000 resetKeyRepeatLocked();
5001 releasePendingEventLocked();
5002 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005003 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005005 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005006 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005008 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009}
5010
5011void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005012 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 dumpDispatchStateLocked(dump);
5014
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005015 std::istringstream stream(dump);
5016 std::string line;
5017
5018 while (std::getline(stream, line, '\n')) {
5019 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 }
5021}
5022
Prabir Pradhan99987712020-11-10 18:43:05 -08005023std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5024 std::string dump;
5025
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005026 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5027 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005028
5029 std::string windowName = "None";
5030 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005031 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005032 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5033 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5034 : "token has capture without window";
5035 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005036 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005037
5038 return dump;
5039}
5040
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005041void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005042 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5043 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5044 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005045 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046
Tiger Huang721e26f2018-07-24 22:26:19 +08005047 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5048 dump += StringPrintf(INDENT "FocusedApplications:\n");
5049 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5050 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005051 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005052 const std::chrono::duration timeout =
5053 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005054 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005055 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005056 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005059 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005061
Vishnu Nairc519ff72021-01-21 08:23:08 -08005062 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005063 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005065 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005066 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005067 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5068 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005069 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005070 state.displayId, toString(state.down), toString(state.split),
5071 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005072 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005073 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005074 for (size_t i = 0; i < state.windows.size(); i++) {
5075 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005076 dump += StringPrintf(INDENT4
5077 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5078 i, touchedWindow.windowHandle->getName().c_str(),
5079 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005080 }
5081 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005082 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 }
5085 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005086 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 }
5088
arthurhung6d4bed92021-03-17 11:59:33 +08005089 if (mDragState) {
5090 dump += StringPrintf(INDENT "DragState:\n");
5091 mDragState->dump(dump, INDENT2);
5092 }
5093
Arthur Hungb92218b2018-08-14 12:00:21 +08005094 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005095 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005096 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005097 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005098 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005099 dump += INDENT2 "Windows:\n";
5100 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005101 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5102 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005104 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005105 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005106 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005107 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005108 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005109 "applicationInfo.name=%s, "
5110 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005111 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005112 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005113 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005114 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005115 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005116 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005117 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005118 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005119 windowInfo->frameLeft, windowInfo->frameTop,
5120 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005121 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005122 windowInfo->applicationInfo.name.c_str(),
5123 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005124 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005125 dump += StringPrintf(", inputFeatures=%s",
5126 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005127 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005128 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005129 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005130 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005131 millis(windowInfo->dispatchingTimeout),
5132 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005133 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005134 toString(windowInfo->touchOcclusionMode).c_str(),
5135 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005136 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005137 }
5138 } else {
5139 dump += INDENT2 "Windows: <none>\n";
5140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 }
5142 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005143 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 }
5145
Michael Wright3dd60e22019-03-27 22:06:44 +00005146 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005147 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005148 const std::vector<Monitor>& monitors = it.second;
5149 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5150 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005151 }
5152 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005153 const std::vector<Monitor>& monitors = it.second;
5154 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5155 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005158 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160
5161 nsecs_t currentTime = now();
5162
5163 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005164 if (!mRecentQueue.empty()) {
5165 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005166 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005167 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005168 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
5175 // Dump event currently being dispatched.
5176 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 dump += INDENT "PendingEvent:\n";
5178 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005179 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005180 dump += StringPrintf(", age=%" PRId64 "ms\n",
5181 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005183 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 }
5185
5186 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005187 if (!mInboundQueue.empty()) {
5188 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005189 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005190 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005191 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005192 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 }
5194 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005195 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 }
5197
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005198 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005199 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005200 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5201 const KeyReplacement& replacement = pair.first;
5202 int32_t newKeyCode = pair.second;
5203 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005204 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005205 }
5206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005207 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005208 }
5209
Prabir Pradhancef936d2021-07-21 16:17:52 +00005210 if (!mCommandQueue.empty()) {
5211 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5212 } else {
5213 dump += INDENT "CommandQueue: <empty>\n";
5214 }
5215
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005216 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005217 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005218 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005219 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005220 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005221 connection->inputChannel->getFd().get(),
5222 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005223 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005224 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005226 if (!connection->outboundQueue.empty()) {
5227 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5228 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005229 dump += dumpQueue(connection->outboundQueue, currentTime);
5230
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005232 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 }
5234
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005235 if (!connection->waitQueue.empty()) {
5236 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5237 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005238 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005240 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 }
5242 }
5243 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005244 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 }
5246
5247 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005248 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5249 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005251 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 }
5253
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005254 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005255 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5256 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5257 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005258 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005259 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260}
5261
Michael Wright3dd60e22019-03-27 22:06:44 +00005262void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5263 const size_t numMonitors = monitors.size();
5264 for (size_t i = 0; i < numMonitors; i++) {
5265 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005266 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005267 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5268 dump += "\n";
5269 }
5270}
5271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272class LooperEventCallback : public LooperCallback {
5273public:
5274 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5275 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5276
5277private:
5278 std::function<int(int events)> mCallback;
5279};
5280
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005281Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005282 if (DEBUG_CHANNEL_CREATION) {
5283 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005286 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005287 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005288 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005289
5290 if (result) {
5291 return base::Error(result) << "Failed to open input channel pair with name " << name;
5292 }
5293
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005295 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005296 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005297 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005298 sp<Connection> connection =
5299 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005301 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5302 ALOGE("Created a new connection, but the token %p is already known", token.get());
5303 }
5304 mConnectionsByToken.emplace(token, connection);
5305
5306 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5307 this, std::placeholders::_1, token);
5308
5309 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 } // release lock
5311
5312 // Wake the looper because some connections have changed.
5313 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005314 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315}
5316
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005317Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5318 bool isGestureMonitor,
5319 const std::string& name,
5320 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005321 std::shared_ptr<InputChannel> serverChannel;
5322 std::unique_ptr<InputChannel> clientChannel;
5323 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5324 if (result) {
5325 return base::Error(result) << "Failed to open input channel pair with name " << name;
5326 }
5327
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 { // acquire lock
5329 std::scoped_lock _l(mLock);
5330
5331 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005332 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5333 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005334 }
5335
Garfield Tan15601662020-09-22 15:32:38 -07005336 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005337 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005338 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005339
5340 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5341 ALOGE("Created a new connection, but the token %p is already known", token.get());
5342 }
5343 mConnectionsByToken.emplace(token, connection);
5344 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5345 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005347 auto& monitorsByDisplay =
5348 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005349 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005350
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005351 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005352 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5353 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005354 }
Garfield Tan15601662020-09-22 15:32:38 -07005355
Michael Wright3dd60e22019-03-27 22:06:44 +00005356 // Wake the looper because some connections have changed.
5357 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005358 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005359}
5360
Garfield Tan15601662020-09-22 15:32:38 -07005361status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005363 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364
Garfield Tan15601662020-09-22 15:32:38 -07005365 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366 if (status) {
5367 return status;
5368 }
5369 } // release lock
5370
5371 // Wake the poll loop because removing the connection may have changed the current
5372 // synchronization state.
5373 mLooper->wake();
5374 return OK;
5375}
5376
Garfield Tan15601662020-09-22 15:32:38 -07005377status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5378 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005379 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005380 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005381 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 return BAD_VALUE;
5383 }
5384
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005385 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005386
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005388 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 }
5390
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005391 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392
5393 nsecs_t currentTime = now();
5394 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5395
5396 connection->status = Connection::STATUS_ZOMBIE;
5397 return OK;
5398}
5399
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005400void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5401 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5402 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005403}
5404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005405void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005406 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005407 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005408 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005409 std::vector<Monitor>& monitors = it->second;
5410 const size_t numMonitors = monitors.size();
5411 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005412 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005413 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5414 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005415 monitors.erase(monitors.begin() + i);
5416 break;
5417 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005418 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005419 if (monitors.empty()) {
5420 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005421 } else {
5422 ++it;
5423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 }
5425}
5426
Michael Wright3dd60e22019-03-27 22:06:44 +00005427status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5428 { // acquire lock
5429 std::scoped_lock _l(mLock);
5430 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5431
5432 if (!foundDisplayId) {
5433 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5434 return BAD_VALUE;
5435 }
5436 int32_t displayId = foundDisplayId.value();
5437
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005438 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5439 mTouchStatesByDisplay.find(displayId);
5440 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005441 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5442 return BAD_VALUE;
5443 }
5444
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005445 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005446 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005447 std::optional<int32_t> foundDeviceId;
5448 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005449 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005450 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005451 foundDeviceId = state.deviceId;
5452 }
5453 }
5454 if (!foundDeviceId || !state.down) {
5455 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005456 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005457 return BAD_VALUE;
5458 }
5459 int32_t deviceId = foundDeviceId.value();
5460
5461 // Send cancel events to all the input channels we're stealing from.
5462 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005463 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005464 options.deviceId = deviceId;
5465 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005466 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005467 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005468 std::shared_ptr<InputChannel> channel =
5469 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005470 if (channel != nullptr) {
5471 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005472 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005473 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005474 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005475 canceledWindows += "]";
5476 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5477 canceledWindows.c_str());
5478
Michael Wright3dd60e22019-03-27 22:06:44 +00005479 // Then clear the current touch state so we stop dispatching to them as well.
5480 state.filterNonMonitors();
5481 }
5482 return OK;
5483}
5484
Prabir Pradhan99987712020-11-10 18:43:05 -08005485void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5486 { // acquire lock
5487 std::scoped_lock _l(mLock);
5488 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005489 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005490 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5491 windowHandle != nullptr ? windowHandle->getName().c_str()
5492 : "token without window");
5493 }
5494
Vishnu Nairc519ff72021-01-21 08:23:08 -08005495 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005496 if (focusedToken != windowToken) {
5497 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5498 enabled ? "enable" : "disable");
5499 return;
5500 }
5501
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005502 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005503 ALOGW("Ignoring request to %s Pointer Capture: "
5504 "window has %s requested pointer capture.",
5505 enabled ? "enable" : "disable", enabled ? "already" : "not");
5506 return;
5507 }
5508
Prabir Pradhan99987712020-11-10 18:43:05 -08005509 setPointerCaptureLocked(enabled);
5510 } // release lock
5511
5512 // Wake the thread to process command entries.
5513 mLooper->wake();
5514}
5515
Michael Wright3dd60e22019-03-27 22:06:44 +00005516std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5517 const sp<IBinder>& token) {
5518 for (const auto& it : mGestureMonitorsByDisplay) {
5519 const std::vector<Monitor>& monitors = it.second;
5520 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005521 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005522 return it.first;
5523 }
5524 }
5525 }
5526 return std::nullopt;
5527}
5528
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005529std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5530 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5531 if (gesturePid.has_value()) {
5532 return gesturePid;
5533 }
5534 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5535}
5536
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005537sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005538 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005539 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005540 }
5541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542 for (const auto& [token, connection] : mConnectionsByToken) {
5543 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005544 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 }
5546 }
Robert Carr4e670e52018-08-15 13:26:12 -07005547
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005548 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549}
5550
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005551std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5552 sp<Connection> connection = getConnectionLocked(connectionToken);
5553 if (connection == nullptr) {
5554 return "<nullptr>";
5555 }
5556 return connection->getInputChannelName();
5557}
5558
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005559void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005560 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005561 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005562}
5563
Prabir Pradhancef936d2021-07-21 16:17:52 +00005564void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5565 const sp<Connection>& connection, uint32_t seq,
5566 bool handled, nsecs_t consumeTime) {
5567 // Handle post-event policy actions.
5568 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5569 if (dispatchEntryIt == connection->waitQueue.end()) {
5570 return;
5571 }
5572 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5573 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5574 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5575 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5576 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5577 }
5578 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5579 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5580 connection->inputChannel->getConnectionToken(),
5581 dispatchEntry->deliveryTime, consumeTime, finishTime);
5582 }
5583
5584 bool restartEvent;
5585 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5586 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5587 restartEvent =
5588 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5589 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5590 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5591 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5592 handled);
5593 } else {
5594 restartEvent = false;
5595 }
5596
5597 // Dequeue the event and start the next cycle.
5598 // Because the lock might have been released, it is possible that the
5599 // contents of the wait queue to have been drained, so we need to double-check
5600 // a few things.
5601 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5602 if (dispatchEntryIt != connection->waitQueue.end()) {
5603 dispatchEntry = *dispatchEntryIt;
5604 connection->waitQueue.erase(dispatchEntryIt);
5605 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5606 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5607 if (!connection->responsive) {
5608 connection->responsive = isConnectionResponsive(*connection);
5609 if (connection->responsive) {
5610 // The connection was unresponsive, and now it's responsive.
5611 processConnectionResponsiveLocked(*connection);
5612 }
5613 }
5614 traceWaitQueueLength(*connection);
5615 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5616 connection->outboundQueue.push_front(dispatchEntry);
5617 traceOutboundQueueLength(*connection);
5618 } else {
5619 releaseDispatchEntry(dispatchEntry);
5620 }
5621 }
5622
5623 // Start the next dispatch cycle for this connection.
5624 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625}
5626
Prabir Pradhancef936d2021-07-21 16:17:52 +00005627void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5628 const sp<IBinder>& newToken) {
5629 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5630 scoped_unlock unlock(mLock);
5631 mPolicy->notifyFocusChanged(oldToken, newToken);
5632 };
5633 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634}
5635
Prabir Pradhancef936d2021-07-21 16:17:52 +00005636void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5637 auto command = [this, token, x, y]() REQUIRES(mLock) {
5638 scoped_unlock unlock(mLock);
5639 mPolicy->notifyDropWindow(token, x, y);
5640 };
5641 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005642}
5643
Prabir Pradhancef936d2021-07-21 16:17:52 +00005644void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5645 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5646 scoped_unlock unlock(mLock);
5647 mPolicy->notifyUntrustedTouch(obscuringPackage);
5648 };
5649 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005650}
5651
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005652void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5653 if (connection == nullptr) {
5654 LOG_ALWAYS_FATAL("Caller must check for nullness");
5655 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005656 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5657 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005658 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005659 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005660 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005661 return;
5662 }
5663 /**
5664 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5665 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5666 * has changed. This could cause newer entries to time out before the already dispatched
5667 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5668 * processes the events linearly. So providing information about the oldest entry seems to be
5669 * most useful.
5670 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005671 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5673 std::string reason =
5674 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005675 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005676 ns2ms(currentWait),
5677 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005678 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005679 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005680
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005681 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5682
5683 // Stop waking up for events on this connection, it is already unresponsive
5684 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005685}
5686
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005687void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5688 std::string reason =
5689 StringPrintf("%s does not have a focused window", application->getName().c_str());
5690 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005691
Prabir Pradhancef936d2021-07-21 16:17:52 +00005692 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5693 scoped_unlock unlock(mLock);
5694 mPolicy->notifyNoFocusedWindowAnr(application);
5695 };
5696 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005697}
5698
chaviw98318de2021-05-19 16:45:23 -05005699void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005700 const std::string& reason) {
5701 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5702 updateLastAnrStateLocked(windowLabel, reason);
5703}
5704
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005705void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5706 const std::string& reason) {
5707 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005708 updateLastAnrStateLocked(windowLabel, reason);
5709}
5710
5711void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5712 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005714 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 struct tm tm;
5716 localtime_r(&t, &tm);
5717 char timestr[64];
5718 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005719 mLastAnrState.clear();
5720 mLastAnrState += INDENT "ANR:\n";
5721 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5723 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005724 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725}
5726
Prabir Pradhancef936d2021-07-21 16:17:52 +00005727void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5728 KeyEntry& entry) {
5729 const KeyEvent event = createKeyEvent(entry);
5730 nsecs_t delay = 0;
5731 { // release lock
5732 scoped_unlock unlock(mLock);
5733 android::base::Timer t;
5734 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5735 entry.policyFlags);
5736 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5737 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5738 std::to_string(t.duration().count()).c_str());
5739 }
5740 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005741
5742 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005743 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005744 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005745 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005747 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5748 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750}
5751
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005752void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005753 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5754 scoped_unlock unlock(mLock);
5755 mPolicy->notifyMonitorUnresponsive(pid, reason);
5756 };
5757 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005758}
5759
Prabir Pradhancef936d2021-07-21 16:17:52 +00005760void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005761 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005762 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5763 scoped_unlock unlock(mLock);
5764 mPolicy->notifyWindowUnresponsive(token, reason);
5765 };
5766 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005767}
5768
5769void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005770 auto command = [this, pid]() REQUIRES(mLock) {
5771 scoped_unlock unlock(mLock);
5772 mPolicy->notifyMonitorResponsive(pid);
5773 };
5774 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005775}
5776
Prabir Pradhancef936d2021-07-21 16:17:52 +00005777void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5778 auto command = [this, connectionToken]() REQUIRES(mLock) {
5779 scoped_unlock unlock(mLock);
5780 mPolicy->notifyWindowResponsive(connectionToken);
5781 };
5782 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005783}
5784
5785/**
5786 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5787 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5788 * command entry to the command queue.
5789 */
5790void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5791 std::string reason) {
5792 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5793 if (connection.monitor) {
5794 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5795 reason.c_str());
5796 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5797 if (!pid.has_value()) {
5798 ALOGE("Could not find unresponsive monitor for connection %s",
5799 connection.inputChannel->getName().c_str());
5800 return;
5801 }
5802 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5803 return;
5804 }
5805 // If not a monitor, must be a window
5806 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5807 reason.c_str());
5808 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5809}
5810
5811/**
5812 * Tell the policy that a connection has become responsive so that it can stop ANR.
5813 */
5814void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5815 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5816 if (connection.monitor) {
5817 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5818 if (!pid.has_value()) {
5819 ALOGE("Could not find responsive monitor for connection %s",
5820 connection.inputChannel->getName().c_str());
5821 return;
5822 }
5823 sendMonitorResponsiveCommandLocked(pid.value());
5824 return;
5825 }
5826 // If not a monitor, must be a window
5827 sendWindowResponsiveCommandLocked(connectionToken);
5828}
5829
Prabir Pradhancef936d2021-07-21 16:17:52 +00005830bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005831 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005832 KeyEntry& keyEntry, bool handled) {
5833 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005834 if (!handled) {
5835 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005836 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005837 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005838 return false;
5839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005841 // Get the fallback key state.
5842 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005843 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005844 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005845 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005846 connection->inputState.removeFallbackKey(originalKeyCode);
5847 }
5848
5849 if (handled || !dispatchEntry->hasForegroundTarget()) {
5850 // If the application handles the original key for which we previously
5851 // generated a fallback or if the window is not a foreground window,
5852 // then cancel the associated fallback key, if any.
5853 if (fallbackKeyCode != -1) {
5854 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005855 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5856 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5857 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5858 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5859 keyEntry.policyFlags);
5860 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005861 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005862 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863
5864 mLock.unlock();
5865
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005866 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005867 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868
5869 mLock.lock();
5870
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005871 // Cancel the fallback key.
5872 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005874 "application handled the original non-fallback key "
5875 "or is no longer a foreground target, "
5876 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 options.keyCode = fallbackKeyCode;
5878 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005880 connection->inputState.removeFallbackKey(originalKeyCode);
5881 }
5882 } else {
5883 // If the application did not handle a non-fallback key, first check
5884 // that we are in a good state to perform unhandled key event processing
5885 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005887 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005888 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5889 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5890 "since this is not an initial down. "
5891 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5892 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5893 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005894 return false;
5895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005898 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5899 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5900 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5901 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5902 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005903 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005904
5905 mLock.unlock();
5906
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005907 bool fallback =
5908 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005909 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005910
5911 mLock.lock();
5912
5913 if (connection->status != Connection::STATUS_NORMAL) {
5914 connection->inputState.removeFallbackKey(originalKeyCode);
5915 return false;
5916 }
5917
5918 // Latch the fallback keycode for this key on an initial down.
5919 // The fallback keycode cannot change at any other point in the lifecycle.
5920 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922 fallbackKeyCode = event.getKeyCode();
5923 } else {
5924 fallbackKeyCode = AKEYCODE_UNKNOWN;
5925 }
5926 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5927 }
5928
5929 ALOG_ASSERT(fallbackKeyCode != -1);
5930
5931 // Cancel the fallback key if the policy decides not to send it anymore.
5932 // We will continue to dispatch the key to the policy but we will no
5933 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005934 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5935 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005936 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5937 if (fallback) {
5938 ALOGD("Unhandled key event: Policy requested to send key %d"
5939 "as a fallback for %d, but on the DOWN it had requested "
5940 "to send %d instead. Fallback canceled.",
5941 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5942 } else {
5943 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5944 "but on the DOWN it had requested to send %d. "
5945 "Fallback canceled.",
5946 originalKeyCode, fallbackKeyCode);
5947 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005949
5950 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5951 "canceling fallback, policy no longer desires it");
5952 options.keyCode = fallbackKeyCode;
5953 synthesizeCancelationEventsForConnectionLocked(connection, options);
5954
5955 fallback = false;
5956 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005958 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 }
5960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005962 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5963 {
5964 std::string msg;
5965 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5966 connection->inputState.getFallbackKeys();
5967 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5968 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5969 }
5970 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5971 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005974
5975 if (fallback) {
5976 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005977 keyEntry.eventTime = event.getEventTime();
5978 keyEntry.deviceId = event.getDeviceId();
5979 keyEntry.source = event.getSource();
5980 keyEntry.displayId = event.getDisplayId();
5981 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5982 keyEntry.keyCode = fallbackKeyCode;
5983 keyEntry.scanCode = event.getScanCode();
5984 keyEntry.metaState = event.getMetaState();
5985 keyEntry.repeatCount = event.getRepeatCount();
5986 keyEntry.downTime = event.getDownTime();
5987 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005989 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5990 ALOGD("Unhandled key event: Dispatching fallback key. "
5991 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5992 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
5993 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005994 return true; // restart the event
5995 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005996 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5997 ALOGD("Unhandled key event: No fallback key.");
5998 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005999
6000 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006001 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002 }
6003 }
6004 return false;
6005}
6006
Prabir Pradhancef936d2021-07-21 16:17:52 +00006007bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006008 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006009 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 return false;
6011}
6012
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013void InputDispatcher::traceInboundQueueLengthLocked() {
6014 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006015 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 }
6017}
6018
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006019void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 if (ATRACE_ENABLED()) {
6021 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006022 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6023 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 }
6025}
6026
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006027void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 if (ATRACE_ENABLED()) {
6029 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006030 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6031 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 }
6033}
6034
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006035void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006036 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006038 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 dumpDispatchStateLocked(dump);
6040
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006041 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006042 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006043 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 }
6045}
6046
6047void InputDispatcher::monitor() {
6048 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006049 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006051 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052}
6053
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006054/**
6055 * Wake up the dispatcher and wait until it processes all events and commands.
6056 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6057 * this method can be safely called from any thread, as long as you've ensured that
6058 * the work you are interested in completing has already been queued.
6059 */
6060bool InputDispatcher::waitForIdle() {
6061 /**
6062 * Timeout should represent the longest possible time that a device might spend processing
6063 * events and commands.
6064 */
6065 constexpr std::chrono::duration TIMEOUT = 100ms;
6066 std::unique_lock lock(mLock);
6067 mLooper->wake();
6068 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6069 return result == std::cv_status::no_timeout;
6070}
6071
Vishnu Naire798b472020-07-23 13:52:21 -07006072/**
6073 * Sets focus to the window identified by the token. This must be called
6074 * after updating any input window handles.
6075 *
6076 * Params:
6077 * request.token - input channel token used to identify the window that should gain focus.
6078 * request.focusedToken - the token that the caller expects currently to be focused. If the
6079 * specified token does not match the currently focused window, this request will be dropped.
6080 * If the specified focused token matches the currently focused window, the call will succeed.
6081 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6082 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6083 * when requesting the focus change. This determines which request gets
6084 * precedence if there is a focus change request from another source such as pointer down.
6085 */
Vishnu Nair958da932020-08-21 17:12:37 -07006086void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6087 { // acquire lock
6088 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006089 std::optional<FocusResolver::FocusChanges> changes =
6090 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6091 if (changes) {
6092 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006093 }
6094 } // release lock
6095 // Wake up poll loop since it may need to make new input dispatching choices.
6096 mLooper->wake();
6097}
6098
Vishnu Nairc519ff72021-01-21 08:23:08 -08006099void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6100 if (changes.oldFocus) {
6101 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006102 if (focusedInputChannel) {
6103 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6104 "focus left window");
6105 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006106 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006107 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006108 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006109 if (changes.newFocus) {
6110 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006111 }
6112
Prabir Pradhan99987712020-11-10 18:43:05 -08006113 // If a window has pointer capture, then it must have focus. We need to ensure that this
6114 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6115 // If the window loses focus before it loses pointer capture, then the window can be in a state
6116 // where it has pointer capture but not focus, violating the contract. Therefore we must
6117 // dispatch the pointer capture event before the focus event. Since focus events are added to
6118 // the front of the queue (above), we add the pointer capture event to the front of the queue
6119 // after the focus events are added. This ensures the pointer capture event ends up at the
6120 // front.
6121 disablePointerCaptureForcedLocked();
6122
Vishnu Nairc519ff72021-01-21 08:23:08 -08006123 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006124 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006125 }
6126}
Vishnu Nair958da932020-08-21 17:12:37 -07006127
Prabir Pradhan99987712020-11-10 18:43:05 -08006128void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006129 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006130 return;
6131 }
6132
6133 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6134
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006135 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006136 setPointerCaptureLocked(false);
6137 }
6138
6139 if (!mWindowTokenWithPointerCapture) {
6140 // No need to send capture changes because no window has capture.
6141 return;
6142 }
6143
6144 if (mPendingEvent != nullptr) {
6145 // Move the pending event to the front of the queue. This will give the chance
6146 // for the pending event to be dropped if it is a captured event.
6147 mInboundQueue.push_front(mPendingEvent);
6148 mPendingEvent = nullptr;
6149 }
6150
6151 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006152 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006153 mInboundQueue.push_front(std::move(entry));
6154}
6155
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006156void InputDispatcher::setPointerCaptureLocked(bool enable) {
6157 mCurrentPointerCaptureRequest.enable = enable;
6158 mCurrentPointerCaptureRequest.seq++;
6159 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006160 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006161 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006162 };
6163 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006164}
6165
Vishnu Nair599f1412021-06-21 10:39:58 -07006166void InputDispatcher::displayRemoved(int32_t displayId) {
6167 { // acquire lock
6168 std::scoped_lock _l(mLock);
6169 // Set an empty list to remove all handles from the specific display.
6170 setInputWindowsLocked(/* window handles */ {}, displayId);
6171 setFocusedApplicationLocked(displayId, nullptr);
6172 // Call focus resolver to clean up stale requests. This must be called after input windows
6173 // have been removed for the removed display.
6174 mFocusResolver.displayRemoved(displayId);
6175 } // release lock
6176
6177 // Wake up poll loop since it may need to make new input dispatching choices.
6178 mLooper->wake();
6179}
6180
chaviw15fab6f2021-06-07 14:15:52 -05006181void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6182 // The listener sends the windows as a flattened array. Separate the windows by display for
6183 // more convenient parsing.
6184 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6185
6186 for (const auto& info : windowInfos) {
6187 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6188 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6189 }
6190 setInputWindows(handlesPerDisplay);
6191}
6192
Garfield Tane84e6f92019-08-29 17:28:41 -07006193} // namespace android::inputdispatcher