blob: e0977733703f67adfc82e0231d675a784ee3de55 [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
Prabir Pradhan99987712020-11-10 18:43:05 -0800828 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
829 const auto typedEntry =
830 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
831 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
832 done = true;
833 break;
834 }
835
arthurhungb89ccb02020-12-30 16:19:01 +0800836 case EventEntry::Type::DRAG: {
837 std::shared_ptr<DragEntry> typedEntry =
838 std::static_pointer_cast<DragEntry>(mPendingEvent);
839 dispatchDragLocked(currentTime, typedEntry);
840 done = true;
841 break;
842 }
843
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700844 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700845 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700847 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700848 resetPendingAppSwitchLocked(true);
849 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700850 } else if (dropReason == DropReason::NOT_DROPPED) {
851 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 }
853 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700854 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700855 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700857 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
858 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700860 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 break;
862 }
863
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700864 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700865 std::shared_ptr<MotionEntry> motionEntry =
866 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
868 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700870 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
874 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 }
Chris Yef59a2f42020-10-16 12:55:26 -0700879
880 case EventEntry::Type::SENSOR: {
881 std::shared_ptr<SensorEntry> sensorEntry =
882 std::static_pointer_cast<SensorEntry>(mPendingEvent);
883 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
884 dropReason = DropReason::APP_SWITCH;
885 }
886 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
887 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
888 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
889 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
890 dropReason = DropReason::STALE;
891 }
892 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
893 done = true;
894 break;
895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897
898 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700900 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
Michael Wright3a981722015-06-10 15:26:13 +0100902 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903
904 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907}
908
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700909/**
910 * Return true if the events preceding this incoming motion event should be dropped
911 * Return false otherwise (the default behaviour)
912 */
913bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700915 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700916
917 // Optimize case where the current application is unresponsive and the user
918 // decides to touch a window in a different application.
919 // If the application takes too long to catch up then we drop all events preceding
920 // the touch into the other window.
921 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700922 int32_t displayId = motionEntry.displayId;
923 int32_t x = static_cast<int32_t>(
924 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
925 int32_t y = static_cast<int32_t>(
926 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500927 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700928 findTouchedWindowAtLocked(displayId, x, y, nullptr);
929 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 touchedWindowHandle->getApplicationToken() !=
931 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700932 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700933 ALOGI("Pruning input queue because user touched a different application while waiting "
934 "for %s",
935 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700936 return true;
937 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938
939 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600940 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700941 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
942 sp<Connection> connection =
943 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000944 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 // This monitor could take more input. Drop all events preceding this
946 // event, so that gesture monitor could get a chance to receive the stream
947 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
948 "responsive gesture monitor that may handle the event",
949 mAwaitedFocusedApplication->getName().c_str());
950 return true;
951 }
952 }
953 }
954
955 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
956 // yet been processed by some connections, the dispatcher will wait for these motion
957 // events to be processed before dispatching the key event. This is because these motion events
958 // may cause a new window to be launched, which the user might expect to receive focus.
959 // To prevent waiting forever for such events, just send the key to the currently focused window
960 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
961 ALOGD("Received a new pointer down event, stop waiting for events to process and "
962 "just send the pending key event to the focused window.");
963 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700964 }
965 return false;
966}
967
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700969 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700970 mInboundQueue.push_back(std::move(newEntry));
971 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 traceInboundQueueLengthLocked();
973
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700975 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 // Optimize app switch latency.
977 // If the application takes too long to catch up then we drop all events preceding
978 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700981 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700983 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000985 if (DEBUG_APP_SWITCH) {
986 ALOGD("App switch is pending!");
987 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700988 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 mAppSwitchSawKeyDown = false;
990 needWake = true;
991 }
992 }
993 }
994 break;
995 }
996
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700997 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700998 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
999 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001000 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001004 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001005 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1006 break;
1007 }
1008 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001009 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001010 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001011 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1012 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001013 // nothing to do
1014 break;
1015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 return needWake;
1019}
1020
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001021void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001022 // Do not store sensor event in recent queue to avoid flooding the queue.
1023 if (entry->type != EventEntry::Type::SENSOR) {
1024 mRecentQueue.push_back(entry);
1025 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001026 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001027 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 }
1029}
1030
chaviw98318de2021-05-19 16:45:23 -05001031sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1032 int32_t y, TouchState* touchState,
1033 bool addOutsideTargets,
1034 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001035 if (addOutsideTargets && touchState == nullptr) {
1036 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001039 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1040 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001041 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001042 continue;
1043 }
chaviw98318de2021-05-19 16:45:23 -05001044 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001046 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047
1048 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001049 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1050 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1051 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1053 // Found window.
1054 return windowHandle;
1055 }
1056 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001057
chaviw98318de2021-05-19 16:45:23 -05001058 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001059 touchState->addOrUpdateWindow(windowHandle,
1060 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1061 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
1065 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001066 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067}
1068
Garfield Tane84e6f92019-08-29 17:28:41 -07001069std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001070 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001071 std::vector<TouchedMonitor> touchedMonitors;
1072
1073 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1074 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001075 return touchedMonitors;
1076}
1077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 const char* reason;
1080 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001082 if (DEBUG_INBOUND_EVENT_DETAILS) {
1083 ALOGD("Dropped event because policy consumed it.");
1084 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 reason = "inbound event was dropped because the policy consumed it";
1086 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 case DropReason::DISABLED:
1088 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because input dispatch is disabled.");
1090 }
1091 reason = "inbound event was dropped because input dispatch is disabled";
1092 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 ALOGI("Dropped event because of pending overdue app switch.");
1095 reason = "inbound event was dropped because of pending overdue app switch";
1096 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 ALOGI("Dropped event because the current application is not responding and the user "
1099 "has started interacting with a different application.");
1100 reason = "inbound event was dropped because the current application is not responding "
1101 "and the user has started interacting with a different application";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because it is stale.");
1105 reason = "inbound event was dropped because it is stale";
1106 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001107 case DropReason::NO_POINTER_CAPTURE:
1108 ALOGI("Dropped event because there is no window with Pointer Capture.");
1109 reason = "inbound event was dropped because there is no window with Pointer Capture";
1110 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001111 case DropReason::NOT_DROPPED: {
1112 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
1116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001117 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001118 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1120 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001123 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1125 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1127 synthesizeCancelationEventsForAllConnectionsLocked(options);
1128 } else {
1129 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1130 synthesizeCancelationEventsForAllConnectionsLocked(options);
1131 }
1132 break;
1133 }
Chris Yef59a2f42020-10-16 12:55:26 -07001134 case EventEntry::Type::SENSOR: {
1135 break;
1136 }
arthurhungb89ccb02020-12-30 16:19:01 +08001137 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1138 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 break;
1140 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001141 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001142 case EventEntry::Type::CONFIGURATION_CHANGED:
1143 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001144 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001145 break;
1146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148}
1149
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001150static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001151 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1152 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153}
1154
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1156 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1157 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1158 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159}
1160
1161bool InputDispatcher::isAppSwitchPendingLocked() {
1162 return mAppSwitchDueTime != LONG_LONG_MAX;
1163}
1164
1165void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1166 mAppSwitchDueTime = LONG_LONG_MAX;
1167
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001168 if (DEBUG_APP_SWITCH) {
1169 if (handled) {
1170 ALOGD("App switch has arrived.");
1171 } else {
1172 ALOGD("App switch was abandoned.");
1173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175}
1176
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001178 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179}
1180
Prabir Pradhancef936d2021-07-21 16:17:52 +00001181bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001182 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 return false;
1184 }
1185
1186 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001187 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001188 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001189 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1190 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001191 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 return true;
1193}
1194
Prabir Pradhancef936d2021-07-21 16:17:52 +00001195void InputDispatcher::postCommandLocked(Command&& command) {
1196 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197}
1198
1199void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001200 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001202 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 releaseInboundEventLocked(entry);
1204 }
1205 traceInboundQueueLengthLocked();
1206}
1207
1208void InputDispatcher::releasePendingEventLocked() {
1209 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001211 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213}
1214
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001217 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001218 if (DEBUG_DISPATCH_CYCLE) {
1219 ALOGD("Injected inbound event was dropped.");
1220 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001221 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001224 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 }
1226 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227}
1228
1229void InputDispatcher::resetKeyRepeatLocked() {
1230 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001231 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233}
1234
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1236 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237
Michael Wright2e732952014-09-24 13:26:59 -07001238 uint32_t policyFlags = entry->policyFlags &
1239 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 std::shared_ptr<KeyEntry> newEntry =
1242 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1243 entry->source, entry->displayId, policyFlags, entry->action,
1244 entry->flags, entry->keyCode, entry->scanCode,
1245 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247 newEntry->syntheticRepeat = true;
1248 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251}
1252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001253bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001255 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1256 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1257 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258
1259 // Reset key repeating in case a keyboard device was added or removed or something.
1260 resetKeyRepeatLocked();
1261
1262 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001263 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1264 scoped_unlock unlock(mLock);
1265 mPolicy->notifyConfigurationChanged(eventTime);
1266 };
1267 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 return true;
1269}
1270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1272 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001273 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1274 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1275 entry.deviceId);
1276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277
liushenxiang42232912021-05-21 20:24:09 +08001278 // Reset key repeating in case a keyboard device was disabled or enabled.
1279 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1280 resetKeyRepeatLocked();
1281 }
1282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001283 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 synthesizeCancelationEventsForAllConnectionsLocked(options);
1286 return true;
1287}
1288
Vishnu Nairad321cd2020-08-20 16:40:21 -07001289void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001290 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001291 if (mPendingEvent != nullptr) {
1292 // Move the pending event to the front of the queue. This will give the chance
1293 // for the pending event to get dispatched to the newly focused window
1294 mInboundQueue.push_front(mPendingEvent);
1295 mPendingEvent = nullptr;
1296 }
1297
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001298 std::unique_ptr<FocusEntry> focusEntry =
1299 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1300 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001301
1302 // This event should go to the front of the queue, but behind all other focus events
1303 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001305 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001306 [](const std::shared_ptr<EventEntry>& event) {
1307 return event->type == EventEntry::Type::FOCUS;
1308 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001309
1310 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001311 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001312}
1313
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001315 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001316 if (channel == nullptr) {
1317 return; // Window has gone away
1318 }
1319 InputTarget target;
1320 target.inputChannel = channel;
1321 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1322 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001323 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1324 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001325 std::string reason = std::string("reason=").append(entry->reason);
1326 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001327 dispatchEventLocked(currentTime, entry, {target});
1328}
1329
Prabir Pradhan99987712020-11-10 18:43:05 -08001330void InputDispatcher::dispatchPointerCaptureChangedLocked(
1331 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1332 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001333 dropReason = DropReason::NOT_DROPPED;
1334
Prabir Pradhan99987712020-11-10 18:43:05 -08001335 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001337
1338 if (entry->pointerCaptureRequest.enable) {
1339 // Enable Pointer Capture.
1340 if (haveWindowWithPointerCapture &&
1341 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1342 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1343 "to the window.");
1344 }
1345 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001346 // This can happen if a window requests capture and immediately releases capture.
1347 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001348 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 return;
1350 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001351 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1352 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1353 return;
1354 }
1355
Vishnu Nairc519ff72021-01-21 08:23:08 -08001356 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001357 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1358 mWindowTokenWithPointerCapture = token;
1359 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001360 // Disable Pointer Capture.
1361 // We do not check if the sequence number matches for requests to disable Pointer Capture
1362 // for two reasons:
1363 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1364 // to disable capture with the same sequence number: one generated by
1365 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1366 // Capture being disabled in InputReader.
1367 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1368 // actual Pointer Capture state that affects events being generated by input devices is
1369 // in InputReader.
1370 if (!haveWindowWithPointerCapture) {
1371 // Pointer capture was already forcefully disabled because of focus change.
1372 dropReason = DropReason::NOT_DROPPED;
1373 return;
1374 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 token = mWindowTokenWithPointerCapture;
1376 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001378 setPointerCaptureLocked(false);
1379 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001380 }
1381
1382 auto channel = getInputChannelLocked(token);
1383 if (channel == nullptr) {
1384 // Window has gone away, clean up Pointer Capture state.
1385 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001386 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001387 setPointerCaptureLocked(false);
1388 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001389 return;
1390 }
1391 InputTarget target;
1392 target.inputChannel = channel;
1393 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1394 entry->dispatchInProgress = true;
1395 dispatchEventLocked(currentTime, entry, {target});
1396
1397 dropReason = DropReason::NOT_DROPPED;
1398}
1399
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001400bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001403 if (!entry->dispatchInProgress) {
1404 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1405 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1406 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1407 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001408 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 // We have seen two identical key downs in a row which indicates that the device
1410 // driver is automatically generating key repeats itself. We take note of the
1411 // repeat here, but we disable our own next key repeat timer since it is clear that
1412 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001413 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1414 // Make sure we don't get key down from a different device. If a different
1415 // device Id has same key pressed down, the new device Id will replace the
1416 // current one to hold the key repeat with repeat count reset.
1417 // In the future when got a KEY_UP on the device id, drop it and do not
1418 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1420 resetKeyRepeatLocked();
1421 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1422 } else {
1423 // Not a repeat. Save key down state in case we do see a repeat later.
1424 resetKeyRepeatLocked();
1425 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1426 }
1427 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001428 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1429 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001430 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001431 if (DEBUG_INBOUND_EVENT_DETAILS) {
1432 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1433 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 resetKeyRepeatLocked();
1436 }
1437
1438 if (entry->repeatCount == 1) {
1439 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1440 } else {
1441 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1442 }
1443
1444 entry->dispatchInProgress = true;
1445
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001446 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 }
1448
1449 // Handle case where the policy asked us to try again later last time.
1450 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1451 if (currentTime < entry->interceptKeyWakeupTime) {
1452 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1453 *nextWakeupTime = entry->interceptKeyWakeupTime;
1454 }
1455 return false; // wait until next wakeup
1456 }
1457 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1458 entry->interceptKeyWakeupTime = 0;
1459 }
1460
1461 // Give the policy a chance to intercept the key.
1462 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1463 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001464 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001465 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001466
1467 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1468 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1469 };
1470 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 return false; // wait for the command to run
1472 } else {
1473 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1474 }
1475 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001476 if (*dropReason == DropReason::NOT_DROPPED) {
1477 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 }
1479 }
1480
1481 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001482 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001484 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1485 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001486 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 return true;
1488 }
1489
1490 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001491 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001492 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001493 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001494 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 return false;
1496 }
1497
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001498 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001499 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 return true;
1501 }
1502
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001503 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505
1506 // Dispatch the key.
1507 dispatchEventLocked(currentTime, entry, inputTargets);
1508 return true;
1509}
1510
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001511void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001512 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1513 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1514 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1515 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1516 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1517 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1518 entry.metaState, entry.repeatCount, entry.downTime);
1519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520}
1521
Prabir Pradhancef936d2021-07-21 16:17:52 +00001522void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1523 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001524 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001525 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1526 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1527 "source=0x%x, sensorType=%s",
1528 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1529 NamedEnum::string(entry->sensorType).c_str());
1530 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001531 auto command = [this, entry]() REQUIRES(mLock) {
1532 scoped_unlock unlock(mLock);
1533
1534 if (entry->accuracyChanged) {
1535 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1536 }
1537 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1538 entry->hwTimestamp, entry->values);
1539 };
1540 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001541}
1542
1543bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001544 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1545 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1546 NamedEnum::string(sensorType).c_str());
1547 }
Chris Yef59a2f42020-10-16 12:55:26 -07001548 { // acquire lock
1549 std::scoped_lock _l(mLock);
1550
1551 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1552 std::shared_ptr<EventEntry> entry = *it;
1553 if (entry->type == EventEntry::Type::SENSOR) {
1554 it = mInboundQueue.erase(it);
1555 releaseInboundEventLocked(entry);
1556 }
1557 }
1558 }
1559 return true;
1560}
1561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001564 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001566 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 entry->dispatchInProgress = true;
1568
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001569 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571
1572 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001573 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001574 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001575 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1576 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 return true;
1578 }
1579
1580 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1581
1582 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001583 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
1585 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 if (isPointerEvent) {
1588 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001589 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001590 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001591 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 } else {
1593 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001594 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001595 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001597 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 return false;
1599 }
1600
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001601 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001602 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001603 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1604 return true;
1605 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001606 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001607 CancelationOptions::Mode mode(isPointerEvent
1608 ? CancelationOptions::CANCEL_POINTER_EVENTS
1609 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1610 CancelationOptions options(mode, "input event injection failed");
1611 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 return true;
1613 }
1614
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001615 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001616 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617
1618 // Dispatch the motion.
1619 if (conflictingPointerActions) {
1620 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001621 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 synthesizeCancelationEventsForAllConnectionsLocked(options);
1623 }
1624 dispatchEventLocked(currentTime, entry, inputTargets);
1625 return true;
1626}
1627
chaviw98318de2021-05-19 16:45:23 -05001628void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001629 bool isExiting, const MotionEntry& motionEntry) {
1630 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1631 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1632 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1633 PointerCoords pointerCoords;
1634 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1635 pointerCoords.transform(windowHandle->getInfo()->transform);
1636
1637 std::unique_ptr<DragEntry> dragEntry =
1638 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1639 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1640 pointerCoords.getY());
1641
1642 enqueueInboundEventLocked(std::move(dragEntry));
1643}
1644
1645void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1646 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1647 if (channel == nullptr) {
1648 return; // Window has gone away
1649 }
1650 InputTarget target;
1651 target.inputChannel = channel;
1652 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1653 entry->dispatchInProgress = true;
1654 dispatchEventLocked(currentTime, entry, {target});
1655}
1656
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001658 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1659 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1660 ", policyFlags=0x%x, "
1661 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1662 "metaState=0x%x, buttonState=0x%x,"
1663 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1664 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1665 entry.policyFlags, entry.action, entry.actionButton, entry.flags, entry.metaState,
1666 entry.buttonState, entry.edgeFlags, entry.xPrecision, entry.yPrecision,
1667 entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001669 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1670 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1671 "x=%f, y=%f, pressure=%f, size=%f, "
1672 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1673 "orientation=%f",
1674 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1675 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1676 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1677 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1678 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1679 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1680 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1681 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1682 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1683 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686}
1687
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001688void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1689 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001690 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001691 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001692 if (DEBUG_DISPATCH_CYCLE) {
1693 ALOGD("dispatchEventToCurrentInputTargets");
1694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001696 updateInteractionTokensLocked(*eventEntry, inputTargets);
1697
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1699
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001700 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001702 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001703 sp<Connection> connection =
1704 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001705 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001706 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001708 if (DEBUG_FOCUS) {
1709 ALOGD("Dropping event delivery to target with channel '%s' because it "
1710 "is no longer registered with the input dispatcher.",
1711 inputTarget.inputChannel->getName().c_str());
1712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
1714 }
1715}
1716
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001717void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1718 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1719 // If the policy decides to close the app, we will get a channel removal event via
1720 // unregisterInputChannel, and will clean up the connection that way. We are already not
1721 // sending new pointers to the connection when it blocked, but focused events will continue to
1722 // pile up.
1723 ALOGW("Canceling events for %s because it is unresponsive",
1724 connection->inputChannel->getName().c_str());
1725 if (connection->status == Connection::STATUS_NORMAL) {
1726 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1727 "application not responding");
1728 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 }
1730}
1731
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001733 if (DEBUG_FOCUS) {
1734 ALOGD("Resetting ANR timeouts.");
1735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736
1737 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001738 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001739 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740}
1741
Tiger Huang721e26f2018-07-24 22:26:19 +08001742/**
1743 * Get the display id that the given event should go to. If this event specifies a valid display id,
1744 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1745 * Focused display is the display that the user most recently interacted with.
1746 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001748 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001749 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001750 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001751 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1752 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001753 break;
1754 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001755 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001756 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1757 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001758 break;
1759 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001760 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001761 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001762 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001763 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001764 case EventEntry::Type::SENSOR:
1765 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001766 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767 return ADISPLAY_ID_NONE;
1768 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001769 }
1770 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1771}
1772
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001773bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1774 const char* focusedWindowName) {
1775 if (mAnrTracker.empty()) {
1776 // already processed all events that we waited for
1777 mKeyIsWaitingForEventsTimeout = std::nullopt;
1778 return false;
1779 }
1780
1781 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1782 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001783 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001784 mKeyIsWaitingForEventsTimeout = currentTime +
1785 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1786 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787 return true;
1788 }
1789
1790 // We still have pending events, and already started the timer
1791 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1792 return true; // Still waiting
1793 }
1794
1795 // Waited too long, and some connection still hasn't processed all motions
1796 // Just send the key to the focused window
1797 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1798 focusedWindowName);
1799 mKeyIsWaitingForEventsTimeout = std::nullopt;
1800 return false;
1801}
1802
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001803InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1804 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1805 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001806 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
Tiger Huang721e26f2018-07-24 22:26:19 +08001808 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001809 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001810 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001811 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1812
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 // If there is no currently focused window and no focused application
1814 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001815 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1816 ALOGI("Dropping %s event because there is no focused window or focused application in "
1817 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001818 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001819 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
1821
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1823 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1824 // start interacting with another application via touch (app switch). This code can be removed
1825 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1826 // an app is expected to have a focused window.
1827 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1828 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1829 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001830 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1831 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1832 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001834 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001835 ALOGW("Waiting because no window has focus but %s may eventually add a "
1836 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001837 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001838 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001839 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001840 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1841 // Already raised ANR. Drop the event
1842 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001843 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001845 } else {
1846 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001848 }
1849 }
1850
1851 // we have a valid, non-null focused window
1852 resetNoFocusedWindowTimeoutLocked();
1853
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001855 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001856 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 }
1858
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001859 if (focusedWindowHandle->getInfo()->paused) {
1860 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001861 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001862 }
1863
1864 // If the event is a key event, then we must wait for all previous events to
1865 // complete before delivering it because previous events may have the
1866 // side-effect of transferring focus to a different window and we want to
1867 // ensure that the following keys are sent to the new window.
1868 //
1869 // Suppose the user touches a button in a window then immediately presses "A".
1870 // If the button causes a pop-up window to appear then we want to ensure that
1871 // the "A" key is delivered to the new pop-up window. This is because users
1872 // often anticipate pending UI changes when typing on a keyboard.
1873 // To obtain this behavior, we must serialize key events with respect to all
1874 // prior input events.
1875 if (entry.type == EventEntry::Type::KEY) {
1876 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1877 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 }
1881
1882 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001883 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001884 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1885 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886
1887 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889}
1890
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001891/**
1892 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1893 * that are currently unresponsive.
1894 */
1895std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1896 const std::vector<TouchedMonitor>& monitors) const {
1897 std::vector<TouchedMonitor> responsiveMonitors;
1898 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1899 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1900 sp<Connection> connection = getConnectionLocked(
1901 monitor.monitor.inputChannel->getConnectionToken());
1902 if (connection == nullptr) {
1903 ALOGE("Could not find connection for monitor %s",
1904 monitor.monitor.inputChannel->getName().c_str());
1905 return false;
1906 }
1907 if (!connection->responsive) {
1908 ALOGW("Unresponsive monitor %s will not get the new gesture",
1909 connection->inputChannel->getName().c_str());
1910 return false;
1911 }
1912 return true;
1913 });
1914 return responsiveMonitors;
1915}
1916
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1918 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1919 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001920 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 enum InjectionPermission {
1922 INJECTION_PERMISSION_UNKNOWN,
1923 INJECTION_PERMISSION_GRANTED,
1924 INJECTION_PERMISSION_DENIED
1925 };
1926
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 // For security reasons, we defer updating the touch state until we are sure that
1928 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001929 int32_t displayId = entry.displayId;
1930 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1932
1933 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001934 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001936 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1937 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 // Copy current touch state into tempTouchState.
1940 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1941 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001942 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001943 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001944 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1945 mTouchStatesByDisplay.find(displayId);
1946 if (oldStateIt != mTouchStatesByDisplay.end()) {
1947 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001948 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001949 }
1950
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001951 bool isSplit = tempTouchState.split;
1952 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1953 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1954 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001955 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1956 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1957 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1958 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1959 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001960 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 bool wrongDevice = false;
1962 if (newGesture) {
1963 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001964 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001965 ALOGI("Dropping event because a pointer for a different device is already down "
1966 "in display %" PRId32,
1967 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001968 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 switchedDevice = false;
1971 wrongDevice = true;
1972 goto Failed;
1973 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001974 tempTouchState.reset();
1975 tempTouchState.down = down;
1976 tempTouchState.deviceId = entry.deviceId;
1977 tempTouchState.source = entry.source;
1978 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001980 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001981 ALOGI("Dropping move event because a pointer for a different device is already active "
1982 "in display %" PRId32,
1983 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001984 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001985 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001986 switchedDevice = false;
1987 wrongDevice = true;
1988 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
1990
1991 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1992 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1993
Garfield Tan00f511d2019-06-12 16:55:40 -07001994 int32_t x;
1995 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001997 // Always dispatch mouse events to cursor position.
1998 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001999 x = int32_t(entry.xCursorPosition);
2000 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002001 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002002 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2003 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002004 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002005 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002006 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2007 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002008
2009 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002010 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00002011 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014 if (newTouchedWindowHandle != nullptr &&
2015 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002016 // New window supports splitting, but we should never split mouse events.
2017 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 } else if (isSplit) {
2019 // New window does not support splitting but we have already split events.
2020 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002021 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
2023
2024 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002025 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002027 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002028 }
2029
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002030 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2031 ALOGI("Not sending touch event to %s because it is paused",
2032 newTouchedWindowHandle->getName().c_str());
2033 newTouchedWindowHandle = nullptr;
2034 }
2035
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002036 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002037 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002038 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2039 if (!isResponsive) {
2040 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2042 newTouchedWindowHandle = nullptr;
2043 }
2044 }
2045
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002046 // Drop events that can't be trusted due to occlusion
2047 if (newTouchedWindowHandle != nullptr &&
2048 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2049 TouchOcclusionInfo occlusionInfo =
2050 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002051 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002052 if (DEBUG_TOUCH_OCCLUSION) {
2053 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2054 for (const auto& log : occlusionInfo.debugInfo) {
2055 ALOGD("%s", log.c_str());
2056 }
2057 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002058 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002059 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2060 ALOGW("Dropping untrusted touch event due to %s/%d",
2061 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2062 newTouchedWindowHandle = nullptr;
2063 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002064 }
2065 }
2066
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067 // Also don't send the new touch event to unresponsive gesture monitors
2068 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2069
Michael Wright3dd60e22019-03-27 22:06:44 +00002070 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2071 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002072 "(%d, %d) in display %" PRId32 ".",
2073 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002074 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002075 goto Failed;
2076 }
2077
2078 if (newTouchedWindowHandle != nullptr) {
2079 // Set target flags.
2080 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2081 if (isSplit) {
2082 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2085 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2086 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2087 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2088 }
2089
2090 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002091 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2092 newHoverWindowHandle = nullptr;
2093 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002094 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002095 }
2096
2097 // Update the temporary touch state.
2098 BitSet32 pointerIds;
2099 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002100 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002101 pointerIds.markBit(pointerId);
2102 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
2105
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002106 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 } else {
2108 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2109
2110 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002111 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002112 if (DEBUG_FOCUS) {
2113 ALOGD("Dropping event because the pointer is not down or we previously "
2114 "dropped the pointer down event in display %" PRId32,
2115 displayId);
2116 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002117 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 goto Failed;
2119 }
2120
arthurhung6d4bed92021-03-17 11:59:33 +08002121 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002122
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002124 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002125 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002126 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2127 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128
chaviw98318de2021-05-19 16:45:23 -05002129 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002130 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002131 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002132 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2133 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002134 if (DEBUG_FOCUS) {
2135 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2136 oldTouchedWindowHandle->getName().c_str(),
2137 newTouchedWindowHandle->getName().c_str(), displayId);
2138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002140 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2141 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2142 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
2144 // Make a slippery entrance into the new window.
2145 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2146 isSplit = true;
2147 }
2148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002149 int32_t targetFlags =
2150 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 if (isSplit) {
2152 targetFlags |= InputTarget::FLAG_SPLIT;
2153 }
2154 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2155 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002156 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2157 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 }
2159
2160 BitSet32 pointerIds;
2161 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002162 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002164 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166 }
2167 }
2168
2169 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002170 // Let the previous window know that the hover sequence is over, unless we already did it
2171 // when dispatching it as is to newTouchedWindowHandle.
2172 if (mLastHoverWindowHandle != nullptr &&
2173 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2174 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002175 if (DEBUG_HOVER) {
2176 ALOGD("Sending hover exit event to window %s.",
2177 mLastHoverWindowHandle->getName().c_str());
2178 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002179 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2180 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
2182
Garfield Tandf26e862020-07-01 20:18:19 -07002183 // Let the new window know that the hover sequence is starting, unless we already did it
2184 // when dispatching it as is to newTouchedWindowHandle.
2185 if (newHoverWindowHandle != nullptr &&
2186 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2187 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002188 if (DEBUG_HOVER) {
2189 ALOGD("Sending hover enter event to window %s.",
2190 newHoverWindowHandle->getName().c_str());
2191 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002192 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2193 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2194 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
2196 }
2197
2198 // Check permission to inject into all touched foreground windows and ensure there
2199 // is at least one touched foreground window.
2200 {
2201 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002202 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2204 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002205 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002206 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 injectionPermission = INJECTION_PERMISSION_DENIED;
2208 goto Failed;
2209 }
2210 }
2211 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002213 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002214 ALOGI("Dropping event because there is no touched foreground window in display "
2215 "%" PRId32 " or gesture monitor to receive it.",
2216 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002217 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 goto Failed;
2219 }
2220
2221 // Permission granted to injection into all touched foreground windows.
2222 injectionPermission = INJECTION_PERMISSION_GRANTED;
2223 }
2224
2225 // Check whether windows listening for outside touches are owned by the same UID. If it is
2226 // set the policy flag that we will not reveal coordinate information to this window.
2227 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002228 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 if (foregroundWindowHandle) {
2231 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002232 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002233 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002234 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2235 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2236 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 InputTarget::FLAG_ZERO_COORDS,
2238 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
2241 }
2242 }
2243 }
2244
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // If this is the first pointer going down and the touched window has a wallpaper
2246 // then also add the touched wallpaper windows so they are locked in for the duration
2247 // of the touch gesture.
2248 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2249 // engine only supports touch events. We would need to add a mechanism similar
2250 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2251 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002252 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002253 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002254 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002255 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002256 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002257 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2258 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002260 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002261 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262 .addOrUpdateWindow(windowHandle,
2263 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2264 InputTarget::
2265 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2266 InputTarget::FLAG_DISPATCH_AS_IS,
2267 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269 }
2270 }
2271 }
2272
2273 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002274 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
2280
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 }
2285
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 // Drop the outside or hover touch windows since we will not care about them
2287 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289
2290Failed:
2291 // Check injection permission once and for all.
2292 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002293 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 injectionPermission = INJECTION_PERMISSION_GRANTED;
2295 } else {
2296 injectionPermission = INJECTION_PERMISSION_DENIED;
2297 }
2298 }
2299
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002300 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2301 return injectionResult;
2302 }
2303
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002305 if (!wrongDevice) {
2306 if (switchedDevice) {
2307 if (DEBUG_FOCUS) {
2308 ALOGD("Conflicting pointer actions: Switched to a different device.");
2309 }
2310 *outConflictingPointerActions = true;
2311 }
2312
2313 if (isHoverAction) {
2314 // Started hovering, therefore no longer down.
2315 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002316 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002317 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2318 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 *outConflictingPointerActions = true;
2321 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002322 tempTouchState.reset();
2323 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2324 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2325 tempTouchState.deviceId = entry.deviceId;
2326 tempTouchState.source = entry.source;
2327 tempTouchState.displayId = displayId;
2328 }
2329 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2330 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2331 // All pointers up or canceled.
2332 tempTouchState.reset();
2333 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2334 // First pointer went down.
2335 if (oldState && oldState->down) {
2336 if (DEBUG_FOCUS) {
2337 ALOGD("Conflicting pointer actions: Down received while already down.");
2338 }
2339 *outConflictingPointerActions = true;
2340 }
2341 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2342 // One pointer went up.
2343 if (isSplit) {
2344 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2345 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002347 for (size_t i = 0; i < tempTouchState.windows.size();) {
2348 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2349 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2350 touchedWindow.pointerIds.clearBit(pointerId);
2351 if (touchedWindow.pointerIds.isEmpty()) {
2352 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2353 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002356 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002358 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002359 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002360
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002361 // Save changes unless the action was scroll in which case the temporary touch
2362 // state was only valid for this one action.
2363 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2364 if (tempTouchState.displayId >= 0) {
2365 mTouchStatesByDisplay[displayId] = tempTouchState;
2366 } else {
2367 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 // Update hover state.
2372 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 return injectionResult;
2376}
2377
arthurhung6d4bed92021-03-17 11:59:33 +08002378void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002379 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002380 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002381 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002382 if (dropWindow) {
2383 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002384 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002385 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002386 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002387 }
2388 mDragState.reset();
2389}
2390
2391void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2392 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002393 return;
2394 }
2395
arthurhung6d4bed92021-03-17 11:59:33 +08002396 if (!mDragState->isStartDrag) {
2397 mDragState->isStartDrag = true;
2398 mDragState->isStylusButtonDownAtStart =
2399 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2400 }
2401
arthurhungb89ccb02020-12-30 16:19:01 +08002402 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2403 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2404 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2405 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002406 // Handle the special case : stylus button no longer pressed.
2407 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2408 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2409 finishDragAndDrop(entry.displayId, x, y);
2410 return;
2411 }
2412
chaviw98318de2021-05-19 16:45:23 -05002413 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002414 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002415 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002416 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002417 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2418 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2419 if (mDragState->dragHoverWindowHandle != nullptr) {
2420 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2421 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002422 }
arthurhung6d4bed92021-03-17 11:59:33 +08002423 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002424 }
2425 // enqueue drag location if needed.
2426 if (hoverWindowHandle != nullptr) {
2427 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2428 }
arthurhung6d4bed92021-03-17 11:59:33 +08002429 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2430 finishDragAndDrop(entry.displayId, x, y);
2431 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002432 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002433 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002434 }
2435}
2436
chaviw98318de2021-05-19 16:45:23 -05002437void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 int32_t targetFlags, BitSet32 pointerIds,
2439 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002440 std::vector<InputTarget>::iterator it =
2441 std::find_if(inputTargets.begin(), inputTargets.end(),
2442 [&windowHandle](const InputTarget& inputTarget) {
2443 return inputTarget.inputChannel->getConnectionToken() ==
2444 windowHandle->getToken();
2445 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002446
chaviw98318de2021-05-19 16:45:23 -05002447 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002448
2449 if (it == inputTargets.end()) {
2450 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002451 std::shared_ptr<InputChannel> inputChannel =
2452 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002453 if (inputChannel == nullptr) {
2454 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2455 return;
2456 }
2457 inputTarget.inputChannel = inputChannel;
2458 inputTarget.flags = targetFlags;
2459 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002460 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002461 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002462 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002463 inputTargets.push_back(inputTarget);
2464 it = inputTargets.end() - 1;
2465 }
2466
2467 ALOG_ASSERT(it->flags == targetFlags);
2468 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2469
chaviw1ff3d1e2020-07-01 15:53:47 -07002470 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471}
2472
Michael Wright3dd60e22019-03-27 22:06:44 +00002473void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002474 int32_t displayId, float xOffset,
2475 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002476 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2477 mGlobalMonitorsByDisplay.find(displayId);
2478
2479 if (it != mGlobalMonitorsByDisplay.end()) {
2480 const std::vector<Monitor>& monitors = it->second;
2481 for (const Monitor& monitor : monitors) {
2482 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
2485}
2486
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2488 float yOffset,
2489 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002490 InputTarget target;
2491 target.inputChannel = monitor.inputChannel;
2492 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002493 ui::Transform t;
2494 t.set(xOffset, yOffset);
2495 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002496 inputTargets.push_back(target);
2497}
2498
chaviw98318de2021-05-19 16:45:23 -05002499bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002500 const InjectionState* injectionState) {
2501 if (injectionState &&
2502 (windowHandle == nullptr ||
2503 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2504 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002505 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002507 "owned by uid %d",
2508 injectionState->injectorPid, injectionState->injectorUid,
2509 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 } else {
2511 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002512 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
2514 return false;
2515 }
2516 return true;
2517}
2518
Robert Carrc9bf1d32020-04-13 17:21:08 -07002519/**
2520 * Indicate whether one window handle should be considered as obscuring
2521 * another window handle. We only check a few preconditions. Actually
2522 * checking the bounds is left to the caller.
2523 */
chaviw98318de2021-05-19 16:45:23 -05002524static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2525 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002526 // Compare by token so cloned layers aren't counted
2527 if (haveSameToken(windowHandle, otherHandle)) {
2528 return false;
2529 }
2530 auto info = windowHandle->getInfo();
2531 auto otherInfo = otherHandle->getInfo();
2532 if (!otherInfo->visible) {
2533 return false;
chaviw98318de2021-05-19 16:45:23 -05002534 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002535 // Those act as if they were invisible, so we don't need to flag them.
2536 // We do want to potentially flag touchable windows even if they have 0
2537 // opacity, since they can consume touches and alter the effects of the
2538 // user interaction (eg. apps that rely on
2539 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2540 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2541 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002542 } else if (info->ownerUid == otherInfo->ownerUid) {
2543 // If ownerUid is the same we don't generate occlusion events as there
2544 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002545 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002546 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002547 return false;
2548 } else if (otherInfo->displayId != info->displayId) {
2549 return false;
2550 }
2551 return true;
2552}
2553
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002554/**
2555 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2556 * untrusted, one should check:
2557 *
2558 * 1. If result.hasBlockingOcclusion is true.
2559 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2560 * BLOCK_UNTRUSTED.
2561 *
2562 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2563 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2564 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2565 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2566 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2567 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2568 *
2569 * If neither of those is true, then it means the touch can be allowed.
2570 */
2571InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002572 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2573 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002574 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002575 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002576 TouchOcclusionInfo info;
2577 info.hasBlockingOcclusion = false;
2578 info.obscuringOpacity = 0;
2579 info.obscuringUid = -1;
2580 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002581 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002582 if (windowHandle == otherHandle) {
2583 break; // All future windows are below us. Exit early.
2584 }
chaviw98318de2021-05-19 16:45:23 -05002585 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002586 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2587 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002588 if (DEBUG_TOUCH_OCCLUSION) {
2589 info.debugInfo.push_back(
2590 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2591 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002592 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2593 // we perform the checks below to see if the touch can be propagated or not based on the
2594 // window's touch occlusion mode
2595 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2596 info.hasBlockingOcclusion = true;
2597 info.obscuringUid = otherInfo->ownerUid;
2598 info.obscuringPackage = otherInfo->packageName;
2599 break;
2600 }
2601 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2602 uint32_t uid = otherInfo->ownerUid;
2603 float opacity =
2604 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2605 // Given windows A and B:
2606 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2607 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2608 opacityByUid[uid] = opacity;
2609 if (opacity > info.obscuringOpacity) {
2610 info.obscuringOpacity = opacity;
2611 info.obscuringUid = uid;
2612 info.obscuringPackage = otherInfo->packageName;
2613 }
2614 }
2615 }
2616 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002617 if (DEBUG_TOUCH_OCCLUSION) {
2618 info.debugInfo.push_back(
2619 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2620 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002621 return info;
2622}
2623
chaviw98318de2021-05-19 16:45:23 -05002624std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002625 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002626 return StringPrintf(INDENT2
2627 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2628 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2629 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2630 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002631 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002632 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002633 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002634 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2635 info->frameTop, info->frameRight, info->frameBottom,
2636 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002637 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2638 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2639 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002640}
2641
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002642bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2643 if (occlusionInfo.hasBlockingOcclusion) {
2644 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2645 occlusionInfo.obscuringUid);
2646 return false;
2647 }
2648 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2649 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2650 "%.2f, maximum allowed = %.2f)",
2651 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2652 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2653 return false;
2654 }
2655 return true;
2656}
2657
chaviw98318de2021-05-19 16:45:23 -05002658bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002661 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2662 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002663 if (windowHandle == otherHandle) {
2664 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 }
chaviw98318de2021-05-19 16:45:23 -05002666 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002667 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002668 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 return true;
2670 }
2671 }
2672 return false;
2673}
2674
chaviw98318de2021-05-19 16:45:23 -05002675bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002676 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002677 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2678 const WindowInfo* windowInfo = windowHandle->getInfo();
2679 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002680 if (windowHandle == otherHandle) {
2681 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002682 }
chaviw98318de2021-05-19 16:45:23 -05002683 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002684 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002685 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002686 return true;
2687 }
2688 }
2689 return false;
2690}
2691
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002692std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002693 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002694 if (applicationHandle != nullptr) {
2695 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002696 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 } else {
2698 return applicationHandle->getName();
2699 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002700 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002701 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002703 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
2705}
2706
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002707void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002708 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002709 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2710 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002711 // Focus or pointer capture changed events are passed to apps, but do not represent user
2712 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002713 return;
2714 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002715 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002716 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002717 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002718 const WindowInfo* info = focusedWindowHandle->getInfo();
2719 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002720 if (DEBUG_DISPATCH_CYCLE) {
2721 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 return;
2724 }
2725 }
2726
2727 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002728 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002729 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002730 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2731 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 return;
2733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002735 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 eventType = USER_ACTIVITY_EVENT_TOUCH;
2737 }
2738 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002740 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002741 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2742 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 return;
2744 }
2745 eventType = USER_ACTIVITY_EVENT_BUTTON;
2746 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002748 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002749 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002750 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002751 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002752 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2753 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002754 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002755 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002756 break;
2757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 }
2759
Prabir Pradhancef936d2021-07-21 16:17:52 +00002760 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2761 REQUIRES(mLock) {
2762 scoped_unlock unlock(mLock);
2763 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2764 };
2765 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766}
2767
2768void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002770 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002771 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002772 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002774 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002775 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002776 ATRACE_NAME(message.c_str());
2777 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002778 if (DEBUG_DISPATCH_CYCLE) {
2779 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2780 "globalScaleFactor=%f, pointerIds=0x%x %s",
2781 connection->getInputChannelName().c_str(), inputTarget.flags,
2782 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2783 inputTarget.getPointerInfoString().c_str());
2784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785
2786 // Skip this event if the connection status is not normal.
2787 // We don't want to enqueue additional outbound events if the connection is broken.
2788 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002789 if (DEBUG_DISPATCH_CYCLE) {
2790 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2791 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 return;
2794 }
2795
2796 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002797 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2798 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2799 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002800 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002802 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002803 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002804 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002805 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 if (!splitMotionEntry) {
2807 return; // split event was dropped
2808 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002809 if (DEBUG_FOCUS) {
2810 ALOGD("channel '%s' ~ Split motion event.",
2811 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002812 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002813 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002814 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2815 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 return;
2817 }
2818 }
2819
2820 // Not splitting. Enqueue dispatch entries for the event as is.
2821 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2822}
2823
2824void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002826 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002827 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002828 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002830 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002831 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002832 ATRACE_NAME(message.c_str());
2833 }
2834
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002835 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836
2837 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002844 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002846 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002848 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850
2851 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002852 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 startDispatchCycleLocked(currentTime, connection);
2854 }
2855}
2856
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002858 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002859 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002861 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002862 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2863 connection->getInputChannelName().c_str(),
2864 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002865 ATRACE_NAME(message.c_str());
2866 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002867 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 if (!(inputTargetFlags & dispatchMode)) {
2869 return;
2870 }
2871 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2872
2873 // This is a new event.
2874 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002875 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002876 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002878 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2879 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002880 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002882 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002883 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002884 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002885 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002886 dispatchEntry->resolvedAction = keyEntry.action;
2887 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2890 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002891 if (DEBUG_DISPATCH_CYCLE) {
2892 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2893 "event",
2894 connection->getInputChannelName().c_str());
2895 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 return; // skip the inconsistent event
2897 }
2898 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002901 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002902 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002903 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2904 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2905 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2906 static_cast<int32_t>(IdGenerator::Source::OTHER);
2907 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002908 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2909 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2910 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2911 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2912 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2913 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2914 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2915 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2916 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2917 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2918 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002919 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002920 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 }
2922 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2924 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002925 if (DEBUG_DISPATCH_CYCLE) {
2926 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2927 "enter event",
2928 connection->getInputChannelName().c_str());
2929 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002930 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2931 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002935 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2937 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2938 }
2939 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2940 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2944 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002945 if (DEBUG_DISPATCH_CYCLE) {
2946 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2947 "event",
2948 connection->getInputChannelName().c_str());
2949 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950 return; // skip the inconsistent event
2951 }
2952
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002953 dispatchEntry->resolvedEventId =
2954 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2955 ? mIdGenerator.nextId()
2956 : motionEntry.id;
2957 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2958 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2959 ") to MotionEvent(id=0x%" PRIx32 ").",
2960 motionEntry.id, dispatchEntry->resolvedEventId);
2961 ATRACE_NAME(message.c_str());
2962 }
2963
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002964 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2965 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2966 // Skip reporting pointer down outside focus to the policy.
2967 break;
2968 }
2969
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002970 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002971 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972
2973 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002975 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002976 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2977 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002978 break;
2979 }
Chris Yef59a2f42020-10-16 12:55:26 -07002980 case EventEntry::Type::SENSOR: {
2981 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2982 break;
2983 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002984 case EventEntry::Type::CONFIGURATION_CHANGED:
2985 case EventEntry::Type::DEVICE_RESET: {
2986 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002987 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002988 break;
2989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 }
2991
2992 // Remember that we are waiting for this dispatch to complete.
2993 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002994 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 }
2996
2997 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002998 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002999 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003000}
3001
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003002/**
3003 * This function is purely for debugging. It helps us understand where the user interaction
3004 * was taking place. For example, if user is touching launcher, we will see a log that user
3005 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3006 * We will see both launcher and wallpaper in that list.
3007 * Once the interaction with a particular set of connections starts, no new logs will be printed
3008 * until the set of interacted connections changes.
3009 *
3010 * The following items are skipped, to reduce the logspam:
3011 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3012 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3013 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3014 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3015 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003016 */
3017void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3018 const std::vector<InputTarget>& targets) {
3019 // Skip ACTION_UP events, and all events other than keys and motions
3020 if (entry.type == EventEntry::Type::KEY) {
3021 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3022 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3023 return;
3024 }
3025 } else if (entry.type == EventEntry::Type::MOTION) {
3026 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3027 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3028 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3029 return;
3030 }
3031 } else {
3032 return; // Not a key or a motion
3033 }
3034
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003035 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003036 std::vector<sp<Connection>> newConnections;
3037 for (const InputTarget& target : targets) {
3038 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3039 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3040 continue; // Skip windows that receive ACTION_OUTSIDE
3041 }
3042
3043 sp<IBinder> token = target.inputChannel->getConnectionToken();
3044 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003045 if (connection == nullptr) {
3046 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003047 }
3048 newConnectionTokens.insert(std::move(token));
3049 newConnections.emplace_back(connection);
3050 }
3051 if (newConnectionTokens == mInteractionConnectionTokens) {
3052 return; // no change
3053 }
3054 mInteractionConnectionTokens = newConnectionTokens;
3055
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003056 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003057 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003058 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003059 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003060 std::string message = "Interaction with: " + targetList;
3061 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003062 message += "<none>";
3063 }
3064 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3065}
3066
chaviwfd6d3512019-03-25 13:23:49 -07003067void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003068 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003069 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003070 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3071 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003072 return;
3073 }
3074
Vishnu Nairc519ff72021-01-21 08:23:08 -08003075 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003076 if (focusedToken == token) {
3077 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003078 return;
3079 }
3080
Prabir Pradhancef936d2021-07-21 16:17:52 +00003081 auto command = [this, token]() REQUIRES(mLock) {
3082 scoped_unlock unlock(mLock);
3083 mPolicy->onPointerDownOutsideFocus(token);
3084 };
3085 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086}
3087
3088void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003090 if (ATRACE_ENABLED()) {
3091 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003093 ATRACE_NAME(message.c_str());
3094 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003095 if (DEBUG_DISPATCH_CYCLE) {
3096 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003099 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3100 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003102 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003103 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003104 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
3106 // Publish the event.
3107 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3109 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003110 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003111 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3112 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003115 status = connection->inputPublisher
3116 .publishKeyEvent(dispatchEntry->seq,
3117 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3118 keyEntry.source, keyEntry.displayId,
3119 std::move(hmac), dispatchEntry->resolvedAction,
3120 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3121 keyEntry.scanCode, keyEntry.metaState,
3122 keyEntry.repeatCount, keyEntry.downTime,
3123 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 }
3126
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003127 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132
chaviw82357092020-01-28 13:13:06 -08003133 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003134 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3136 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003137 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003138 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3139 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003140 // Don't apply window scale here since we don't want scale to affect raw
3141 // coordinates. The scale will be sent back to the client and applied
3142 // later when requesting relative coordinates.
3143 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3144 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 }
3146 usingCoords = scaledCoords;
3147 }
3148 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 // We don't want the dispatch target to know.
3150 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003151 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 scaledCoords[i].clear();
3153 }
3154 usingCoords = scaledCoords;
3155 }
3156 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003157
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003158 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159
3160 // Publish the motion event.
3161 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003162 .publishMotionEvent(dispatchEntry->seq,
3163 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 motionEntry.deviceId, motionEntry.source,
3165 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003166 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003167 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003169 motionEntry.edgeFlags, motionEntry.metaState,
3170 motionEntry.buttonState,
3171 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003172 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003173 motionEntry.xPrecision, motionEntry.yPrecision,
3174 motionEntry.xCursorPosition,
3175 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003176 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003177 dispatchEntry->displaySize.x,
3178 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003179 motionEntry.downTime, motionEntry.eventTime,
3180 motionEntry.pointerCount,
3181 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 break;
3183 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003184
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003185 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003186 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003187 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 focusEntry.id,
3189 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003190 mInTouchMode);
3191 break;
3192 }
3193
Prabir Pradhan99987712020-11-10 18:43:05 -08003194 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3195 const auto& captureEntry =
3196 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3197 status = connection->inputPublisher
3198 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003199 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003200 break;
3201 }
3202
arthurhungb89ccb02020-12-30 16:19:01 +08003203 case EventEntry::Type::DRAG: {
3204 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3205 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3206 dragEntry.id, dragEntry.x,
3207 dragEntry.y,
3208 dragEntry.isExiting);
3209 break;
3210 }
3211
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003212 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003213 case EventEntry::Type::DEVICE_RESET:
3214 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003215 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003216 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220
3221 // Check the result.
3222 if (status) {
3223 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003224 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 "This is unexpected because the wait queue is empty, so the pipe "
3227 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003228 "event to it, status=%s(%d)",
3229 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3230 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3232 } else {
3233 // Pipe is full and we are waiting for the app to finish process some events
3234 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003235 if (DEBUG_DISPATCH_CYCLE) {
3236 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3237 "waiting for the application to catch up",
3238 connection->getInputChannelName().c_str());
3239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 }
3241 } else {
3242 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003243 "status=%s(%d)",
3244 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3245 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3247 }
3248 return;
3249 }
3250
3251 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003252 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3253 connection->outboundQueue.end(),
3254 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003255 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003256 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003257 if (connection->responsive) {
3258 mAnrTracker.insert(dispatchEntry->timeoutTime,
3259 connection->inputChannel->getConnectionToken());
3260 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003261 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262 }
3263}
3264
chaviw09c8d2d2020-08-24 15:48:26 -07003265std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3266 size_t size;
3267 switch (event.type) {
3268 case VerifiedInputEvent::Type::KEY: {
3269 size = sizeof(VerifiedKeyEvent);
3270 break;
3271 }
3272 case VerifiedInputEvent::Type::MOTION: {
3273 size = sizeof(VerifiedMotionEvent);
3274 break;
3275 }
3276 }
3277 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3278 return mHmacKeyManager.sign(start, size);
3279}
3280
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003281const std::array<uint8_t, 32> InputDispatcher::getSignature(
3282 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3283 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3284 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3285 // Only sign events up and down events as the purely move events
3286 // are tied to their up/down counterparts so signing would be redundant.
3287 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3288 verifiedEvent.actionMasked = actionMasked;
3289 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003290 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003291 }
3292 return INVALID_HMAC;
3293}
3294
3295const std::array<uint8_t, 32> InputDispatcher::getSignature(
3296 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3297 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3298 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3299 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003300 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003301}
3302
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003305 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003306 if (DEBUG_DISPATCH_CYCLE) {
3307 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3308 connection->getInputChannelName().c_str(), seq, toString(handled));
3309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 if (connection->status == Connection::STATUS_BROKEN ||
3312 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 return;
3314 }
3315
3316 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003317 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3318 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3319 };
3320 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321}
3322
3323void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 const sp<Connection>& connection,
3325 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003326 if (DEBUG_DISPATCH_CYCLE) {
3327 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3328 connection->getInputChannelName().c_str(), toString(notify));
3329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003332 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003333 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003334 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003335 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
3337 // The connection appears to be unrecoverably broken.
3338 // Ignore already broken or zombie connections.
3339 if (connection->status == Connection::STATUS_NORMAL) {
3340 connection->status = Connection::STATUS_BROKEN;
3341
3342 if (notify) {
3343 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003344 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3345 connection->getInputChannelName().c_str());
3346
3347 auto command = [this, connection]() REQUIRES(mLock) {
3348 if (connection->status == Connection::STATUS_ZOMBIE) return;
3349 scoped_unlock unlock(mLock);
3350 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3351 };
3352 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354 }
3355}
3356
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003357void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3358 while (!queue.empty()) {
3359 DispatchEntry* dispatchEntry = queue.front();
3360 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003361 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 }
3363}
3364
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003365void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003367 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
3369 delete dispatchEntry;
3370}
3371
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003372int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3373 std::scoped_lock _l(mLock);
3374 sp<Connection> connection = getConnectionLocked(connectionToken);
3375 if (connection == nullptr) {
3376 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3377 connectionToken.get(), events);
3378 return 0; // remove the callback
3379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003381 bool notify;
3382 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3383 if (!(events & ALOOPER_EVENT_INPUT)) {
3384 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3385 "events=0x%x",
3386 connection->getInputChannelName().c_str(), events);
3387 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003390 nsecs_t currentTime = now();
3391 bool gotOne = false;
3392 status_t status = OK;
3393 for (;;) {
3394 Result<InputPublisher::ConsumerResponse> result =
3395 connection->inputPublisher.receiveConsumerResponse();
3396 if (!result.ok()) {
3397 status = result.error().code();
3398 break;
3399 }
3400
3401 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3402 const InputPublisher::Finished& finish =
3403 std::get<InputPublisher::Finished>(*result);
3404 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3405 finish.consumeTime);
3406 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003407 if (shouldReportMetricsForConnection(*connection)) {
3408 const InputPublisher::Timeline& timeline =
3409 std::get<InputPublisher::Timeline>(*result);
3410 mLatencyTracker
3411 .trackGraphicsLatency(timeline.inputEventId,
3412 connection->inputChannel->getConnectionToken(),
3413 std::move(timeline.graphicsTimeline));
3414 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003415 }
3416 gotOne = true;
3417 }
3418 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003419 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003420 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 return 1;
3422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003425 notify = status != DEAD_OBJECT || !connection->monitor;
3426 if (notify) {
3427 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3428 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3429 status);
3430 }
3431 } else {
3432 // Monitor channels are never explicitly unregistered.
3433 // We do it automatically when the remote endpoint is closed so don't warn about them.
3434 const bool stillHaveWindowHandle =
3435 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3436 notify = !connection->monitor && stillHaveWindowHandle;
3437 if (notify) {
3438 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3439 connection->getInputChannelName().c_str(), events);
3440 }
3441 }
3442
3443 // Remove the channel.
3444 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3445 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446}
3447
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003450 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003451 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 }
3453}
3454
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003455void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003456 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003457 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3458 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3459}
3460
3461void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3462 const CancelationOptions& options,
3463 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3464 for (const auto& it : monitorsByDisplay) {
3465 const std::vector<Monitor>& monitors = it.second;
3466 for (const Monitor& monitor : monitors) {
3467 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003468 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003469 }
3470}
3471
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003473 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003474 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003475 if (connection == nullptr) {
3476 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003478
3479 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480}
3481
3482void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3483 const sp<Connection>& connection, const CancelationOptions& options) {
3484 if (connection->status == Connection::STATUS_BROKEN) {
3485 return;
3486 }
3487
3488 nsecs_t currentTime = now();
3489
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003490 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003491 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003493 if (cancelationEvents.empty()) {
3494 return;
3495 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003496 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3497 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3498 "with reality: %s, mode=%d.",
3499 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3500 options.mode);
3501 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003502
3503 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003504 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003505 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3506 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003507 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003508 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003509 target.globalScaleFactor = windowInfo->globalScaleFactor;
3510 }
3511 target.inputChannel = connection->inputChannel;
3512 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3513
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003514 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003515 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003516 switch (cancelationEventEntry->type) {
3517 case EventEntry::Type::KEY: {
3518 logOutboundKeyDetails("cancel - ",
3519 static_cast<const KeyEntry&>(*cancelationEventEntry));
3520 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003522 case EventEntry::Type::MOTION: {
3523 logOutboundMotionDetails("cancel - ",
3524 static_cast<const MotionEntry&>(*cancelationEventEntry));
3525 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003527 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003528 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3529 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003530 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003531 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003532 break;
3533 }
3534 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003535 case EventEntry::Type::DEVICE_RESET:
3536 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003537 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003538 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003539 break;
3540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 }
3542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003543 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3544 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003546
3547 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548}
3549
Svet Ganov5d3bc372020-01-26 23:11:07 -08003550void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3551 const sp<Connection>& connection) {
3552 if (connection->status == Connection::STATUS_BROKEN) {
3553 return;
3554 }
3555
3556 nsecs_t currentTime = now();
3557
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003558 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003559 connection->inputState.synthesizePointerDownEvents(currentTime);
3560
3561 if (downEvents.empty()) {
3562 return;
3563 }
3564
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003566 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3567 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003568 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569
3570 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003571 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003572 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3573 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003574 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003575 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003576 target.globalScaleFactor = windowInfo->globalScaleFactor;
3577 }
3578 target.inputChannel = connection->inputChannel;
3579 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003581 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582 switch (downEventEntry->type) {
3583 case EventEntry::Type::MOTION: {
3584 logOutboundMotionDetails("down - ",
3585 static_cast<const MotionEntry&>(*downEventEntry));
3586 break;
3587 }
3588
3589 case EventEntry::Type::KEY:
3590 case EventEntry::Type::FOCUS:
3591 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003592 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003593 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003594 case EventEntry::Type::SENSOR:
3595 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003596 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003597 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003598 break;
3599 }
3600 }
3601
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3603 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003604 }
3605
3606 startDispatchCycleLocked(currentTime, connection);
3607}
3608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003609std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3610 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 ALOG_ASSERT(pointerIds.value != 0);
3612
3613 uint32_t splitPointerIndexMap[MAX_POINTERS];
3614 PointerProperties splitPointerProperties[MAX_POINTERS];
3615 PointerCoords splitPointerCoords[MAX_POINTERS];
3616
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003617 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 uint32_t splitPointerCount = 0;
3619
3620 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003621 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003623 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 uint32_t pointerId = uint32_t(pointerProperties.id);
3625 if (pointerIds.hasBit(pointerId)) {
3626 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3627 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3628 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003629 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 splitPointerCount += 1;
3631 }
3632 }
3633
3634 if (splitPointerCount != pointerIds.count()) {
3635 // This is bad. We are missing some of the pointers that we expected to deliver.
3636 // Most likely this indicates that we received an ACTION_MOVE events that has
3637 // different pointer ids than we expected based on the previous ACTION_DOWN
3638 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3639 // in this way.
3640 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003641 "we expected there to be %d pointers. This probably means we received "
3642 "a broken sequence of pointer ids from the input device.",
3643 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003644 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003647 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003649 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3650 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3652 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003653 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 uint32_t pointerId = uint32_t(pointerProperties.id);
3655 if (pointerIds.hasBit(pointerId)) {
3656 if (pointerIds.count() == 1) {
3657 // The first/last pointer went down/up.
3658 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003660 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3661 ? AMOTION_EVENT_ACTION_CANCEL
3662 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 } else {
3664 // A secondary pointer went down/up.
3665 uint32_t splitPointerIndex = 0;
3666 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3667 splitPointerIndex += 1;
3668 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003669 action = maskedAction |
3670 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 }
3672 } else {
3673 // An unrelated pointer changed.
3674 action = AMOTION_EVENT_ACTION_MOVE;
3675 }
3676 }
3677
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003678 int32_t newId = mIdGenerator.nextId();
3679 if (ATRACE_ENABLED()) {
3680 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3681 ") to MotionEvent(id=0x%" PRIx32 ").",
3682 originalMotionEntry.id, newId);
3683 ATRACE_NAME(message.c_str());
3684 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003685 std::unique_ptr<MotionEntry> splitMotionEntry =
3686 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3687 originalMotionEntry.deviceId, originalMotionEntry.source,
3688 originalMotionEntry.displayId,
3689 originalMotionEntry.policyFlags, action,
3690 originalMotionEntry.actionButton,
3691 originalMotionEntry.flags, originalMotionEntry.metaState,
3692 originalMotionEntry.buttonState,
3693 originalMotionEntry.classification,
3694 originalMotionEntry.edgeFlags,
3695 originalMotionEntry.xPrecision,
3696 originalMotionEntry.yPrecision,
3697 originalMotionEntry.xCursorPosition,
3698 originalMotionEntry.yCursorPosition,
3699 originalMotionEntry.downTime, splitPointerCount,
3700 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003702 if (originalMotionEntry.injectionState) {
3703 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 splitMotionEntry->injectionState->refCount += 1;
3705 }
3706
3707 return splitMotionEntry;
3708}
3709
3710void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003711 if (DEBUG_INBOUND_EVENT_DETAILS) {
3712 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714
3715 bool needWake;
3716 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003717 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003719 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3720 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3721 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 } // release lock
3723
3724 if (needWake) {
3725 mLooper->wake();
3726 }
3727}
3728
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003729/**
3730 * If one of the meta shortcuts is detected, process them here:
3731 * Meta + Backspace -> generate BACK
3732 * Meta + Enter -> generate HOME
3733 * This will potentially overwrite keyCode and metaState.
3734 */
3735void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003737 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3738 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3739 if (keyCode == AKEYCODE_DEL) {
3740 newKeyCode = AKEYCODE_BACK;
3741 } else if (keyCode == AKEYCODE_ENTER) {
3742 newKeyCode = AKEYCODE_HOME;
3743 }
3744 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003745 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003746 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003747 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003748 keyCode = newKeyCode;
3749 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3750 }
3751 } else if (action == AKEY_EVENT_ACTION_UP) {
3752 // In order to maintain a consistent stream of up and down events, check to see if the key
3753 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3754 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003755 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003756 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003757 auto replacementIt = mReplacedKeys.find(replacement);
3758 if (replacementIt != mReplacedKeys.end()) {
3759 keyCode = replacementIt->second;
3760 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003761 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3762 }
3763 }
3764}
3765
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003767 if (DEBUG_INBOUND_EVENT_DETAILS) {
3768 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3769 "policyFlags=0x%x, action=0x%x, "
3770 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3771 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3772 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3773 args->downTime);
3774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 if (!validateKeyEvent(args->action)) {
3776 return;
3777 }
3778
3779 uint32_t policyFlags = args->policyFlags;
3780 int32_t flags = args->flags;
3781 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003782 // InputDispatcher tracks and generates key repeats on behalf of
3783 // whatever notifies it, so repeatCount should always be set to 0
3784 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3786 policyFlags |= POLICY_FLAG_VIRTUAL;
3787 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 if (policyFlags & POLICY_FLAG_FUNCTION) {
3790 metaState |= AMETA_FUNCTION_ON;
3791 }
3792
3793 policyFlags |= POLICY_FLAG_TRUSTED;
3794
Michael Wright78f24442014-08-06 15:55:28 -07003795 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003796 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003797
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003799 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003800 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3801 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802
Michael Wright2b3c3302018-03-02 17:19:13 +00003803 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003805 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3806 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003807 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 bool needWake;
3811 { // acquire lock
3812 mLock.lock();
3813
3814 if (shouldSendKeyToInputFilterLocked(args)) {
3815 mLock.unlock();
3816
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003817 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3819 return; // event was consumed by the filter
3820 }
3821
3822 mLock.lock();
3823 }
3824
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003825 std::unique_ptr<KeyEntry> newEntry =
3826 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3827 args->displayId, policyFlags, args->action, flags,
3828 keyCode, args->scanCode, metaState, repeatCount,
3829 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003831 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 mLock.unlock();
3833 } // release lock
3834
3835 if (needWake) {
3836 mLooper->wake();
3837 }
3838}
3839
3840bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3841 return mInputFilterEnabled;
3842}
3843
3844void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003845 if (DEBUG_INBOUND_EVENT_DETAILS) {
3846 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3847 "displayId=%" PRId32 ", policyFlags=0x%x, "
3848 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3849 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3850 "yCursorPosition=%f, downTime=%" PRId64,
3851 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3852 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3853 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3854 args->xCursorPosition, args->yCursorPosition, args->downTime);
3855 for (uint32_t i = 0; i < args->pointerCount; i++) {
3856 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3857 "x=%f, y=%f, pressure=%f, size=%f, "
3858 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3859 "orientation=%f",
3860 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3861 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3862 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3863 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3864 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3865 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3866 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3867 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3868 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3869 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3873 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 return;
3875 }
3876
3877 uint32_t policyFlags = args->policyFlags;
3878 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003879
3880 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003881 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003882 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3883 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003884 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886
3887 bool needWake;
3888 { // acquire lock
3889 mLock.lock();
3890
3891 if (shouldSendMotionToInputFilterLocked(args)) {
3892 mLock.unlock();
3893
3894 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003895 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003896 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3897 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003898 args->metaState, args->buttonState, args->classification, transform,
3899 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003900 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3901 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3902 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
3904 policyFlags |= POLICY_FLAG_FILTERED;
3905 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3906 return; // event was consumed by the filter
3907 }
3908
3909 mLock.lock();
3910 }
3911
3912 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003913 std::unique_ptr<MotionEntry> newEntry =
3914 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3915 args->source, args->displayId, policyFlags,
3916 args->action, args->actionButton, args->flags,
3917 args->metaState, args->buttonState,
3918 args->classification, args->edgeFlags,
3919 args->xPrecision, args->yPrecision,
3920 args->xCursorPosition, args->yCursorPosition,
3921 args->downTime, args->pointerCount,
3922 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003924 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3925 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3926 !mInputFilterEnabled) {
3927 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3928 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3929 }
3930
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003931 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 mLock.unlock();
3933 } // release lock
3934
3935 if (needWake) {
3936 mLooper->wake();
3937 }
3938}
3939
Chris Yef59a2f42020-10-16 12:55:26 -07003940void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 if (DEBUG_INBOUND_EVENT_DETAILS) {
3942 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3943 " sensorType=%s",
3944 args->id, args->eventTime, args->deviceId, args->source,
3945 NamedEnum::string(args->sensorType).c_str());
3946 }
Chris Yef59a2f42020-10-16 12:55:26 -07003947
3948 bool needWake;
3949 { // acquire lock
3950 mLock.lock();
3951
3952 // Just enqueue a new sensor event.
3953 std::unique_ptr<SensorEntry> newEntry =
3954 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3955 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3956 args->sensorType, args->accuracy,
3957 args->accuracyChanged, args->values);
3958
3959 needWake = enqueueInboundEventLocked(std::move(newEntry));
3960 mLock.unlock();
3961 } // release lock
3962
3963 if (needWake) {
3964 mLooper->wake();
3965 }
3966}
3967
Chris Yefb552902021-02-03 17:18:37 -08003968void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003969 if (DEBUG_INBOUND_EVENT_DETAILS) {
3970 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3971 args->deviceId, args->isOn);
3972 }
Chris Yefb552902021-02-03 17:18:37 -08003973 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3974}
3975
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003977 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978}
3979
3980void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003981 if (DEBUG_INBOUND_EVENT_DETAILS) {
3982 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
3983 "switchMask=0x%08x",
3984 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
3985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
3987 uint32_t policyFlags = args->policyFlags;
3988 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990}
3991
3992void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003993 if (DEBUG_INBOUND_EVENT_DETAILS) {
3994 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3995 args->deviceId);
3996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997
3998 bool needWake;
3999 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004000 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::unique_ptr<DeviceResetEntry> newEntry =
4003 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4004 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 } // release lock
4006
4007 if (needWake) {
4008 mLooper->wake();
4009 }
4010}
4011
Prabir Pradhan7e186182020-11-10 13:56:45 -08004012void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004013 if (DEBUG_INBOUND_EVENT_DETAILS) {
4014 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004015 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004016 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004017
Prabir Pradhan99987712020-11-10 18:43:05 -08004018 bool needWake;
4019 { // acquire lock
4020 std::scoped_lock _l(mLock);
4021 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004022 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004023 needWake = enqueueInboundEventLocked(std::move(entry));
4024 } // release lock
4025
4026 if (needWake) {
4027 mLooper->wake();
4028 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004029}
4030
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004031InputEventInjectionResult InputDispatcher::injectInputEvent(
4032 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4033 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 if (DEBUG_INBOUND_EVENT_DETAILS) {
4035 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4036 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4037 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4038 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004039 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
4041 policyFlags |= POLICY_FLAG_INJECTED;
4042 if (hasInjectionPermission(injectorPid, injectorUid)) {
4043 policyFlags |= POLICY_FLAG_TRUSTED;
4044 }
4045
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004046 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004047 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4048 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4049 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4050 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4051 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004052 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004053 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004055 }
4056
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004057 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004060 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4061 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004066 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004067 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4068 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4069 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004070 int32_t keyCode = incomingKey.getKeyCode();
4071 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004072 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004074 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004075 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004076 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4077 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4078 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4081 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004082 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083
4084 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4085 android::base::Timer t;
4086 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4087 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4088 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4089 std::to_string(t.duration().count()).c_str());
4090 }
4091 }
4092
4093 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004094 std::unique_ptr<KeyEntry> injectedEntry =
4095 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004096 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004097 incomingKey.getDisplayId(), policyFlags, action,
4098 flags, keyCode, incomingKey.getScanCode(), metaState,
4099 incomingKey.getRepeatCount(),
4100 incomingKey.getDownTime());
4101 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 }
4104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004106 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4107 int32_t action = motionEvent.getAction();
4108 size_t pointerCount = motionEvent.getPointerCount();
4109 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4110 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004111 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004112 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004114 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 }
4116
4117 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004118 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 android::base::Timer t;
4120 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4121 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4122 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4123 std::to_string(t.duration().count()).c_str());
4124 }
4125 }
4126
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004127 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4128 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4129 }
4130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004132 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4133 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004134 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004135 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4136 resolvedDeviceId, motionEvent.getSource(),
4137 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004138 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004139 motionEvent.getButtonState(),
4140 motionEvent.getClassification(),
4141 motionEvent.getEdgeFlags(),
4142 motionEvent.getXPrecision(),
4143 motionEvent.getYPrecision(),
4144 motionEvent.getRawXCursorPosition(),
4145 motionEvent.getRawYCursorPosition(),
4146 motionEvent.getDownTime(), uint32_t(pointerCount),
4147 pointerProperties, samplePointerCoords,
4148 motionEvent.getXOffset(),
4149 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004151 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 sampleEventTimes += 1;
4153 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004154 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004155 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4156 resolvedDeviceId, motionEvent.getSource(),
4157 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004158 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004159 motionEvent.getMetaState(),
4160 motionEvent.getButtonState(),
4161 motionEvent.getClassification(),
4162 motionEvent.getEdgeFlags(),
4163 motionEvent.getXPrecision(),
4164 motionEvent.getYPrecision(),
4165 motionEvent.getRawXCursorPosition(),
4166 motionEvent.getRawYCursorPosition(),
4167 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004168 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004169 samplePointerCoords, motionEvent.getXOffset(),
4170 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004171 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 }
4173 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004177 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004178 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 }
4180
4181 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004182 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 injectionState->injectionIsAsync = true;
4184 }
4185
4186 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004187 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
4189 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004190 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004191 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004192 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
4195 mLock.unlock();
4196
4197 if (needWake) {
4198 mLooper->wake();
4199 }
4200
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004203 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004205 if (syncMode == InputEventInjectionSync::NONE) {
4206 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 } else {
4208 for (;;) {
4209 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004210 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 break;
4212 }
4213
4214 nsecs_t remainingTimeout = endTime - now();
4215 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004216 if (DEBUG_INJECTION) {
4217 ALOGD("injectInputEvent - Timed out waiting for injection result "
4218 "to become available.");
4219 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004220 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 break;
4222 }
4223
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004224 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 }
4226
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004227 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4228 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004230 if (DEBUG_INJECTION) {
4231 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4232 injectionState->pendingForegroundDispatches);
4233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 nsecs_t remainingTimeout = endTime - now();
4235 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004236 if (DEBUG_INJECTION) {
4237 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4238 "dispatches to finish.");
4239 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004240 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 break;
4242 }
4243
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004244 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 }
4246 }
4247 }
4248
4249 injectionState->release();
4250 } // release lock
4251
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004252 if (DEBUG_INJECTION) {
4253 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4254 injectionResult, injectorPid, injectorUid);
4255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
4257 return injectionResult;
4258}
4259
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004260std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004261 std::array<uint8_t, 32> calculatedHmac;
4262 std::unique_ptr<VerifiedInputEvent> result;
4263 switch (event.getType()) {
4264 case AINPUT_EVENT_TYPE_KEY: {
4265 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4266 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4267 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004268 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004269 break;
4270 }
4271 case AINPUT_EVENT_TYPE_MOTION: {
4272 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4273 VerifiedMotionEvent verifiedMotionEvent =
4274 verifiedMotionEventFromMotionEvent(motionEvent);
4275 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004276 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004277 break;
4278 }
4279 default: {
4280 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4281 return nullptr;
4282 }
4283 }
4284 if (calculatedHmac == INVALID_HMAC) {
4285 return nullptr;
4286 }
4287 if (calculatedHmac != event.getHmac()) {
4288 return nullptr;
4289 }
4290 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004291}
4292
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 return injectorUid == 0 ||
4295 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296}
4297
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004298void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004299 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004300 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004302 if (DEBUG_INJECTION) {
4303 ALOGD("Setting input event injection result to %d. "
4304 "injectorPid=%d, injectorUid=%d",
4305 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004308 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 // Log the outcome since the injector did not wait for the injection result.
4310 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004311 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 ALOGV("Asynchronous input event injection succeeded.");
4313 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 ALOGW("Asynchronous input event injection failed.");
4316 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004317 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 ALOGW("Asynchronous input event injection permission denied.");
4319 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004320 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 ALOGW("Asynchronous input event injection timed out.");
4322 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 case InputEventInjectionResult::PENDING:
4324 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4325 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 }
4327 }
4328
4329 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004330 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332}
4333
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004334void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4335 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 if (injectionState) {
4337 injectionState->pendingForegroundDispatches += 1;
4338 }
4339}
4340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004341void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4342 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 if (injectionState) {
4344 injectionState->pendingForegroundDispatches -= 1;
4345
4346 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004347 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 }
4349 }
4350}
4351
chaviw98318de2021-05-19 16:45:23 -05004352const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004353 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004354 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004355 auto it = mWindowHandlesByDisplay.find(displayId);
4356 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004357}
4358
chaviw98318de2021-05-19 16:45:23 -05004359sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004360 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004361 if (windowHandleToken == nullptr) {
4362 return nullptr;
4363 }
4364
Arthur Hungb92218b2018-08-14 12:00:21 +08004365 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004366 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4367 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004368 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004369 return windowHandle;
4370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004373 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374}
4375
chaviw98318de2021-05-19 16:45:23 -05004376sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4377 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004378 if (windowHandleToken == nullptr) {
4379 return nullptr;
4380 }
4381
chaviw98318de2021-05-19 16:45:23 -05004382 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004383 if (windowHandle->getToken() == windowHandleToken) {
4384 return windowHandle;
4385 }
4386 }
4387 return nullptr;
4388}
4389
chaviw98318de2021-05-19 16:45:23 -05004390sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4391 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004392 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004393 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4394 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004395 if (handle->getId() == windowHandle->getId() &&
4396 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004397 if (windowHandle->getInfo()->displayId != it.first) {
4398 ALOGE("Found window %s in display %" PRId32
4399 ", but it should belong to display %" PRId32,
4400 windowHandle->getName().c_str(), it.first,
4401 windowHandle->getInfo()->displayId);
4402 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004403 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 }
4406 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004407 return nullptr;
4408}
4409
chaviw98318de2021-05-19 16:45:23 -05004410sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004411 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4412 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413}
4414
chaviw98318de2021-05-19 16:45:23 -05004415bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004416 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4417 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004418 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004419 if (connection != nullptr && noInputChannel) {
4420 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4421 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4422 return false;
4423 }
4424
4425 if (connection == nullptr) {
4426 if (!noInputChannel) {
4427 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4428 }
4429 return false;
4430 }
4431 if (!connection->responsive) {
4432 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4433 return false;
4434 }
4435 return true;
4436}
4437
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004438std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4439 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004440 auto connectionIt = mConnectionsByToken.find(token);
4441 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004442 return nullptr;
4443 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004444 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004445}
4446
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004447void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004448 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4449 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004450 // Remove all handles on a display if there are no windows left.
4451 mWindowHandlesByDisplay.erase(displayId);
4452 return;
4453 }
4454
4455 // Since we compare the pointer of input window handles across window updates, we need
4456 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004457 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4458 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4459 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004460 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004461 }
4462
chaviw98318de2021-05-19 16:45:23 -05004463 std::vector<sp<WindowInfoHandle>> newHandles;
4464 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004465 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004466 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004467 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004468 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4469 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4470 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004471 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004472 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004473 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004474 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004475 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004476 }
4477
4478 if (info->displayId != displayId) {
4479 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4480 handle->getName().c_str(), displayId, info->displayId);
4481 continue;
4482 }
4483
Robert Carredd13602020-04-13 17:24:34 -07004484 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4485 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004486 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004487 oldHandle->updateFrom(handle);
4488 newHandles.push_back(oldHandle);
4489 } else {
4490 newHandles.push_back(handle);
4491 }
4492 }
4493
4494 // Insert or replace
4495 mWindowHandlesByDisplay[displayId] = newHandles;
4496}
4497
Arthur Hung72d8dc32020-03-28 00:48:39 +00004498void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004499 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004500 { // acquire lock
4501 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004502 for (const auto& [displayId, handles] : handlesPerDisplay) {
4503 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004504 }
4505 }
4506 // Wake up poll loop since it may need to make new input dispatching choices.
4507 mLooper->wake();
4508}
4509
Arthur Hungb92218b2018-08-14 12:00:21 +08004510/**
4511 * Called from InputManagerService, update window handle list by displayId that can receive input.
4512 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4513 * If set an empty list, remove all handles from the specific display.
4514 * For focused handle, check if need to change and send a cancel event to previous one.
4515 * For removed handle, check if need to send a cancel event if already in touch.
4516 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004517void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004518 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004519 if (DEBUG_FOCUS) {
4520 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004521 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004522 windowList += iwh->getName() + " ";
4523 }
4524 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004527 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004528 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004529 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004530 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004531 if (noInputWindow && window->getToken() != nullptr) {
4532 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4533 window->getName().c_str());
4534 window->releaseChannel();
4535 }
4536 }
4537
Arthur Hung72d8dc32020-03-28 00:48:39 +00004538 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004539 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004541 // Save the old windows' orientation by ID before it gets updated.
4542 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004543 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004544 oldWindowOrientations.emplace(handle->getId(),
4545 handle->getInfo()->transform.getOrientation());
4546 }
4547
chaviw98318de2021-05-19 16:45:23 -05004548 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004549
chaviw98318de2021-05-19 16:45:23 -05004550 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004551 if (mLastHoverWindowHandle &&
4552 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4553 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004554 mLastHoverWindowHandle = nullptr;
4555 }
4556
Vishnu Nairc519ff72021-01-21 08:23:08 -08004557 std::optional<FocusResolver::FocusChanges> changes =
4558 mFocusResolver.setInputWindows(displayId, windowHandles);
4559 if (changes) {
4560 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004563 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4564 mTouchStatesByDisplay.find(displayId);
4565 if (stateIt != mTouchStatesByDisplay.end()) {
4566 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004567 for (size_t i = 0; i < state.windows.size();) {
4568 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004569 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004570 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004571 ALOGD("Touched window was removed: %s in display %" PRId32,
4572 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004573 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004574 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004575 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4576 if (touchedInputChannel != nullptr) {
4577 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4578 "touched window was removed");
4579 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004581 state.windows.erase(state.windows.begin() + i);
4582 } else {
4583 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 }
4585 }
arthurhungb89ccb02020-12-30 16:19:01 +08004586
arthurhung6d4bed92021-03-17 11:59:33 +08004587 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004588 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004589 if (mDragState &&
4590 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004591 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004592 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004593 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004594 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004595
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004596 if (isPerWindowInputRotationEnabled()) {
4597 // Determine if the orientation of any of the input windows have changed, and cancel all
4598 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004599 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4600 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004601 if (newWindowHandle != nullptr &&
4602 newWindowHandle->getInfo()->transform.getOrientation() !=
4603 oldWindowOrientations[oldWindowHandle->getId()]) {
4604 std::shared_ptr<InputChannel> inputChannel =
4605 getInputChannelLocked(newWindowHandle->getToken());
4606 if (inputChannel != nullptr) {
4607 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4608 "touched window's orientation changed");
4609 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4610 }
4611 }
4612 }
4613 }
4614
Arthur Hung72d8dc32020-03-28 00:48:39 +00004615 // Release information for windows that are no longer present.
4616 // This ensures that unused input channels are released promptly.
4617 // Otherwise, they might stick around until the window handle is destroyed
4618 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004619 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004620 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004621 if (DEBUG_FOCUS) {
4622 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004623 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004624 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004625 // To avoid making too many calls into the compat framework, only
4626 // check for window flags when windows are going away.
4627 // TODO(b/157929241) : delete this. This is only needed temporarily
4628 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004629 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004630 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4631 oldWindowHandle->getName().c_str());
4632 if (mCompatService != nullptr) {
4633 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4634 oldWindowHandle->getInfo()->ownerUid);
4635 }
4636 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004637 }
chaviw291d88a2019-02-14 10:33:58 -08004638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639}
4640
4641void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004642 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004643 if (DEBUG_FOCUS) {
4644 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4645 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4646 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004647 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004648 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004649 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 } // release lock
4651
4652 // Wake up poll loop since it may need to make new input dispatching choices.
4653 mLooper->wake();
4654}
4655
Vishnu Nair599f1412021-06-21 10:39:58 -07004656void InputDispatcher::setFocusedApplicationLocked(
4657 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4658 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4659 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4660
4661 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4662 return; // This application is already focused. No need to wake up or change anything.
4663 }
4664
4665 // Set the new application handle.
4666 if (inputApplicationHandle != nullptr) {
4667 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4668 } else {
4669 mFocusedApplicationHandlesByDisplay.erase(displayId);
4670 }
4671
4672 // No matter what the old focused application was, stop waiting on it because it is
4673 // no longer focused.
4674 resetNoFocusedWindowTimeoutLocked();
4675}
4676
Tiger Huang721e26f2018-07-24 22:26:19 +08004677/**
4678 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4679 * the display not specified.
4680 *
4681 * We track any unreleased events for each window. If a window loses the ability to receive the
4682 * released event, we will send a cancel event to it. So when the focused display is changed, we
4683 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4684 * display. The display-specified events won't be affected.
4685 */
4686void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004687 if (DEBUG_FOCUS) {
4688 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4689 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004690 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004691 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004692
4693 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004694 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004695 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004696 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004697 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004698 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004699 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700 CancelationOptions
4701 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4702 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004703 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004704 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4705 }
4706 }
4707 mFocusedDisplayId = displayId;
4708
Chris Ye3c2d6f52020-08-09 10:39:48 -07004709 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004710 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004711 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004712
Vishnu Nairad321cd2020-08-20 16:40:21 -07004713 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004714 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004715 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004716 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004717 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004718 }
4719 }
4720 }
4721
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004722 if (DEBUG_FOCUS) {
4723 logDispatchStateLocked();
4724 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004725 } // release lock
4726
4727 // Wake up poll loop since it may need to make new input dispatching choices.
4728 mLooper->wake();
4729}
4730
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004732 if (DEBUG_FOCUS) {
4733 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735
4736 bool changed;
4737 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004738 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739
4740 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4741 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
4744
4745 if (mDispatchEnabled && !enabled) {
4746 resetAndDropEverythingLocked("dispatcher is being disabled");
4747 }
4748
4749 mDispatchEnabled = enabled;
4750 mDispatchFrozen = frozen;
4751 changed = true;
4752 } else {
4753 changed = false;
4754 }
4755
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004756 if (DEBUG_FOCUS) {
4757 logDispatchStateLocked();
4758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 } // release lock
4760
4761 if (changed) {
4762 // Wake up poll loop since it may need to make new input dispatching choices.
4763 mLooper->wake();
4764 }
4765}
4766
4767void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004768 if (DEBUG_FOCUS) {
4769 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771
4772 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004773 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774
4775 if (mInputFilterEnabled == enabled) {
4776 return;
4777 }
4778
4779 mInputFilterEnabled = enabled;
4780 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4781 } // release lock
4782
4783 // Wake up poll loop since there might be work to do to drop everything.
4784 mLooper->wake();
4785}
4786
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004787void InputDispatcher::setInTouchMode(bool inTouchMode) {
4788 std::scoped_lock lock(mLock);
4789 mInTouchMode = inTouchMode;
4790}
4791
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004792void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4793 if (opacity < 0 || opacity > 1) {
4794 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4795 return;
4796 }
4797
4798 std::scoped_lock lock(mLock);
4799 mMaximumObscuringOpacityForTouch = opacity;
4800}
4801
4802void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4803 std::scoped_lock lock(mLock);
4804 mBlockUntrustedTouchesMode = mode;
4805}
4806
arthurhungb89ccb02020-12-30 16:19:01 +08004807bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4808 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004809 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004810 if (DEBUG_FOCUS) {
4811 ALOGD("Trivial transfer to same window.");
4812 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004813 return true;
4814 }
4815
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004817 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818
chaviw98318de2021-05-19 16:45:23 -05004819 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4820 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004821 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004822 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 return false;
4824 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004825 if (DEBUG_FOCUS) {
4826 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4827 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004830 if (DEBUG_FOCUS) {
4831 ALOGD("Cannot transfer focus because windows are on different displays.");
4832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 return false;
4834 }
4835
4836 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004837 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4838 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004839 for (size_t i = 0; i < state.windows.size(); i++) {
4840 const TouchedWindow& touchedWindow = state.windows[i];
4841 if (touchedWindow.windowHandle == fromWindowHandle) {
4842 int32_t oldTargetFlags = touchedWindow.targetFlags;
4843 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004845 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 int32_t newTargetFlags = oldTargetFlags &
4848 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4849 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004850 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851
arthurhungb89ccb02020-12-30 16:19:01 +08004852 // Store the dragging window.
4853 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004854 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004855 }
4856
Jeff Brownf086ddb2014-02-11 14:28:48 -08004857 found = true;
4858 goto Found;
4859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
4861 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004864 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004865 if (DEBUG_FOCUS) {
4866 ALOGD("Focus transfer failed because from window did not have focus.");
4867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 return false;
4869 }
4870
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004871 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4872 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004873 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004874 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004875 CancelationOptions
4876 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4877 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004879 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 }
4881
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004882 if (DEBUG_FOCUS) {
4883 logDispatchStateLocked();
4884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 } // release lock
4886
4887 // Wake up poll loop since it may need to make new input dispatching choices.
4888 mLooper->wake();
4889 return true;
4890}
4891
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004892// Binder call
4893bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4894 sp<IBinder> fromToken;
4895 { // acquire lock
4896 std::scoped_lock _l(mLock);
4897
chaviw98318de2021-05-19 16:45:23 -05004898 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004899 if (toWindowHandle == nullptr) {
4900 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4901 return false;
4902 }
4903
4904 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4905
4906 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4907 if (touchStateIt == mTouchStatesByDisplay.end()) {
4908 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4909 displayId);
4910 return false;
4911 }
4912
4913 TouchState& state = touchStateIt->second;
4914 if (state.windows.size() != 1) {
4915 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4916 state.windows.size());
4917 return false;
4918 }
4919 const TouchedWindow& touchedWindow = state.windows[0];
4920 fromToken = touchedWindow.windowHandle->getToken();
4921 } // release lock
4922
4923 return transferTouchFocus(fromToken, destChannelToken);
4924}
4925
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004927 if (DEBUG_FOCUS) {
4928 ALOGD("Resetting and dropping all events (%s).", reason);
4929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
4931 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4932 synthesizeCancelationEventsForAllConnectionsLocked(options);
4933
4934 resetKeyRepeatLocked();
4935 releasePendingEventLocked();
4936 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004937 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004939 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004940 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004942 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943}
4944
4945void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004946 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 dumpDispatchStateLocked(dump);
4948
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004949 std::istringstream stream(dump);
4950 std::string line;
4951
4952 while (std::getline(stream, line, '\n')) {
4953 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 }
4955}
4956
Prabir Pradhan99987712020-11-10 18:43:05 -08004957std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4958 std::string dump;
4959
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004960 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
4961 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08004962
4963 std::string windowName = "None";
4964 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05004965 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004966 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4967 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4968 : "token has capture without window";
4969 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004970 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08004971
4972 return dump;
4973}
4974
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004975void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004976 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4977 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4978 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004979 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980
Tiger Huang721e26f2018-07-24 22:26:19 +08004981 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4982 dump += StringPrintf(INDENT "FocusedApplications:\n");
4983 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4984 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004985 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004986 const std::chrono::duration timeout =
4987 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004988 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004989 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004990 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004993 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004995
Vishnu Nairc519ff72021-01-21 08:23:08 -08004996 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004997 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004999 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005000 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005001 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5002 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005003 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005004 state.displayId, toString(state.down), toString(state.split),
5005 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005006 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005007 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005008 for (size_t i = 0; i < state.windows.size(); i++) {
5009 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005010 dump += StringPrintf(INDENT4
5011 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5012 i, touchedWindow.windowHandle->getName().c_str(),
5013 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005014 }
5015 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005016 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 }
5019 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005020 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 }
5022
arthurhung6d4bed92021-03-17 11:59:33 +08005023 if (mDragState) {
5024 dump += StringPrintf(INDENT "DragState:\n");
5025 mDragState->dump(dump, INDENT2);
5026 }
5027
Arthur Hungb92218b2018-08-14 12:00:21 +08005028 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005029 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005030 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005031 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005032 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005033 dump += INDENT2 "Windows:\n";
5034 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005035 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5036 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005038 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005039 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005040 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005041 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005042 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005043 "applicationInfo.name=%s, "
5044 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005045 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005046 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005047 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005048 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005049 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005050 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005051 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005052 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005053 windowInfo->frameLeft, windowInfo->frameTop,
5054 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005055 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005056 windowInfo->applicationInfo.name.c_str(),
5057 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005058 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005059 dump += StringPrintf(", inputFeatures=%s",
5060 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005061 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005062 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005063 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005064 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005065 millis(windowInfo->dispatchingTimeout),
5066 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005067 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005068 toString(windowInfo->touchOcclusionMode).c_str(),
5069 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005070 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005071 }
5072 } else {
5073 dump += INDENT2 "Windows: <none>\n";
5074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 }
5076 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005077 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078 }
5079
Michael Wright3dd60e22019-03-27 22:06:44 +00005080 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005081 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005082 const std::vector<Monitor>& monitors = it.second;
5083 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5084 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005085 }
5086 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005087 const std::vector<Monitor>& monitors = it.second;
5088 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5089 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005092 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 }
5094
5095 nsecs_t currentTime = now();
5096
5097 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005098 if (!mRecentQueue.empty()) {
5099 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005100 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005101 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005102 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005103 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 }
5105 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005106 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 }
5108
5109 // Dump event currently being dispatched.
5110 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 dump += INDENT "PendingEvent:\n";
5112 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005113 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005114 dump += StringPrintf(", age=%" PRId64 "ms\n",
5115 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005117 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 }
5119
5120 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005121 if (!mInboundQueue.empty()) {
5122 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005123 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005124 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005125 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005126 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 }
5128 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005129 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005132 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005134 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5135 const KeyReplacement& replacement = pair.first;
5136 int32_t newKeyCode = pair.second;
5137 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005138 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005139 }
5140 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005141 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005142 }
5143
Prabir Pradhancef936d2021-07-21 16:17:52 +00005144 if (!mCommandQueue.empty()) {
5145 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5146 } else {
5147 dump += INDENT "CommandQueue: <empty>\n";
5148 }
5149
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005150 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005151 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005152 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005153 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005154 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005155 connection->inputChannel->getFd().get(),
5156 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005157 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005158 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005160 if (!connection->outboundQueue.empty()) {
5161 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5162 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005163 dump += dumpQueue(connection->outboundQueue, currentTime);
5164
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005166 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 }
5168
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005169 if (!connection->waitQueue.empty()) {
5170 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5171 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005172 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005174 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 }
5176 }
5177 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005178 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 }
5180
5181 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005182 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5183 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005185 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 }
5187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005188 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005189 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5190 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5191 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005192 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005193 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194}
5195
Michael Wright3dd60e22019-03-27 22:06:44 +00005196void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5197 const size_t numMonitors = monitors.size();
5198 for (size_t i = 0; i < numMonitors; i++) {
5199 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005200 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005201 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5202 dump += "\n";
5203 }
5204}
5205
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005206class LooperEventCallback : public LooperCallback {
5207public:
5208 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5209 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5210
5211private:
5212 std::function<int(int events)> mCallback;
5213};
5214
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005215Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005216 if (DEBUG_CHANNEL_CREATION) {
5217 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005220 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005221 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005222 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005223
5224 if (result) {
5225 return base::Error(result) << "Failed to open input channel pair with name " << name;
5226 }
5227
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005229 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005230 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005231 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005232 sp<Connection> connection =
5233 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005235 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5236 ALOGE("Created a new connection, but the token %p is already known", token.get());
5237 }
5238 mConnectionsByToken.emplace(token, connection);
5239
5240 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5241 this, std::placeholders::_1, token);
5242
5243 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 } // release lock
5245
5246 // Wake the looper because some connections have changed.
5247 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005248 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249}
5250
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005251Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5252 bool isGestureMonitor,
5253 const std::string& name,
5254 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005255 std::shared_ptr<InputChannel> serverChannel;
5256 std::unique_ptr<InputChannel> clientChannel;
5257 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5258 if (result) {
5259 return base::Error(result) << "Failed to open input channel pair with name " << name;
5260 }
5261
Michael Wright3dd60e22019-03-27 22:06:44 +00005262 { // acquire lock
5263 std::scoped_lock _l(mLock);
5264
5265 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005266 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5267 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005268 }
5269
Garfield Tan15601662020-09-22 15:32:38 -07005270 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005271 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005272 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005273
5274 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5275 ALOGE("Created a new connection, but the token %p is already known", token.get());
5276 }
5277 mConnectionsByToken.emplace(token, connection);
5278 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5279 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005280
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005281 auto& monitorsByDisplay =
5282 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005283 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005284
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005285 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005286 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5287 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005288 }
Garfield Tan15601662020-09-22 15:32:38 -07005289
Michael Wright3dd60e22019-03-27 22:06:44 +00005290 // Wake the looper because some connections have changed.
5291 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005292 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005293}
5294
Garfield Tan15601662020-09-22 15:32:38 -07005295status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005297 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298
Garfield Tan15601662020-09-22 15:32:38 -07005299 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 if (status) {
5301 return status;
5302 }
5303 } // release lock
5304
5305 // Wake the poll loop because removing the connection may have changed the current
5306 // synchronization state.
5307 mLooper->wake();
5308 return OK;
5309}
5310
Garfield Tan15601662020-09-22 15:32:38 -07005311status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5312 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005313 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005314 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005315 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 return BAD_VALUE;
5317 }
5318
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005319 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005320
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005322 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 }
5324
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005325 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326
5327 nsecs_t currentTime = now();
5328 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5329
5330 connection->status = Connection::STATUS_ZOMBIE;
5331 return OK;
5332}
5333
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005334void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5335 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5336 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005337}
5338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005339void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005340 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005341 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005342 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005343 std::vector<Monitor>& monitors = it->second;
5344 const size_t numMonitors = monitors.size();
5345 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005346 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005347 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5348 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005349 monitors.erase(monitors.begin() + i);
5350 break;
5351 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005352 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005353 if (monitors.empty()) {
5354 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005355 } else {
5356 ++it;
5357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 }
5359}
5360
Michael Wright3dd60e22019-03-27 22:06:44 +00005361status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5362 { // acquire lock
5363 std::scoped_lock _l(mLock);
5364 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5365
5366 if (!foundDisplayId) {
5367 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5368 return BAD_VALUE;
5369 }
5370 int32_t displayId = foundDisplayId.value();
5371
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005372 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5373 mTouchStatesByDisplay.find(displayId);
5374 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005375 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5376 return BAD_VALUE;
5377 }
5378
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005379 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005380 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005381 std::optional<int32_t> foundDeviceId;
5382 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005383 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005384 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 foundDeviceId = state.deviceId;
5386 }
5387 }
5388 if (!foundDeviceId || !state.down) {
5389 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005390 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005391 return BAD_VALUE;
5392 }
5393 int32_t deviceId = foundDeviceId.value();
5394
5395 // Send cancel events to all the input channels we're stealing from.
5396 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005397 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005398 options.deviceId = deviceId;
5399 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005400 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005401 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005402 std::shared_ptr<InputChannel> channel =
5403 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005404 if (channel != nullptr) {
5405 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005406 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005407 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005408 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005409 canceledWindows += "]";
5410 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5411 canceledWindows.c_str());
5412
Michael Wright3dd60e22019-03-27 22:06:44 +00005413 // Then clear the current touch state so we stop dispatching to them as well.
5414 state.filterNonMonitors();
5415 }
5416 return OK;
5417}
5418
Prabir Pradhan99987712020-11-10 18:43:05 -08005419void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5420 { // acquire lock
5421 std::scoped_lock _l(mLock);
5422 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005423 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005424 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5425 windowHandle != nullptr ? windowHandle->getName().c_str()
5426 : "token without window");
5427 }
5428
Vishnu Nairc519ff72021-01-21 08:23:08 -08005429 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005430 if (focusedToken != windowToken) {
5431 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5432 enabled ? "enable" : "disable");
5433 return;
5434 }
5435
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005436 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005437 ALOGW("Ignoring request to %s Pointer Capture: "
5438 "window has %s requested pointer capture.",
5439 enabled ? "enable" : "disable", enabled ? "already" : "not");
5440 return;
5441 }
5442
Prabir Pradhan99987712020-11-10 18:43:05 -08005443 setPointerCaptureLocked(enabled);
5444 } // release lock
5445
5446 // Wake the thread to process command entries.
5447 mLooper->wake();
5448}
5449
Michael Wright3dd60e22019-03-27 22:06:44 +00005450std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5451 const sp<IBinder>& token) {
5452 for (const auto& it : mGestureMonitorsByDisplay) {
5453 const std::vector<Monitor>& monitors = it.second;
5454 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005455 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005456 return it.first;
5457 }
5458 }
5459 }
5460 return std::nullopt;
5461}
5462
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005463std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5464 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5465 if (gesturePid.has_value()) {
5466 return gesturePid;
5467 }
5468 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5469}
5470
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005471sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005472 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005473 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005474 }
5475
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005476 for (const auto& [token, connection] : mConnectionsByToken) {
5477 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005478 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480 }
Robert Carr4e670e52018-08-15 13:26:12 -07005481
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005482 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483}
5484
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005485std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5486 sp<Connection> connection = getConnectionLocked(connectionToken);
5487 if (connection == nullptr) {
5488 return "<nullptr>";
5489 }
5490 return connection->getInputChannelName();
5491}
5492
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005493void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005494 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005495 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005496}
5497
Prabir Pradhancef936d2021-07-21 16:17:52 +00005498void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5499 const sp<Connection>& connection, uint32_t seq,
5500 bool handled, nsecs_t consumeTime) {
5501 // Handle post-event policy actions.
5502 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5503 if (dispatchEntryIt == connection->waitQueue.end()) {
5504 return;
5505 }
5506 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5507 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5508 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5509 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5510 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5511 }
5512 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5513 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5514 connection->inputChannel->getConnectionToken(),
5515 dispatchEntry->deliveryTime, consumeTime, finishTime);
5516 }
5517
5518 bool restartEvent;
5519 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5520 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5521 restartEvent =
5522 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5523 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5524 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5525 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5526 handled);
5527 } else {
5528 restartEvent = false;
5529 }
5530
5531 // Dequeue the event and start the next cycle.
5532 // Because the lock might have been released, it is possible that the
5533 // contents of the wait queue to have been drained, so we need to double-check
5534 // a few things.
5535 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5536 if (dispatchEntryIt != connection->waitQueue.end()) {
5537 dispatchEntry = *dispatchEntryIt;
5538 connection->waitQueue.erase(dispatchEntryIt);
5539 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5540 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5541 if (!connection->responsive) {
5542 connection->responsive = isConnectionResponsive(*connection);
5543 if (connection->responsive) {
5544 // The connection was unresponsive, and now it's responsive.
5545 processConnectionResponsiveLocked(*connection);
5546 }
5547 }
5548 traceWaitQueueLength(*connection);
5549 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5550 connection->outboundQueue.push_front(dispatchEntry);
5551 traceOutboundQueueLength(*connection);
5552 } else {
5553 releaseDispatchEntry(dispatchEntry);
5554 }
5555 }
5556
5557 // Start the next dispatch cycle for this connection.
5558 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559}
5560
Prabir Pradhancef936d2021-07-21 16:17:52 +00005561void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5562 const sp<IBinder>& newToken) {
5563 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5564 scoped_unlock unlock(mLock);
5565 mPolicy->notifyFocusChanged(oldToken, newToken);
5566 };
5567 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568}
5569
Prabir Pradhancef936d2021-07-21 16:17:52 +00005570void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5571 auto command = [this, token, x, y]() REQUIRES(mLock) {
5572 scoped_unlock unlock(mLock);
5573 mPolicy->notifyDropWindow(token, x, y);
5574 };
5575 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005576}
5577
Prabir Pradhancef936d2021-07-21 16:17:52 +00005578void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5579 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5580 scoped_unlock unlock(mLock);
5581 mPolicy->notifyUntrustedTouch(obscuringPackage);
5582 };
5583 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005584}
5585
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005586void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5587 if (connection == nullptr) {
5588 LOG_ALWAYS_FATAL("Caller must check for nullness");
5589 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005590 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5591 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005592 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005593 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005594 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005595 return;
5596 }
5597 /**
5598 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5599 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5600 * has changed. This could cause newer entries to time out before the already dispatched
5601 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5602 * processes the events linearly. So providing information about the oldest entry seems to be
5603 * most useful.
5604 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005605 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005606 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5607 std::string reason =
5608 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005609 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005610 ns2ms(currentWait),
5611 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005612 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005613 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005614
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005615 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5616
5617 // Stop waking up for events on this connection, it is already unresponsive
5618 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005619}
5620
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005621void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5622 std::string reason =
5623 StringPrintf("%s does not have a focused window", application->getName().c_str());
5624 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005625
Prabir Pradhancef936d2021-07-21 16:17:52 +00005626 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5627 scoped_unlock unlock(mLock);
5628 mPolicy->notifyNoFocusedWindowAnr(application);
5629 };
5630 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005631}
5632
chaviw98318de2021-05-19 16:45:23 -05005633void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005634 const std::string& reason) {
5635 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5636 updateLastAnrStateLocked(windowLabel, reason);
5637}
5638
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005639void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5640 const std::string& reason) {
5641 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005642 updateLastAnrStateLocked(windowLabel, reason);
5643}
5644
5645void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5646 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005648 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 struct tm tm;
5650 localtime_r(&t, &tm);
5651 char timestr[64];
5652 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005653 mLastAnrState.clear();
5654 mLastAnrState += INDENT "ANR:\n";
5655 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005656 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5657 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005658 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659}
5660
Prabir Pradhancef936d2021-07-21 16:17:52 +00005661void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5662 KeyEntry& entry) {
5663 const KeyEvent event = createKeyEvent(entry);
5664 nsecs_t delay = 0;
5665 { // release lock
5666 scoped_unlock unlock(mLock);
5667 android::base::Timer t;
5668 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5669 entry.policyFlags);
5670 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5671 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5672 std::to_string(t.duration().count()).c_str());
5673 }
5674 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675
5676 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005677 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005678 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005679 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005681 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5682 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684}
5685
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005686void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005687 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5688 scoped_unlock unlock(mLock);
5689 mPolicy->notifyMonitorUnresponsive(pid, reason);
5690 };
5691 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005692}
5693
Prabir Pradhancef936d2021-07-21 16:17:52 +00005694void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005695 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005696 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5697 scoped_unlock unlock(mLock);
5698 mPolicy->notifyWindowUnresponsive(token, reason);
5699 };
5700 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005701}
5702
5703void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005704 auto command = [this, pid]() REQUIRES(mLock) {
5705 scoped_unlock unlock(mLock);
5706 mPolicy->notifyMonitorResponsive(pid);
5707 };
5708 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005709}
5710
Prabir Pradhancef936d2021-07-21 16:17:52 +00005711void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5712 auto command = [this, connectionToken]() REQUIRES(mLock) {
5713 scoped_unlock unlock(mLock);
5714 mPolicy->notifyWindowResponsive(connectionToken);
5715 };
5716 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005717}
5718
5719/**
5720 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5721 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5722 * command entry to the command queue.
5723 */
5724void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5725 std::string reason) {
5726 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5727 if (connection.monitor) {
5728 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5729 reason.c_str());
5730 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5731 if (!pid.has_value()) {
5732 ALOGE("Could not find unresponsive monitor for connection %s",
5733 connection.inputChannel->getName().c_str());
5734 return;
5735 }
5736 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5737 return;
5738 }
5739 // If not a monitor, must be a window
5740 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5741 reason.c_str());
5742 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5743}
5744
5745/**
5746 * Tell the policy that a connection has become responsive so that it can stop ANR.
5747 */
5748void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5749 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5750 if (connection.monitor) {
5751 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5752 if (!pid.has_value()) {
5753 ALOGE("Could not find responsive monitor for connection %s",
5754 connection.inputChannel->getName().c_str());
5755 return;
5756 }
5757 sendMonitorResponsiveCommandLocked(pid.value());
5758 return;
5759 }
5760 // If not a monitor, must be a window
5761 sendWindowResponsiveCommandLocked(connectionToken);
5762}
5763
Prabir Pradhancef936d2021-07-21 16:17:52 +00005764bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005765 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005766 KeyEntry& keyEntry, bool handled) {
5767 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005768 if (!handled) {
5769 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005770 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005771 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005772 return false;
5773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005775 // Get the fallback key state.
5776 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005777 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005778 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005779 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005780 connection->inputState.removeFallbackKey(originalKeyCode);
5781 }
5782
5783 if (handled || !dispatchEntry->hasForegroundTarget()) {
5784 // If the application handles the original key for which we previously
5785 // generated a fallback or if the window is not a foreground window,
5786 // then cancel the associated fallback key, if any.
5787 if (fallbackKeyCode != -1) {
5788 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005789 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5790 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5791 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5792 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5793 keyEntry.policyFlags);
5794 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005795 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005796 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797
5798 mLock.unlock();
5799
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005800 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005801 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802
5803 mLock.lock();
5804
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005805 // Cancel the fallback key.
5806 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005808 "application handled the original non-fallback key "
5809 "or is no longer a foreground target, "
5810 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 options.keyCode = fallbackKeyCode;
5812 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005814 connection->inputState.removeFallbackKey(originalKeyCode);
5815 }
5816 } else {
5817 // If the application did not handle a non-fallback key, first check
5818 // that we are in a good state to perform unhandled key event processing
5819 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005820 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005821 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005822 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5823 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5824 "since this is not an initial down. "
5825 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5826 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5827 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005828 return false;
5829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005830
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005831 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5833 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5834 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5835 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5836 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005837 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005838
5839 mLock.unlock();
5840
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005841 bool fallback =
5842 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005843 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005844
5845 mLock.lock();
5846
5847 if (connection->status != Connection::STATUS_NORMAL) {
5848 connection->inputState.removeFallbackKey(originalKeyCode);
5849 return false;
5850 }
5851
5852 // Latch the fallback keycode for this key on an initial down.
5853 // The fallback keycode cannot change at any other point in the lifecycle.
5854 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005856 fallbackKeyCode = event.getKeyCode();
5857 } else {
5858 fallbackKeyCode = AKEYCODE_UNKNOWN;
5859 }
5860 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5861 }
5862
5863 ALOG_ASSERT(fallbackKeyCode != -1);
5864
5865 // Cancel the fallback key if the policy decides not to send it anymore.
5866 // We will continue to dispatch the key to the policy but we will no
5867 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005868 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5869 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005870 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5871 if (fallback) {
5872 ALOGD("Unhandled key event: Policy requested to send key %d"
5873 "as a fallback for %d, but on the DOWN it had requested "
5874 "to send %d instead. Fallback canceled.",
5875 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5876 } else {
5877 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5878 "but on the DOWN it had requested to send %d. "
5879 "Fallback canceled.",
5880 originalKeyCode, fallbackKeyCode);
5881 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005882 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005883
5884 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5885 "canceling fallback, policy no longer desires it");
5886 options.keyCode = fallbackKeyCode;
5887 synthesizeCancelationEventsForConnectionLocked(connection, options);
5888
5889 fallback = false;
5890 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005891 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005892 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005893 }
5894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005896 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5897 {
5898 std::string msg;
5899 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5900 connection->inputState.getFallbackKeys();
5901 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5902 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5903 }
5904 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5905 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005908
5909 if (fallback) {
5910 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 keyEntry.eventTime = event.getEventTime();
5912 keyEntry.deviceId = event.getDeviceId();
5913 keyEntry.source = event.getSource();
5914 keyEntry.displayId = event.getDisplayId();
5915 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5916 keyEntry.keyCode = fallbackKeyCode;
5917 keyEntry.scanCode = event.getScanCode();
5918 keyEntry.metaState = event.getMetaState();
5919 keyEntry.repeatCount = event.getRepeatCount();
5920 keyEntry.downTime = event.getDownTime();
5921 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5924 ALOGD("Unhandled key event: Dispatching fallback key. "
5925 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5926 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
5927 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005928 return true; // restart the event
5929 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005930 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5931 ALOGD("Unhandled key event: No fallback key.");
5932 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005933
5934 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005935 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 }
5937 }
5938 return false;
5939}
5940
Prabir Pradhancef936d2021-07-21 16:17:52 +00005941bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005942 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005943 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944 return false;
5945}
5946
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947void InputDispatcher::traceInboundQueueLengthLocked() {
5948 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005949 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950 }
5951}
5952
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005953void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 if (ATRACE_ENABLED()) {
5955 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005956 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
5957 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 }
5959}
5960
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005961void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962 if (ATRACE_ENABLED()) {
5963 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005964 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
5965 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966 }
5967}
5968
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005969void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005970 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005972 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 dumpDispatchStateLocked(dump);
5974
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005975 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005976 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005977 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978 }
5979}
5980
5981void InputDispatcher::monitor() {
5982 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005983 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005985 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986}
5987
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005988/**
5989 * Wake up the dispatcher and wait until it processes all events and commands.
5990 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5991 * this method can be safely called from any thread, as long as you've ensured that
5992 * the work you are interested in completing has already been queued.
5993 */
5994bool InputDispatcher::waitForIdle() {
5995 /**
5996 * Timeout should represent the longest possible time that a device might spend processing
5997 * events and commands.
5998 */
5999 constexpr std::chrono::duration TIMEOUT = 100ms;
6000 std::unique_lock lock(mLock);
6001 mLooper->wake();
6002 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6003 return result == std::cv_status::no_timeout;
6004}
6005
Vishnu Naire798b472020-07-23 13:52:21 -07006006/**
6007 * Sets focus to the window identified by the token. This must be called
6008 * after updating any input window handles.
6009 *
6010 * Params:
6011 * request.token - input channel token used to identify the window that should gain focus.
6012 * request.focusedToken - the token that the caller expects currently to be focused. If the
6013 * specified token does not match the currently focused window, this request will be dropped.
6014 * If the specified focused token matches the currently focused window, the call will succeed.
6015 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6016 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6017 * when requesting the focus change. This determines which request gets
6018 * precedence if there is a focus change request from another source such as pointer down.
6019 */
Vishnu Nair958da932020-08-21 17:12:37 -07006020void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6021 { // acquire lock
6022 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006023 std::optional<FocusResolver::FocusChanges> changes =
6024 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6025 if (changes) {
6026 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006027 }
6028 } // release lock
6029 // Wake up poll loop since it may need to make new input dispatching choices.
6030 mLooper->wake();
6031}
6032
Vishnu Nairc519ff72021-01-21 08:23:08 -08006033void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6034 if (changes.oldFocus) {
6035 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006036 if (focusedInputChannel) {
6037 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6038 "focus left window");
6039 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006040 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006041 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006042 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006043 if (changes.newFocus) {
6044 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006045 }
6046
Prabir Pradhan99987712020-11-10 18:43:05 -08006047 // If a window has pointer capture, then it must have focus. We need to ensure that this
6048 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6049 // If the window loses focus before it loses pointer capture, then the window can be in a state
6050 // where it has pointer capture but not focus, violating the contract. Therefore we must
6051 // dispatch the pointer capture event before the focus event. Since focus events are added to
6052 // the front of the queue (above), we add the pointer capture event to the front of the queue
6053 // after the focus events are added. This ensures the pointer capture event ends up at the
6054 // front.
6055 disablePointerCaptureForcedLocked();
6056
Vishnu Nairc519ff72021-01-21 08:23:08 -08006057 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006058 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006059 }
6060}
Vishnu Nair958da932020-08-21 17:12:37 -07006061
Prabir Pradhan99987712020-11-10 18:43:05 -08006062void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006063 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006064 return;
6065 }
6066
6067 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6068
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006069 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006070 setPointerCaptureLocked(false);
6071 }
6072
6073 if (!mWindowTokenWithPointerCapture) {
6074 // No need to send capture changes because no window has capture.
6075 return;
6076 }
6077
6078 if (mPendingEvent != nullptr) {
6079 // Move the pending event to the front of the queue. This will give the chance
6080 // for the pending event to be dropped if it is a captured event.
6081 mInboundQueue.push_front(mPendingEvent);
6082 mPendingEvent = nullptr;
6083 }
6084
6085 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006086 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006087 mInboundQueue.push_front(std::move(entry));
6088}
6089
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006090void InputDispatcher::setPointerCaptureLocked(bool enable) {
6091 mCurrentPointerCaptureRequest.enable = enable;
6092 mCurrentPointerCaptureRequest.seq++;
6093 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006094 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006095 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006096 };
6097 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006098}
6099
Vishnu Nair599f1412021-06-21 10:39:58 -07006100void InputDispatcher::displayRemoved(int32_t displayId) {
6101 { // acquire lock
6102 std::scoped_lock _l(mLock);
6103 // Set an empty list to remove all handles from the specific display.
6104 setInputWindowsLocked(/* window handles */ {}, displayId);
6105 setFocusedApplicationLocked(displayId, nullptr);
6106 // Call focus resolver to clean up stale requests. This must be called after input windows
6107 // have been removed for the removed display.
6108 mFocusResolver.displayRemoved(displayId);
6109 } // release lock
6110
6111 // Wake up poll loop since it may need to make new input dispatching choices.
6112 mLooper->wake();
6113}
6114
chaviw15fab6f2021-06-07 14:15:52 -05006115void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6116 // The listener sends the windows as a flattened array. Separate the windows by display for
6117 // more convenient parsing.
6118 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6119
6120 for (const auto& info : windowInfos) {
6121 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6122 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6123 }
6124 setInputWindows(handlesPerDisplay);
6125}
6126
Garfield Tane84e6f92019-08-29 17:28:41 -07006127} // namespace android::inputdispatcher