blob: 59cb419d2b79cff667e398ad5c1dadb2bb01775c [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 mFocusedWindowRequestedPointerCapture(false),
563 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000564 mLatencyAggregator(),
565 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000566 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800568 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569
Yi Kong9b14ac62018-07-17 13:48:38 -0700570 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571
572 policy->getDispatcherConfiguration(&mConfig);
573}
574
575InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000576 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
Prabir Pradhancef936d2021-07-21 16:17:52 +0000578 resetKeyRepeatLocked();
579 releasePendingEventLocked();
580 drainInboundQueueLocked();
581 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000583 while (!mConnectionsByToken.empty()) {
584 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000585 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
586 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 }
588}
589
chaviw15fab6f2021-06-07 14:15:52 -0500590void InputDispatcher::onFirstRef() {
591 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
592}
593
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700594status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700595 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596 return ALREADY_EXISTS;
597 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700598 mThread = std::make_unique<InputThread>(
599 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
600 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700601}
602
603status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700604 if (mThread && mThread->isCallingThread()) {
605 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700606 return INVALID_OPERATION;
607 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700608 mThread.reset();
609 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700610}
611
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612void InputDispatcher::dispatchOnce() {
613 nsecs_t nextWakeupTime = LONG_LONG_MAX;
614 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800615 std::scoped_lock _l(mLock);
616 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617
618 // Run a dispatch loop if there are no pending commands.
619 // The dispatch loop might enqueue commands to run afterwards.
620 if (!haveCommandsLocked()) {
621 dispatchOnceInnerLocked(&nextWakeupTime);
622 }
623
624 // Run all pending commands if there are any.
625 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000626 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 nextWakeupTime = LONG_LONG_MIN;
628 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800629
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700630 // If we are still waiting for ack on some events,
631 // we might have to wake up earlier to check if an app is anr'ing.
632 const nsecs_t nextAnrCheck = processAnrsLocked();
633 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
634
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800635 // We are about to enter an infinitely long sleep, because we have no commands or
636 // pending or queued events
637 if (nextWakeupTime == LONG_LONG_MAX) {
638 mDispatcherEnteredIdle.notify_all();
639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 } // release lock
641
642 // Wait for callback or timeout or wake. (make sure we round up, not down)
643 nsecs_t currentTime = now();
644 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
645 mLooper->pollOnce(timeoutMillis);
646}
647
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500649 * Raise ANR if there is no focused window.
650 * Before the ANR is raised, do a final state check:
651 * 1. The currently focused application must be the same one we are waiting for.
652 * 2. Ensure we still don't have a focused window.
653 */
654void InputDispatcher::processNoFocusedWindowAnrLocked() {
655 // Check if the application that we are waiting for is still focused.
656 std::shared_ptr<InputApplicationHandle> focusedApplication =
657 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
658 if (focusedApplication == nullptr ||
659 focusedApplication->getApplicationToken() !=
660 mAwaitedFocusedApplication->getApplicationToken()) {
661 // Unexpected because we should have reset the ANR timer when focused application changed
662 ALOGE("Waited for a focused window, but focused application has already changed to %s",
663 focusedApplication->getName().c_str());
664 return; // The focused application has changed.
665 }
666
chaviw98318de2021-05-19 16:45:23 -0500667 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500668 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
669 if (focusedWindowHandle != nullptr) {
670 return; // We now have a focused window. No need for ANR.
671 }
672 onAnrLocked(mAwaitedFocusedApplication);
673}
674
675/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700676 * Check if any of the connections' wait queues have events that are too old.
677 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
678 * Return the time at which we should wake up next.
679 */
680nsecs_t InputDispatcher::processAnrsLocked() {
681 const nsecs_t currentTime = now();
682 nsecs_t nextAnrCheck = LONG_LONG_MAX;
683 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
684 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
685 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500686 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700687 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500688 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 return LONG_LONG_MIN;
690 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500691 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700692 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
693 }
694 }
695
696 // Check if any connection ANRs are due
697 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
698 if (currentTime < nextAnrCheck) { // most likely scenario
699 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
700 }
701
702 // If we reached here, we have an unresponsive connection.
703 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
704 if (connection == nullptr) {
705 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
706 return nextAnrCheck;
707 }
708 connection->responsive = false;
709 // Stop waking up for this unresponsive connection
710 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000711 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 return LONG_LONG_MIN;
713}
714
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500715std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500716 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700717 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500718 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500720 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721}
722
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
724 nsecs_t currentTime = now();
725
Jeff Browndc5992e2014-04-11 01:27:26 -0700726 // Reset the key repeat timer whenever normal dispatch is suspended while the
727 // device is in a non-interactive state. This is to ensure that we abort a key
728 // repeat if the device is just coming out of sleep.
729 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 resetKeyRepeatLocked();
731 }
732
733 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
734 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100735 if (DEBUG_FOCUS) {
736 ALOGD("Dispatch frozen. Waiting some more.");
737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 return;
739 }
740
741 // Optimize latency of app switches.
742 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
743 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
744 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
745 if (mAppSwitchDueTime < *nextWakeupTime) {
746 *nextWakeupTime = mAppSwitchDueTime;
747 }
748
749 // Ready to start a new event.
750 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700751 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700752 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 if (isAppSwitchDue) {
754 // The inbound queue is empty so the app switch key we were waiting
755 // for will never arrive. Stop waiting for it.
756 resetPendingAppSwitchLocked(false);
757 isAppSwitchDue = false;
758 }
759
760 // Synthesize a key repeat if appropriate.
761 if (mKeyRepeatState.lastKeyEntry) {
762 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
763 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
764 } else {
765 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
766 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
767 }
768 }
769 }
770
771 // Nothing to do if there is no pending event.
772 if (!mPendingEvent) {
773 return;
774 }
775 } else {
776 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700777 mPendingEvent = mInboundQueue.front();
778 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 traceInboundQueueLengthLocked();
780 }
781
782 // Poke user activity for this event.
783 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700784 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787
788 // Now we have an event to dispatch.
789 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700790 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700792 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 }
798
799 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700800 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802
803 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700804 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700805 const ConfigurationChangedEntry& typedEntry =
806 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700808 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 break;
810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700812 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700813 const DeviceResetEntry& typedEntry =
814 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 break;
818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100820 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700821 std::shared_ptr<FocusEntry> typedEntry =
822 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100823 dispatchFocusLocked(currentTime, typedEntry);
824 done = true;
825 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
826 break;
827 }
828
Prabir Pradhan99987712020-11-10 18:43:05 -0800829 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
830 const auto typedEntry =
831 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
832 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
833 done = true;
834 break;
835 }
836
arthurhungb89ccb02020-12-30 16:19:01 +0800837 case EventEntry::Type::DRAG: {
838 std::shared_ptr<DragEntry> typedEntry =
839 std::static_pointer_cast<DragEntry>(mPendingEvent);
840 dispatchDragLocked(currentTime, typedEntry);
841 done = true;
842 break;
843 }
844
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700845 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700846 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700847 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700848 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 resetPendingAppSwitchLocked(true);
850 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 } else if (dropReason == DropReason::NOT_DROPPED) {
852 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700853 }
854 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700855 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700856 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700858 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
859 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 break;
863 }
864
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700865 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700866 std::shared_ptr<MotionEntry> motionEntry =
867 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
869 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700872 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700874 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
875 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700877 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 }
Chris Yef59a2f42020-10-16 12:55:26 -0700880
881 case EventEntry::Type::SENSOR: {
882 std::shared_ptr<SensorEntry> sensorEntry =
883 std::static_pointer_cast<SensorEntry>(mPendingEvent);
884 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
885 dropReason = DropReason::APP_SWITCH;
886 }
887 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
888 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
889 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
890 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
891 dropReason = DropReason::STALE;
892 }
893 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
894 done = true;
895 break;
896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
899 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700901 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
Michael Wright3a981722015-06-10 15:26:13 +0100903 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904
905 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908}
909
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700910/**
911 * Return true if the events preceding this incoming motion event should be dropped
912 * Return false otherwise (the default behaviour)
913 */
914bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700915 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700916 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700917
918 // Optimize case where the current application is unresponsive and the user
919 // decides to touch a window in a different application.
920 // If the application takes too long to catch up then we drop all events preceding
921 // the touch into the other window.
922 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700923 int32_t displayId = motionEntry.displayId;
924 int32_t x = static_cast<int32_t>(
925 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
926 int32_t y = static_cast<int32_t>(
927 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500928 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 findTouchedWindowAtLocked(displayId, x, y, nullptr);
930 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931 touchedWindowHandle->getApplicationToken() !=
932 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700933 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 ALOGI("Pruning input queue because user touched a different application while waiting "
935 "for %s",
936 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 return true;
938 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939
940 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600941 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
943 sp<Connection> connection =
944 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000945 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 // This monitor could take more input. Drop all events preceding this
947 // event, so that gesture monitor could get a chance to receive the stream
948 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
949 "responsive gesture monitor that may handle the event",
950 mAwaitedFocusedApplication->getName().c_str());
951 return true;
952 }
953 }
954 }
955
956 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
957 // yet been processed by some connections, the dispatcher will wait for these motion
958 // events to be processed before dispatching the key event. This is because these motion events
959 // may cause a new window to be launched, which the user might expect to receive focus.
960 // To prevent waiting forever for such events, just send the key to the currently focused window
961 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
962 ALOGD("Received a new pointer down event, stop waiting for events to process and "
963 "just send the pending key event to the focused window.");
964 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700965 }
966 return false;
967}
968
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700969bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700970 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700971 mInboundQueue.push_back(std::move(newEntry));
972 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 traceInboundQueueLengthLocked();
974
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700976 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 // Optimize app switch latency.
978 // If the application takes too long to catch up then we drop all events preceding
979 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700980 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700982 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700984 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000986 if (DEBUG_APP_SWITCH) {
987 ALOGD("App switch is pending!");
988 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700989 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 mAppSwitchSawKeyDown = false;
991 needWake = true;
992 }
993 }
994 }
995 break;
996 }
997
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700998 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1000 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001001 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001005 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001006 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1007 break;
1008 }
1009 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001010 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001011 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001012 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1013 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001014 // nothing to do
1015 break;
1016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
1018
1019 return needWake;
1020}
1021
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001022void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001023 // Do not store sensor event in recent queue to avoid flooding the queue.
1024 if (entry->type != EventEntry::Type::SENSOR) {
1025 mRecentQueue.push_back(entry);
1026 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001027 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001028 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030}
1031
chaviw98318de2021-05-19 16:45:23 -05001032sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1033 int32_t y, TouchState* touchState,
1034 bool addOutsideTargets,
1035 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001036 if (addOutsideTargets && touchState == nullptr) {
1037 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001040 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1041 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001042 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001043 continue;
1044 }
chaviw98318de2021-05-19 16:45:23 -05001045 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001047 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048
1049 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001050 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1051 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1052 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1054 // Found window.
1055 return windowHandle;
1056 }
1057 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001058
chaviw98318de2021-05-19 16:45:23 -05001059 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001060 touchState->addOrUpdateWindow(windowHandle,
1061 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1062 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001067 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068}
1069
Garfield Tane84e6f92019-08-29 17:28:41 -07001070std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001071 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001072 std::vector<TouchedMonitor> touchedMonitors;
1073
1074 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1075 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001076 return touchedMonitors;
1077}
1078
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001079void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 const char* reason;
1081 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001083 if (DEBUG_INBOUND_EVENT_DETAILS) {
1084 ALOGD("Dropped event because policy consumed it.");
1085 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 reason = "inbound event was dropped because the policy consumed it";
1087 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::DISABLED:
1089 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 ALOGI("Dropped event because input dispatch is disabled.");
1091 }
1092 reason = "inbound event was dropped because input dispatch is disabled";
1093 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001094 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 ALOGI("Dropped event because of pending overdue app switch.");
1096 reason = "inbound event was dropped because of pending overdue app switch";
1097 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001098 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 ALOGI("Dropped event because the current application is not responding and the user "
1100 "has started interacting with a different application.");
1101 reason = "inbound event was dropped because the current application is not responding "
1102 "and the user has started interacting with a different application";
1103 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001104 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 ALOGI("Dropped event because it is stale.");
1106 reason = "inbound event was dropped because it is stale";
1107 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001108 case DropReason::NO_POINTER_CAPTURE:
1109 ALOGI("Dropped event because there is no window with Pointer Capture.");
1110 reason = "inbound event was dropped because there is no window with Pointer Capture";
1111 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001112 case DropReason::NOT_DROPPED: {
1113 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 }
1117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001118 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001119 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1121 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001125 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1126 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1128 synthesizeCancelationEventsForAllConnectionsLocked(options);
1129 } else {
1130 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1131 synthesizeCancelationEventsForAllConnectionsLocked(options);
1132 }
1133 break;
1134 }
Chris Yef59a2f42020-10-16 12:55:26 -07001135 case EventEntry::Type::SENSOR: {
1136 break;
1137 }
arthurhungb89ccb02020-12-30 16:19:01 +08001138 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1139 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001140 break;
1141 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001142 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001143 case EventEntry::Type::CONFIGURATION_CHANGED:
1144 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001145 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001146 break;
1147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149}
1150
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001151static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1153 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154}
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1157 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1158 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1159 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160}
1161
1162bool InputDispatcher::isAppSwitchPendingLocked() {
1163 return mAppSwitchDueTime != LONG_LONG_MAX;
1164}
1165
1166void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1167 mAppSwitchDueTime = LONG_LONG_MAX;
1168
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001169 if (DEBUG_APP_SWITCH) {
1170 if (handled) {
1171 ALOGD("App switch has arrived.");
1172 } else {
1173 ALOGD("App switch was abandoned.");
1174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001179 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180}
1181
Prabir Pradhancef936d2021-07-21 16:17:52 +00001182bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001183 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 return false;
1185 }
1186
1187 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001188 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001190 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1191 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 return true;
1194}
1195
Prabir Pradhancef936d2021-07-21 16:17:52 +00001196void InputDispatcher::postCommandLocked(Command&& command) {
1197 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198}
1199
1200void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001201 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 releaseInboundEventLocked(entry);
1205 }
1206 traceInboundQueueLengthLocked();
1207}
1208
1209void InputDispatcher::releasePendingEventLocked() {
1210 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001212 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214}
1215
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001216void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001218 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001219 if (DEBUG_DISPATCH_CYCLE) {
1220 ALOGD("Injected inbound event was dropped.");
1221 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001225 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228}
1229
1230void InputDispatcher::resetKeyRepeatLocked() {
1231 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001232 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234}
1235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1237 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238
Michael Wright2e732952014-09-24 13:26:59 -07001239 uint32_t policyFlags = entry->policyFlags &
1240 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 std::shared_ptr<KeyEntry> newEntry =
1243 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1244 entry->source, entry->displayId, policyFlags, entry->action,
1245 entry->flags, entry->keyCode, entry->scanCode,
1246 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 newEntry->syntheticRepeat = true;
1249 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252}
1253
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001256 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1257 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259
1260 // Reset key repeating in case a keyboard device was added or removed or something.
1261 resetKeyRepeatLocked();
1262
1263 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001264 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1265 scoped_unlock unlock(mLock);
1266 mPolicy->notifyConfigurationChanged(eventTime);
1267 };
1268 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 return true;
1270}
1271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1273 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001274 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1275 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1276 entry.deviceId);
1277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278
liushenxiang42232912021-05-21 20:24:09 +08001279 // Reset key repeating in case a keyboard device was disabled or enabled.
1280 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1281 resetKeyRepeatLocked();
1282 }
1283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 synthesizeCancelationEventsForAllConnectionsLocked(options);
1287 return true;
1288}
1289
Vishnu Nairad321cd2020-08-20 16:40:21 -07001290void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001291 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001292 if (mPendingEvent != nullptr) {
1293 // Move the pending event to the front of the queue. This will give the chance
1294 // for the pending event to get dispatched to the newly focused window
1295 mInboundQueue.push_front(mPendingEvent);
1296 mPendingEvent = nullptr;
1297 }
1298
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 std::unique_ptr<FocusEntry> focusEntry =
1300 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1301 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302
1303 // This event should go to the front of the queue, but behind all other focus events
1304 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001306 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 [](const std::shared_ptr<EventEntry>& event) {
1308 return event->type == EventEntry::Type::FOCUS;
1309 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001310
1311 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001312 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001313}
1314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001316 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001317 if (channel == nullptr) {
1318 return; // Window has gone away
1319 }
1320 InputTarget target;
1321 target.inputChannel = channel;
1322 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1323 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001324 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1325 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001326 std::string reason = std::string("reason=").append(entry->reason);
1327 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001328 dispatchEventLocked(currentTime, entry, {target});
1329}
1330
Prabir Pradhan99987712020-11-10 18:43:05 -08001331void InputDispatcher::dispatchPointerCaptureChangedLocked(
1332 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1333 DropReason& dropReason) {
1334 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001335 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1336 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1337 }
1338 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001339 // Pointer capture was already forcefully disabled because of focus change.
1340 dropReason = DropReason::NOT_DROPPED;
1341 return;
1342 }
1343
1344 // Set drop reason for early returns
1345 dropReason = DropReason::NO_POINTER_CAPTURE;
1346
1347 sp<IBinder> token;
1348 if (entry->pointerCaptureEnabled) {
1349 // Enable Pointer Capture
1350 if (!mFocusedWindowRequestedPointerCapture) {
1351 // This can happen if a window requests capture and immediately releases capture.
1352 ALOGW("No window requested Pointer Capture.");
1353 return;
1354 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001355 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1357 mWindowTokenWithPointerCapture = token;
1358 } else {
1359 // Disable Pointer Capture
1360 token = mWindowTokenWithPointerCapture;
1361 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001362 if (mFocusedWindowRequestedPointerCapture) {
1363 mFocusedWindowRequestedPointerCapture = false;
1364 setPointerCaptureLocked(false);
1365 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001366 }
1367
1368 auto channel = getInputChannelLocked(token);
1369 if (channel == nullptr) {
1370 // Window has gone away, clean up Pointer Capture state.
1371 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001372 if (mFocusedWindowRequestedPointerCapture) {
1373 mFocusedWindowRequestedPointerCapture = false;
1374 setPointerCaptureLocked(false);
1375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 return;
1377 }
1378 InputTarget target;
1379 target.inputChannel = channel;
1380 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1381 entry->dispatchInProgress = true;
1382 dispatchEventLocked(currentTime, entry, {target});
1383
1384 dropReason = DropReason::NOT_DROPPED;
1385}
1386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001387bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001390 if (!entry->dispatchInProgress) {
1391 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1392 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1393 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1394 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001395 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 // We have seen two identical key downs in a row which indicates that the device
1397 // driver is automatically generating key repeats itself. We take note of the
1398 // repeat here, but we disable our own next key repeat timer since it is clear that
1399 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001400 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1401 // Make sure we don't get key down from a different device. If a different
1402 // device Id has same key pressed down, the new device Id will replace the
1403 // current one to hold the key repeat with repeat count reset.
1404 // In the future when got a KEY_UP on the device id, drop it and do not
1405 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1407 resetKeyRepeatLocked();
1408 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1409 } else {
1410 // Not a repeat. Save key down state in case we do see a repeat later.
1411 resetKeyRepeatLocked();
1412 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1413 }
1414 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001415 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1416 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001417 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001418 if (DEBUG_INBOUND_EVENT_DETAILS) {
1419 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1420 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001421 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 resetKeyRepeatLocked();
1423 }
1424
1425 if (entry->repeatCount == 1) {
1426 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1427 } else {
1428 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1429 }
1430
1431 entry->dispatchInProgress = true;
1432
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
1435
1436 // Handle case where the policy asked us to try again later last time.
1437 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1438 if (currentTime < entry->interceptKeyWakeupTime) {
1439 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1440 *nextWakeupTime = entry->interceptKeyWakeupTime;
1441 }
1442 return false; // wait until next wakeup
1443 }
1444 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1445 entry->interceptKeyWakeupTime = 0;
1446 }
1447
1448 // Give the policy a chance to intercept the key.
1449 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1450 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001451 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001452 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001453
1454 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1455 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1456 };
1457 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 return false; // wait for the command to run
1459 } else {
1460 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1461 }
1462 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001463 if (*dropReason == DropReason::NOT_DROPPED) {
1464 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 }
1466 }
1467
1468 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001469 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001470 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001471 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1472 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001473 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 return true;
1475 }
1476
1477 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001478 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001479 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001481 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 return false;
1483 }
1484
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001485 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001486 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 return true;
1488 }
1489
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001490 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492
1493 // Dispatch the key.
1494 dispatchEventLocked(currentTime, entry, inputTargets);
1495 return true;
1496}
1497
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001498void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001499 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1500 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1501 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1502 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1503 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1504 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1505 entry.metaState, entry.repeatCount, entry.downTime);
1506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507}
1508
Prabir Pradhancef936d2021-07-21 16:17:52 +00001509void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1510 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001511 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001512 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1513 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1514 "source=0x%x, sensorType=%s",
1515 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1516 NamedEnum::string(entry->sensorType).c_str());
1517 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001518 auto command = [this, entry]() REQUIRES(mLock) {
1519 scoped_unlock unlock(mLock);
1520
1521 if (entry->accuracyChanged) {
1522 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1523 }
1524 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1525 entry->hwTimestamp, entry->values);
1526 };
1527 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001528}
1529
1530bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001531 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1532 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1533 NamedEnum::string(sensorType).c_str());
1534 }
Chris Yef59a2f42020-10-16 12:55:26 -07001535 { // acquire lock
1536 std::scoped_lock _l(mLock);
1537
1538 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1539 std::shared_ptr<EventEntry> entry = *it;
1540 if (entry->type == EventEntry::Type::SENSOR) {
1541 it = mInboundQueue.erase(it);
1542 releaseInboundEventLocked(entry);
1543 }
1544 }
1545 }
1546 return true;
1547}
1548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001551 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001553 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 entry->dispatchInProgress = true;
1555
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001556 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 }
1558
1559 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001560 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001561 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001562 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1563 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 return true;
1565 }
1566
1567 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1568
1569 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001570 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571
1572 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 if (isPointerEvent) {
1575 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001577 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001578 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 } else {
1580 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001582 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001584 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 return false;
1586 }
1587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001590 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1591 return true;
1592 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001593 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001594 CancelationOptions::Mode mode(isPointerEvent
1595 ? CancelationOptions::CANCEL_POINTER_EVENTS
1596 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1597 CancelationOptions options(mode, "input event injection failed");
1598 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 return true;
1600 }
1601
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001602 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
1605 // Dispatch the motion.
1606 if (conflictingPointerActions) {
1607 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 synthesizeCancelationEventsForAllConnectionsLocked(options);
1610 }
1611 dispatchEventLocked(currentTime, entry, inputTargets);
1612 return true;
1613}
1614
chaviw98318de2021-05-19 16:45:23 -05001615void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001616 bool isExiting, const MotionEntry& motionEntry) {
1617 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1618 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1619 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1620 PointerCoords pointerCoords;
1621 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1622 pointerCoords.transform(windowHandle->getInfo()->transform);
1623
1624 std::unique_ptr<DragEntry> dragEntry =
1625 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1626 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1627 pointerCoords.getY());
1628
1629 enqueueInboundEventLocked(std::move(dragEntry));
1630}
1631
1632void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1633 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1634 if (channel == nullptr) {
1635 return; // Window has gone away
1636 }
1637 InputTarget target;
1638 target.inputChannel = channel;
1639 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1640 entry->dispatchInProgress = true;
1641 dispatchEventLocked(currentTime, entry, {target});
1642}
1643
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001645 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1646 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1647 ", policyFlags=0x%x, "
1648 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1649 "metaState=0x%x, buttonState=0x%x,"
1650 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1651 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1652 entry.policyFlags, entry.action, entry.actionButton, entry.flags, entry.metaState,
1653 entry.buttonState, entry.edgeFlags, entry.xPrecision, entry.yPrecision,
1654 entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001656 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1657 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1658 "x=%f, y=%f, pressure=%f, size=%f, "
1659 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1660 "orientation=%f",
1661 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1662 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1663 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1664 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1665 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1666 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1667 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1668 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1669 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1670 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673}
1674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001675void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1676 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001677 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001678 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001679 if (DEBUG_DISPATCH_CYCLE) {
1680 ALOGD("dispatchEventToCurrentInputTargets");
1681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001683 updateInteractionTokensLocked(*eventEntry, inputTargets);
1684
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1686
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001687 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001689 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001690 sp<Connection> connection =
1691 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001692 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001693 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001695 if (DEBUG_FOCUS) {
1696 ALOGD("Dropping event delivery to target with channel '%s' because it "
1697 "is no longer registered with the input dispatcher.",
1698 inputTarget.inputChannel->getName().c_str());
1699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701 }
1702}
1703
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001704void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1705 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1706 // If the policy decides to close the app, we will get a channel removal event via
1707 // unregisterInputChannel, and will clean up the connection that way. We are already not
1708 // sending new pointers to the connection when it blocked, but focused events will continue to
1709 // pile up.
1710 ALOGW("Canceling events for %s because it is unresponsive",
1711 connection->inputChannel->getName().c_str());
1712 if (connection->status == Connection::STATUS_NORMAL) {
1713 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1714 "application not responding");
1715 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717}
1718
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001719void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001720 if (DEBUG_FOCUS) {
1721 ALOGD("Resetting ANR timeouts.");
1722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723
1724 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001725 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001726 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727}
1728
Tiger Huang721e26f2018-07-24 22:26:19 +08001729/**
1730 * Get the display id that the given event should go to. If this event specifies a valid display id,
1731 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1732 * Focused display is the display that the user most recently interacted with.
1733 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001735 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001737 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001738 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1739 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 break;
1741 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001742 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001743 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1744 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001745 break;
1746 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001747 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001748 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001749 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001750 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001751 case EventEntry::Type::SENSOR:
1752 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001753 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 return ADISPLAY_ID_NONE;
1755 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001756 }
1757 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1758}
1759
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001760bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1761 const char* focusedWindowName) {
1762 if (mAnrTracker.empty()) {
1763 // already processed all events that we waited for
1764 mKeyIsWaitingForEventsTimeout = std::nullopt;
1765 return false;
1766 }
1767
1768 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1769 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001770 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001771 mKeyIsWaitingForEventsTimeout = currentTime +
1772 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1773 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001774 return true;
1775 }
1776
1777 // We still have pending events, and already started the timer
1778 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1779 return true; // Still waiting
1780 }
1781
1782 // Waited too long, and some connection still hasn't processed all motions
1783 // Just send the key to the focused window
1784 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1785 focusedWindowName);
1786 mKeyIsWaitingForEventsTimeout = std::nullopt;
1787 return false;
1788}
1789
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001790InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1791 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1792 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001793 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794
Tiger Huang721e26f2018-07-24 22:26:19 +08001795 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001796 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001797 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001798 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1799
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 // If there is no currently focused window and no focused application
1801 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001802 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1803 ALOGI("Dropping %s event because there is no focused window or focused application in "
1804 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001805 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 }
1808
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001809 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1810 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1811 // start interacting with another application via touch (app switch). This code can be removed
1812 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1813 // an app is expected to have a focused window.
1814 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1815 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1816 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001817 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1818 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1819 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001820 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001821 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822 ALOGW("Waiting because no window has focus but %s may eventually add a "
1823 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001824 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001825 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001826 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001827 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1828 // Already raised ANR. Drop the event
1829 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001830 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001832 } else {
1833 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001834 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001835 }
1836 }
1837
1838 // we have a valid, non-null focused window
1839 resetNoFocusedWindowTimeoutLocked();
1840
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001842 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
1845
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846 if (focusedWindowHandle->getInfo()->paused) {
1847 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 }
1850
1851 // If the event is a key event, then we must wait for all previous events to
1852 // complete before delivering it because previous events may have the
1853 // side-effect of transferring focus to a different window and we want to
1854 // ensure that the following keys are sent to the new window.
1855 //
1856 // Suppose the user touches a button in a window then immediately presses "A".
1857 // If the button causes a pop-up window to appear then we want to ensure that
1858 // the "A" key is delivered to the new pop-up window. This is because users
1859 // often anticipate pending UI changes when typing on a keyboard.
1860 // To obtain this behavior, we must serialize key events with respect to all
1861 // prior input events.
1862 if (entry.type == EventEntry::Type::KEY) {
1863 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1864 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001865 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 }
1868
1869 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001870 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001871 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1872 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873
1874 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001875 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876}
1877
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001878/**
1879 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1880 * that are currently unresponsive.
1881 */
1882std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1883 const std::vector<TouchedMonitor>& monitors) const {
1884 std::vector<TouchedMonitor> responsiveMonitors;
1885 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1886 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1887 sp<Connection> connection = getConnectionLocked(
1888 monitor.monitor.inputChannel->getConnectionToken());
1889 if (connection == nullptr) {
1890 ALOGE("Could not find connection for monitor %s",
1891 monitor.monitor.inputChannel->getName().c_str());
1892 return false;
1893 }
1894 if (!connection->responsive) {
1895 ALOGW("Unresponsive monitor %s will not get the new gesture",
1896 connection->inputChannel->getName().c_str());
1897 return false;
1898 }
1899 return true;
1900 });
1901 return responsiveMonitors;
1902}
1903
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1905 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1906 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001907 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 enum InjectionPermission {
1909 INJECTION_PERMISSION_UNKNOWN,
1910 INJECTION_PERMISSION_GRANTED,
1911 INJECTION_PERMISSION_DENIED
1912 };
1913
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 // For security reasons, we defer updating the touch state until we are sure that
1915 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001916 int32_t displayId = entry.displayId;
1917 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1919
1920 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001923 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1924 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001926 // Copy current touch state into tempTouchState.
1927 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1928 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001929 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001930 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001931 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1932 mTouchStatesByDisplay.find(displayId);
1933 if (oldStateIt != mTouchStatesByDisplay.end()) {
1934 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001935 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001936 }
1937
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001938 bool isSplit = tempTouchState.split;
1939 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1940 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1941 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001942 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1943 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1944 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1945 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1946 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001947 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 bool wrongDevice = false;
1949 if (newGesture) {
1950 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001951 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001952 ALOGI("Dropping event because a pointer for a different device is already down "
1953 "in display %" PRId32,
1954 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001955 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001956 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 switchedDevice = false;
1958 wrongDevice = true;
1959 goto Failed;
1960 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001961 tempTouchState.reset();
1962 tempTouchState.down = down;
1963 tempTouchState.deviceId = entry.deviceId;
1964 tempTouchState.source = entry.source;
1965 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001967 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001968 ALOGI("Dropping move event because a pointer for a different device is already active "
1969 "in display %" PRId32,
1970 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001971 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001972 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001973 switchedDevice = false;
1974 wrongDevice = true;
1975 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977
1978 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1979 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1980
Garfield Tan00f511d2019-06-12 16:55:40 -07001981 int32_t x;
1982 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001984 // Always dispatch mouse events to cursor position.
1985 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986 x = int32_t(entry.xCursorPosition);
1987 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001988 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1990 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001991 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001993 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1994 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001995
1996 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001997 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00001998 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002001 if (newTouchedWindowHandle != nullptr &&
2002 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002003 // New window supports splitting, but we should never split mouse events.
2004 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 } else if (isSplit) {
2006 // New window does not support splitting but we have already split events.
2007 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002008 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 }
2010
2011 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002012 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002014 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002015 }
2016
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2018 ALOGI("Not sending touch event to %s because it is paused",
2019 newTouchedWindowHandle->getName().c_str());
2020 newTouchedWindowHandle = nullptr;
2021 }
2022
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002023 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002025 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2026 if (!isResponsive) {
2027 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2029 newTouchedWindowHandle = nullptr;
2030 }
2031 }
2032
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002033 // Drop events that can't be trusted due to occlusion
2034 if (newTouchedWindowHandle != nullptr &&
2035 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2036 TouchOcclusionInfo occlusionInfo =
2037 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002038 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002039 if (DEBUG_TOUCH_OCCLUSION) {
2040 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2041 for (const auto& log : occlusionInfo.debugInfo) {
2042 ALOGD("%s", log.c_str());
2043 }
2044 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002045 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002046 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2047 ALOGW("Dropping untrusted touch event due to %s/%d",
2048 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2049 newTouchedWindowHandle = nullptr;
2050 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002051 }
2052 }
2053
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002054 // Also don't send the new touch event to unresponsive gesture monitors
2055 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2056
Michael Wright3dd60e22019-03-27 22:06:44 +00002057 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2058 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002059 "(%d, %d) in display %" PRId32 ".",
2060 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002061 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 goto Failed;
2063 }
2064
2065 if (newTouchedWindowHandle != nullptr) {
2066 // Set target flags.
2067 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2068 if (isSplit) {
2069 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002071 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2072 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2073 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2074 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2075 }
2076
2077 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002078 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2079 newHoverWindowHandle = nullptr;
2080 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002082 }
2083
2084 // Update the temporary touch state.
2085 BitSet32 pointerIds;
2086 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002088 pointerIds.markBit(pointerId);
2089 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002090 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002093 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 } else {
2095 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2096
2097 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002098 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002099 if (DEBUG_FOCUS) {
2100 ALOGD("Dropping event because the pointer is not down or we previously "
2101 "dropped the pointer down event in display %" PRId32,
2102 displayId);
2103 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002104 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 goto Failed;
2106 }
2107
arthurhung6d4bed92021-03-17 11:59:33 +08002108 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002109
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002111 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002112 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002113 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2114 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115
chaviw98318de2021-05-19 16:45:23 -05002116 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002118 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2120 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002121 if (DEBUG_FOCUS) {
2122 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2123 oldTouchedWindowHandle->getName().c_str(),
2124 newTouchedWindowHandle->getName().c_str(), displayId);
2125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2128 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2129 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130
2131 // Make a slippery entrance into the new window.
2132 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2133 isSplit = true;
2134 }
2135
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 int32_t targetFlags =
2137 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 if (isSplit) {
2139 targetFlags |= InputTarget::FLAG_SPLIT;
2140 }
2141 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2142 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002143 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2144 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 }
2146
2147 BitSet32 pointerIds;
2148 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002149 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002151 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153 }
2154 }
2155
2156 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002157 // Let the previous window know that the hover sequence is over, unless we already did it
2158 // when dispatching it as is to newTouchedWindowHandle.
2159 if (mLastHoverWindowHandle != nullptr &&
2160 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2161 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002162 if (DEBUG_HOVER) {
2163 ALOGD("Sending hover exit event to window %s.",
2164 mLastHoverWindowHandle->getName().c_str());
2165 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002166 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2167 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 }
2169
Garfield Tandf26e862020-07-01 20:18:19 -07002170 // Let the new window know that the hover sequence is starting, unless we already did it
2171 // when dispatching it as is to newTouchedWindowHandle.
2172 if (newHoverWindowHandle != nullptr &&
2173 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2174 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002175 if (DEBUG_HOVER) {
2176 ALOGD("Sending hover enter event to window %s.",
2177 newHoverWindowHandle->getName().c_str());
2178 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002179 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2180 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2181 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 }
2183 }
2184
2185 // Check permission to inject into all touched foreground windows and ensure there
2186 // is at least one touched foreground window.
2187 {
2188 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2191 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002192 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002193 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 injectionPermission = INJECTION_PERMISSION_DENIED;
2195 goto Failed;
2196 }
2197 }
2198 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002200 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002201 ALOGI("Dropping event because there is no touched foreground window in display "
2202 "%" PRId32 " or gesture monitor to receive it.",
2203 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002204 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 goto Failed;
2206 }
2207
2208 // Permission granted to injection into all touched foreground windows.
2209 injectionPermission = INJECTION_PERMISSION_GRANTED;
2210 }
2211
2212 // Check whether windows listening for outside touches are owned by the same UID. If it is
2213 // set the policy flag that we will not reveal coordinate information to this window.
2214 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002215 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002216 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002217 if (foregroundWindowHandle) {
2218 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002219 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002220 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002221 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2222 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2223 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002224 InputTarget::FLAG_ZERO_COORDS,
2225 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228 }
2229 }
2230 }
2231
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 // If this is the first pointer going down and the touched window has a wallpaper
2233 // then also add the touched wallpaper windows so they are locked in for the duration
2234 // of the touch gesture.
2235 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2236 // engine only supports touch events. We would need to add a mechanism similar
2237 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2238 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002239 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002240 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002241 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002242 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002243 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002244 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2245 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002247 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002248 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002249 .addOrUpdateWindow(windowHandle,
2250 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2251 InputTarget::
2252 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2253 InputTarget::FLAG_DISPATCH_AS_IS,
2254 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 }
2256 }
2257 }
2258 }
2259
2260 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002261 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002263 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002268 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002269 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002271 }
2272
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 // Drop the outside or hover touch windows since we will not care about them
2274 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002275 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276
2277Failed:
2278 // Check injection permission once and for all.
2279 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002280 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 injectionPermission = INJECTION_PERMISSION_GRANTED;
2282 } else {
2283 injectionPermission = INJECTION_PERMISSION_DENIED;
2284 }
2285 }
2286
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002287 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2288 return injectionResult;
2289 }
2290
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002292 if (!wrongDevice) {
2293 if (switchedDevice) {
2294 if (DEBUG_FOCUS) {
2295 ALOGD("Conflicting pointer actions: Switched to a different device.");
2296 }
2297 *outConflictingPointerActions = true;
2298 }
2299
2300 if (isHoverAction) {
2301 // Started hovering, therefore no longer down.
2302 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002303 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002304 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2305 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 *outConflictingPointerActions = true;
2308 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002309 tempTouchState.reset();
2310 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2311 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2312 tempTouchState.deviceId = entry.deviceId;
2313 tempTouchState.source = entry.source;
2314 tempTouchState.displayId = displayId;
2315 }
2316 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2317 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2318 // All pointers up or canceled.
2319 tempTouchState.reset();
2320 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2321 // First pointer went down.
2322 if (oldState && oldState->down) {
2323 if (DEBUG_FOCUS) {
2324 ALOGD("Conflicting pointer actions: Down received while already down.");
2325 }
2326 *outConflictingPointerActions = true;
2327 }
2328 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2329 // One pointer went up.
2330 if (isSplit) {
2331 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2332 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002334 for (size_t i = 0; i < tempTouchState.windows.size();) {
2335 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2336 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2337 touchedWindow.pointerIds.clearBit(pointerId);
2338 if (touchedWindow.pointerIds.isEmpty()) {
2339 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2340 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002343 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002345 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002346 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002347
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002348 // Save changes unless the action was scroll in which case the temporary touch
2349 // state was only valid for this one action.
2350 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2351 if (tempTouchState.displayId >= 0) {
2352 mTouchStatesByDisplay[displayId] = tempTouchState;
2353 } else {
2354 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002358 // Update hover state.
2359 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 }
2361
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 return injectionResult;
2363}
2364
arthurhung6d4bed92021-03-17 11:59:33 +08002365void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002366 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002367 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002368 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002369 if (dropWindow) {
2370 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002371 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002372 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002373 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002374 }
2375 mDragState.reset();
2376}
2377
2378void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2379 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002380 return;
2381 }
2382
arthurhung6d4bed92021-03-17 11:59:33 +08002383 if (!mDragState->isStartDrag) {
2384 mDragState->isStartDrag = true;
2385 mDragState->isStylusButtonDownAtStart =
2386 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2387 }
2388
arthurhungb89ccb02020-12-30 16:19:01 +08002389 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2390 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2391 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2392 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002393 // Handle the special case : stylus button no longer pressed.
2394 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2395 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2396 finishDragAndDrop(entry.displayId, x, y);
2397 return;
2398 }
2399
chaviw98318de2021-05-19 16:45:23 -05002400 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002401 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002402 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002403 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002404 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2405 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2406 if (mDragState->dragHoverWindowHandle != nullptr) {
2407 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2408 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002409 }
arthurhung6d4bed92021-03-17 11:59:33 +08002410 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002411 }
2412 // enqueue drag location if needed.
2413 if (hoverWindowHandle != nullptr) {
2414 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2415 }
arthurhung6d4bed92021-03-17 11:59:33 +08002416 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2417 finishDragAndDrop(entry.displayId, x, y);
2418 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002419 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002420 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002421 }
2422}
2423
chaviw98318de2021-05-19 16:45:23 -05002424void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002425 int32_t targetFlags, BitSet32 pointerIds,
2426 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002427 std::vector<InputTarget>::iterator it =
2428 std::find_if(inputTargets.begin(), inputTargets.end(),
2429 [&windowHandle](const InputTarget& inputTarget) {
2430 return inputTarget.inputChannel->getConnectionToken() ==
2431 windowHandle->getToken();
2432 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002433
chaviw98318de2021-05-19 16:45:23 -05002434 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002435
2436 if (it == inputTargets.end()) {
2437 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002438 std::shared_ptr<InputChannel> inputChannel =
2439 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002440 if (inputChannel == nullptr) {
2441 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2442 return;
2443 }
2444 inputTarget.inputChannel = inputChannel;
2445 inputTarget.flags = targetFlags;
2446 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002447 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002448 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002449 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002450 inputTargets.push_back(inputTarget);
2451 it = inputTargets.end() - 1;
2452 }
2453
2454 ALOG_ASSERT(it->flags == targetFlags);
2455 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2456
chaviw1ff3d1e2020-07-01 15:53:47 -07002457 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458}
2459
Michael Wright3dd60e22019-03-27 22:06:44 +00002460void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 int32_t displayId, float xOffset,
2462 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002463 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2464 mGlobalMonitorsByDisplay.find(displayId);
2465
2466 if (it != mGlobalMonitorsByDisplay.end()) {
2467 const std::vector<Monitor>& monitors = it->second;
2468 for (const Monitor& monitor : monitors) {
2469 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
2472}
2473
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002474void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2475 float yOffset,
2476 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002477 InputTarget target;
2478 target.inputChannel = monitor.inputChannel;
2479 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002480 ui::Transform t;
2481 t.set(xOffset, yOffset);
2482 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002483 inputTargets.push_back(target);
2484}
2485
chaviw98318de2021-05-19 16:45:23 -05002486bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 const InjectionState* injectionState) {
2488 if (injectionState &&
2489 (windowHandle == nullptr ||
2490 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2491 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002492 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494 "owned by uid %d",
2495 injectionState->injectorPid, injectionState->injectorUid,
2496 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 } else {
2498 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
2501 return false;
2502 }
2503 return true;
2504}
2505
Robert Carrc9bf1d32020-04-13 17:21:08 -07002506/**
2507 * Indicate whether one window handle should be considered as obscuring
2508 * another window handle. We only check a few preconditions. Actually
2509 * checking the bounds is left to the caller.
2510 */
chaviw98318de2021-05-19 16:45:23 -05002511static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2512 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002513 // Compare by token so cloned layers aren't counted
2514 if (haveSameToken(windowHandle, otherHandle)) {
2515 return false;
2516 }
2517 auto info = windowHandle->getInfo();
2518 auto otherInfo = otherHandle->getInfo();
2519 if (!otherInfo->visible) {
2520 return false;
chaviw98318de2021-05-19 16:45:23 -05002521 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002522 // Those act as if they were invisible, so we don't need to flag them.
2523 // We do want to potentially flag touchable windows even if they have 0
2524 // opacity, since they can consume touches and alter the effects of the
2525 // user interaction (eg. apps that rely on
2526 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2527 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2528 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002529 } else if (info->ownerUid == otherInfo->ownerUid) {
2530 // If ownerUid is the same we don't generate occlusion events as there
2531 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002532 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002533 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002534 return false;
2535 } else if (otherInfo->displayId != info->displayId) {
2536 return false;
2537 }
2538 return true;
2539}
2540
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002541/**
2542 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2543 * untrusted, one should check:
2544 *
2545 * 1. If result.hasBlockingOcclusion is true.
2546 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2547 * BLOCK_UNTRUSTED.
2548 *
2549 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2550 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2551 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2552 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2553 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2554 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2555 *
2556 * If neither of those is true, then it means the touch can be allowed.
2557 */
2558InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002559 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2560 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002561 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002562 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002563 TouchOcclusionInfo info;
2564 info.hasBlockingOcclusion = false;
2565 info.obscuringOpacity = 0;
2566 info.obscuringUid = -1;
2567 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002568 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002569 if (windowHandle == otherHandle) {
2570 break; // All future windows are below us. Exit early.
2571 }
chaviw98318de2021-05-19 16:45:23 -05002572 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002573 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2574 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002575 if (DEBUG_TOUCH_OCCLUSION) {
2576 info.debugInfo.push_back(
2577 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2578 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002579 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2580 // we perform the checks below to see if the touch can be propagated or not based on the
2581 // window's touch occlusion mode
2582 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2583 info.hasBlockingOcclusion = true;
2584 info.obscuringUid = otherInfo->ownerUid;
2585 info.obscuringPackage = otherInfo->packageName;
2586 break;
2587 }
2588 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2589 uint32_t uid = otherInfo->ownerUid;
2590 float opacity =
2591 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2592 // Given windows A and B:
2593 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2594 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2595 opacityByUid[uid] = opacity;
2596 if (opacity > info.obscuringOpacity) {
2597 info.obscuringOpacity = opacity;
2598 info.obscuringUid = uid;
2599 info.obscuringPackage = otherInfo->packageName;
2600 }
2601 }
2602 }
2603 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002604 if (DEBUG_TOUCH_OCCLUSION) {
2605 info.debugInfo.push_back(
2606 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2607 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002608 return info;
2609}
2610
chaviw98318de2021-05-19 16:45:23 -05002611std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002612 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002613 return StringPrintf(INDENT2
2614 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2615 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2616 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2617 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002618 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002619 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002620 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002621 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2622 info->frameTop, info->frameRight, info->frameBottom,
2623 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002624 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2625 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2626 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002627}
2628
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002629bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2630 if (occlusionInfo.hasBlockingOcclusion) {
2631 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2632 occlusionInfo.obscuringUid);
2633 return false;
2634 }
2635 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2636 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2637 "%.2f, maximum allowed = %.2f)",
2638 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2639 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2640 return false;
2641 }
2642 return true;
2643}
2644
chaviw98318de2021-05-19 16:45:23 -05002645bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002648 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2649 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002650 if (windowHandle == otherHandle) {
2651 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 }
chaviw98318de2021-05-19 16:45:23 -05002653 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002654 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002655 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 return true;
2657 }
2658 }
2659 return false;
2660}
2661
chaviw98318de2021-05-19 16:45:23 -05002662bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002663 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002664 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2665 const WindowInfo* windowInfo = windowHandle->getInfo();
2666 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002667 if (windowHandle == otherHandle) {
2668 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002669 }
chaviw98318de2021-05-19 16:45:23 -05002670 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002671 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002672 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002673 return true;
2674 }
2675 }
2676 return false;
2677}
2678
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002679std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002680 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002681 if (applicationHandle != nullptr) {
2682 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002683 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 } else {
2685 return applicationHandle->getName();
2686 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002687 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002688 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002690 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 }
2692}
2693
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002694void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002695 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002696 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2697 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002698 // Focus or pointer capture changed events are passed to apps, but do not represent user
2699 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002700 return;
2701 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002702 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002703 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002704 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002705 const WindowInfo* info = focusedWindowHandle->getInfo();
2706 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002707 if (DEBUG_DISPATCH_CYCLE) {
2708 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 return;
2711 }
2712 }
2713
2714 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002715 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002716 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002717 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2718 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 return;
2720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002722 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 eventType = USER_ACTIVITY_EVENT_TOUCH;
2724 }
2725 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002727 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002728 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2729 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 return;
2731 }
2732 eventType = USER_ACTIVITY_EVENT_BUTTON;
2733 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002735 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002736 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002737 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002738 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002739 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2740 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002741 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002742 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002743 break;
2744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 }
2746
Prabir Pradhancef936d2021-07-21 16:17:52 +00002747 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2748 REQUIRES(mLock) {
2749 scoped_unlock unlock(mLock);
2750 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2751 };
2752 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753}
2754
2755void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002756 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002757 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002758 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002759 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002761 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002762 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002763 ATRACE_NAME(message.c_str());
2764 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002765 if (DEBUG_DISPATCH_CYCLE) {
2766 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2767 "globalScaleFactor=%f, pointerIds=0x%x %s",
2768 connection->getInputChannelName().c_str(), inputTarget.flags,
2769 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2770 inputTarget.getPointerInfoString().c_str());
2771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
2773 // Skip this event if the connection status is not normal.
2774 // We don't want to enqueue additional outbound events if the connection is broken.
2775 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002776 if (DEBUG_DISPATCH_CYCLE) {
2777 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2778 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 return;
2781 }
2782
2783 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002784 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2785 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2786 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002787 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002789 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002790 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002791 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002792 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 if (!splitMotionEntry) {
2794 return; // split event was dropped
2795 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002796 if (DEBUG_FOCUS) {
2797 ALOGD("channel '%s' ~ Split motion event.",
2798 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002800 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002801 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2802 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 return;
2804 }
2805 }
2806
2807 // Not splitting. Enqueue dispatch entries for the event as is.
2808 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2809}
2810
2811void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002813 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002814 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002815 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002816 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002817 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002818 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002819 ATRACE_NAME(message.c_str());
2820 }
2821
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002822 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823
2824 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002826 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002831 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002833 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002835 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
2838 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002839 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 startDispatchCycleLocked(currentTime, connection);
2841 }
2842}
2843
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002844void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002845 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002846 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002848 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2850 connection->getInputChannelName().c_str(),
2851 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002852 ATRACE_NAME(message.c_str());
2853 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002854 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 if (!(inputTargetFlags & dispatchMode)) {
2856 return;
2857 }
2858 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2859
2860 // This is a new event.
2861 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002862 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002863 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002865 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2866 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002867 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002869 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002870 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002871 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002872 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002873 dispatchEntry->resolvedAction = keyEntry.action;
2874 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002876 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2877 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002878 if (DEBUG_DISPATCH_CYCLE) {
2879 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2880 "event",
2881 connection->getInputChannelName().c_str());
2882 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883 return; // skip the inconsistent event
2884 }
2885 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002888 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002889 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002890 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2891 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2892 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2893 static_cast<int32_t>(IdGenerator::Source::OTHER);
2894 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2896 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2897 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2898 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2899 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2900 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2901 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2902 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2903 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2904 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2905 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002906 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002907 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002908 }
2909 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002910 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2911 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002912 if (DEBUG_DISPATCH_CYCLE) {
2913 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2914 "enter event",
2915 connection->getInputChannelName().c_str());
2916 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002917 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2918 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002922 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2924 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2925 }
2926 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2927 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2931 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002932 if (DEBUG_DISPATCH_CYCLE) {
2933 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2934 "event",
2935 connection->getInputChannelName().c_str());
2936 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002937 return; // skip the inconsistent event
2938 }
2939
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002940 dispatchEntry->resolvedEventId =
2941 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2942 ? mIdGenerator.nextId()
2943 : motionEntry.id;
2944 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2945 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2946 ") to MotionEvent(id=0x%" PRIx32 ").",
2947 motionEntry.id, dispatchEntry->resolvedEventId);
2948 ATRACE_NAME(message.c_str());
2949 }
2950
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002951 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2952 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2953 // Skip reporting pointer down outside focus to the policy.
2954 break;
2955 }
2956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002958 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959
2960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002962 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002963 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2964 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002965 break;
2966 }
Chris Yef59a2f42020-10-16 12:55:26 -07002967 case EventEntry::Type::SENSOR: {
2968 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2969 break;
2970 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002971 case EventEntry::Type::CONFIGURATION_CHANGED:
2972 case EventEntry::Type::DEVICE_RESET: {
2973 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002974 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002975 break;
2976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 }
2978
2979 // Remember that we are waiting for this dispatch to complete.
2980 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002981 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 }
2983
2984 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002985 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002986 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002987}
2988
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002989/**
2990 * This function is purely for debugging. It helps us understand where the user interaction
2991 * was taking place. For example, if user is touching launcher, we will see a log that user
2992 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2993 * We will see both launcher and wallpaper in that list.
2994 * Once the interaction with a particular set of connections starts, no new logs will be printed
2995 * until the set of interacted connections changes.
2996 *
2997 * The following items are skipped, to reduce the logspam:
2998 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2999 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3000 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3001 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3002 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003003 */
3004void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3005 const std::vector<InputTarget>& targets) {
3006 // Skip ACTION_UP events, and all events other than keys and motions
3007 if (entry.type == EventEntry::Type::KEY) {
3008 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3009 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3010 return;
3011 }
3012 } else if (entry.type == EventEntry::Type::MOTION) {
3013 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3014 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3015 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3016 return;
3017 }
3018 } else {
3019 return; // Not a key or a motion
3020 }
3021
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003022 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003023 std::vector<sp<Connection>> newConnections;
3024 for (const InputTarget& target : targets) {
3025 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3026 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3027 continue; // Skip windows that receive ACTION_OUTSIDE
3028 }
3029
3030 sp<IBinder> token = target.inputChannel->getConnectionToken();
3031 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003032 if (connection == nullptr) {
3033 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003034 }
3035 newConnectionTokens.insert(std::move(token));
3036 newConnections.emplace_back(connection);
3037 }
3038 if (newConnectionTokens == mInteractionConnectionTokens) {
3039 return; // no change
3040 }
3041 mInteractionConnectionTokens = newConnectionTokens;
3042
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003043 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003044 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003045 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003046 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003047 std::string message = "Interaction with: " + targetList;
3048 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003049 message += "<none>";
3050 }
3051 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3052}
3053
chaviwfd6d3512019-03-25 13:23:49 -07003054void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003055 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003056 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003057 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3058 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003059 return;
3060 }
3061
Vishnu Nairc519ff72021-01-21 08:23:08 -08003062 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003063 if (focusedToken == token) {
3064 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003065 return;
3066 }
3067
Prabir Pradhancef936d2021-07-21 16:17:52 +00003068 auto command = [this, token]() REQUIRES(mLock) {
3069 scoped_unlock unlock(mLock);
3070 mPolicy->onPointerDownOutsideFocus(token);
3071 };
3072 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073}
3074
3075void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003077 if (ATRACE_ENABLED()) {
3078 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003080 ATRACE_NAME(message.c_str());
3081 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003082 if (DEBUG_DISPATCH_CYCLE) {
3083 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003086 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3087 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003089 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003090 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003091 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092
3093 // Publish the event.
3094 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003095 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3096 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003097 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003098 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3099 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003102 status = connection->inputPublisher
3103 .publishKeyEvent(dispatchEntry->seq,
3104 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3105 keyEntry.source, keyEntry.displayId,
3106 std::move(hmac), dispatchEntry->resolvedAction,
3107 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3108 keyEntry.scanCode, keyEntry.metaState,
3109 keyEntry.repeatCount, keyEntry.downTime,
3110 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 }
3113
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003114 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003115 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003118 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119
chaviw82357092020-01-28 13:13:06 -08003120 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003121 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3123 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003124 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3126 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003127 // Don't apply window scale here since we don't want scale to affect raw
3128 // coordinates. The scale will be sent back to the client and applied
3129 // later when requesting relative coordinates.
3130 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3131 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 }
3133 usingCoords = scaledCoords;
3134 }
3135 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 // We don't want the dispatch target to know.
3137 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003138 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 scaledCoords[i].clear();
3140 }
3141 usingCoords = scaledCoords;
3142 }
3143 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003144
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003145 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146
3147 // Publish the motion event.
3148 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003149 .publishMotionEvent(dispatchEntry->seq,
3150 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003151 motionEntry.deviceId, motionEntry.source,
3152 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003153 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003154 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003156 motionEntry.edgeFlags, motionEntry.metaState,
3157 motionEntry.buttonState,
3158 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003159 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 motionEntry.xPrecision, motionEntry.yPrecision,
3161 motionEntry.xCursorPosition,
3162 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003163 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003164 dispatchEntry->displaySize.x,
3165 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003166 motionEntry.downTime, motionEntry.eventTime,
3167 motionEntry.pointerCount,
3168 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 break;
3170 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003171
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003172 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003173 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003174 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003175 focusEntry.id,
3176 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003177 mInTouchMode);
3178 break;
3179 }
3180
Prabir Pradhan99987712020-11-10 18:43:05 -08003181 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3182 const auto& captureEntry =
3183 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3184 status = connection->inputPublisher
3185 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3186 captureEntry.pointerCaptureEnabled);
3187 break;
3188 }
3189
arthurhungb89ccb02020-12-30 16:19:01 +08003190 case EventEntry::Type::DRAG: {
3191 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3192 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3193 dragEntry.id, dragEntry.x,
3194 dragEntry.y,
3195 dragEntry.isExiting);
3196 break;
3197 }
3198
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003199 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003200 case EventEntry::Type::DEVICE_RESET:
3201 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003202 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003203 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
3207
3208 // Check the result.
3209 if (status) {
3210 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003211 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 "This is unexpected because the wait queue is empty, so the pipe "
3214 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003215 "event to it, status=%s(%d)",
3216 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3217 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3219 } else {
3220 // Pipe is full and we are waiting for the app to finish process some events
3221 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003222 if (DEBUG_DISPATCH_CYCLE) {
3223 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3224 "waiting for the application to catch up",
3225 connection->getInputChannelName().c_str());
3226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
3228 } else {
3229 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003230 "status=%s(%d)",
3231 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3232 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3234 }
3235 return;
3236 }
3237
3238 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003239 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3240 connection->outboundQueue.end(),
3241 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003242 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003243 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003244 if (connection->responsive) {
3245 mAnrTracker.insert(dispatchEntry->timeoutTime,
3246 connection->inputChannel->getConnectionToken());
3247 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003248 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250}
3251
chaviw09c8d2d2020-08-24 15:48:26 -07003252std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3253 size_t size;
3254 switch (event.type) {
3255 case VerifiedInputEvent::Type::KEY: {
3256 size = sizeof(VerifiedKeyEvent);
3257 break;
3258 }
3259 case VerifiedInputEvent::Type::MOTION: {
3260 size = sizeof(VerifiedMotionEvent);
3261 break;
3262 }
3263 }
3264 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3265 return mHmacKeyManager.sign(start, size);
3266}
3267
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003268const std::array<uint8_t, 32> InputDispatcher::getSignature(
3269 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3270 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3271 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3272 // Only sign events up and down events as the purely move events
3273 // are tied to their up/down counterparts so signing would be redundant.
3274 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3275 verifiedEvent.actionMasked = actionMasked;
3276 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003277 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003278 }
3279 return INVALID_HMAC;
3280}
3281
3282const std::array<uint8_t, 32> InputDispatcher::getSignature(
3283 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3284 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3285 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3286 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003287 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003288}
3289
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003292 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003293 if (DEBUG_DISPATCH_CYCLE) {
3294 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3295 connection->getInputChannelName().c_str(), seq, toString(handled));
3296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 if (connection->status == Connection::STATUS_BROKEN ||
3299 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 return;
3301 }
3302
3303 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003304 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3305 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3306 };
3307 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308}
3309
3310void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 const sp<Connection>& connection,
3312 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003313 if (DEBUG_DISPATCH_CYCLE) {
3314 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3315 connection->getInputChannelName().c_str(), toString(notify));
3316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
3318 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003319 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003320 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003321 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003322 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323
3324 // The connection appears to be unrecoverably broken.
3325 // Ignore already broken or zombie connections.
3326 if (connection->status == Connection::STATUS_NORMAL) {
3327 connection->status = Connection::STATUS_BROKEN;
3328
3329 if (notify) {
3330 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003331 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3332 connection->getInputChannelName().c_str());
3333
3334 auto command = [this, connection]() REQUIRES(mLock) {
3335 if (connection->status == Connection::STATUS_ZOMBIE) return;
3336 scoped_unlock unlock(mLock);
3337 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3338 };
3339 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
3341 }
3342}
3343
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003344void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3345 while (!queue.empty()) {
3346 DispatchEntry* dispatchEntry = queue.front();
3347 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003348 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349 }
3350}
3351
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003352void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003354 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
3356 delete dispatchEntry;
3357}
3358
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003359int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3360 std::scoped_lock _l(mLock);
3361 sp<Connection> connection = getConnectionLocked(connectionToken);
3362 if (connection == nullptr) {
3363 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3364 connectionToken.get(), events);
3365 return 0; // remove the callback
3366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003368 bool notify;
3369 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3370 if (!(events & ALOOPER_EVENT_INPUT)) {
3371 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3372 "events=0x%x",
3373 connection->getInputChannelName().c_str(), events);
3374 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
3376
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003377 nsecs_t currentTime = now();
3378 bool gotOne = false;
3379 status_t status = OK;
3380 for (;;) {
3381 Result<InputPublisher::ConsumerResponse> result =
3382 connection->inputPublisher.receiveConsumerResponse();
3383 if (!result.ok()) {
3384 status = result.error().code();
3385 break;
3386 }
3387
3388 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3389 const InputPublisher::Finished& finish =
3390 std::get<InputPublisher::Finished>(*result);
3391 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3392 finish.consumeTime);
3393 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003394 if (shouldReportMetricsForConnection(*connection)) {
3395 const InputPublisher::Timeline& timeline =
3396 std::get<InputPublisher::Timeline>(*result);
3397 mLatencyTracker
3398 .trackGraphicsLatency(timeline.inputEventId,
3399 connection->inputChannel->getConnectionToken(),
3400 std::move(timeline.graphicsTimeline));
3401 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003402 }
3403 gotOne = true;
3404 }
3405 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003406 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003407 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 return 1;
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003412 notify = status != DEAD_OBJECT || !connection->monitor;
3413 if (notify) {
3414 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3415 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3416 status);
3417 }
3418 } else {
3419 // Monitor channels are never explicitly unregistered.
3420 // We do it automatically when the remote endpoint is closed so don't warn about them.
3421 const bool stillHaveWindowHandle =
3422 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3423 notify = !connection->monitor && stillHaveWindowHandle;
3424 if (notify) {
3425 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3426 connection->getInputChannelName().c_str(), events);
3427 }
3428 }
3429
3430 // Remove the channel.
3431 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3432 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433}
3434
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003437 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003438 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 }
3440}
3441
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003442void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003443 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003444 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3445 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3446}
3447
3448void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3449 const CancelationOptions& options,
3450 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3451 for (const auto& it : monitorsByDisplay) {
3452 const std::vector<Monitor>& monitors = it.second;
3453 for (const Monitor& monitor : monitors) {
3454 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003455 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003456 }
3457}
3458
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003460 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003461 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003462 if (connection == nullptr) {
3463 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003465
3466 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467}
3468
3469void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3470 const sp<Connection>& connection, const CancelationOptions& options) {
3471 if (connection->status == Connection::STATUS_BROKEN) {
3472 return;
3473 }
3474
3475 nsecs_t currentTime = now();
3476
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003477 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003478 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003480 if (cancelationEvents.empty()) {
3481 return;
3482 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003483 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3484 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3485 "with reality: %s, mode=%d.",
3486 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3487 options.mode);
3488 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003489
3490 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003491 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003492 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3493 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003494 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003495 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003496 target.globalScaleFactor = windowInfo->globalScaleFactor;
3497 }
3498 target.inputChannel = connection->inputChannel;
3499 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3500
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003501 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003502 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003503 switch (cancelationEventEntry->type) {
3504 case EventEntry::Type::KEY: {
3505 logOutboundKeyDetails("cancel - ",
3506 static_cast<const KeyEntry&>(*cancelationEventEntry));
3507 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003509 case EventEntry::Type::MOTION: {
3510 logOutboundMotionDetails("cancel - ",
3511 static_cast<const MotionEntry&>(*cancelationEventEntry));
3512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003514 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003515 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3516 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003517 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003518 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003519 break;
3520 }
3521 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003522 case EventEntry::Type::DEVICE_RESET:
3523 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003524 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003525 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003526 break;
3527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003530 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3531 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003533
3534 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535}
3536
Svet Ganov5d3bc372020-01-26 23:11:07 -08003537void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3538 const sp<Connection>& connection) {
3539 if (connection->status == Connection::STATUS_BROKEN) {
3540 return;
3541 }
3542
3543 nsecs_t currentTime = now();
3544
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003545 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003546 connection->inputState.synthesizePointerDownEvents(currentTime);
3547
3548 if (downEvents.empty()) {
3549 return;
3550 }
3551
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003552 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003553 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3554 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003555 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003556
3557 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003558 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003559 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3560 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003561 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003562 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003563 target.globalScaleFactor = windowInfo->globalScaleFactor;
3564 }
3565 target.inputChannel = connection->inputChannel;
3566 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003568 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569 switch (downEventEntry->type) {
3570 case EventEntry::Type::MOTION: {
3571 logOutboundMotionDetails("down - ",
3572 static_cast<const MotionEntry&>(*downEventEntry));
3573 break;
3574 }
3575
3576 case EventEntry::Type::KEY:
3577 case EventEntry::Type::FOCUS:
3578 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003579 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003580 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003581 case EventEntry::Type::SENSOR:
3582 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003583 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003584 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003585 break;
3586 }
3587 }
3588
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3590 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003591 }
3592
3593 startDispatchCycleLocked(currentTime, connection);
3594}
3595
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003596std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3597 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 ALOG_ASSERT(pointerIds.value != 0);
3599
3600 uint32_t splitPointerIndexMap[MAX_POINTERS];
3601 PointerProperties splitPointerProperties[MAX_POINTERS];
3602 PointerCoords splitPointerCoords[MAX_POINTERS];
3603
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003604 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 uint32_t splitPointerCount = 0;
3606
3607 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003608 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003610 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 uint32_t pointerId = uint32_t(pointerProperties.id);
3612 if (pointerIds.hasBit(pointerId)) {
3613 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3614 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3615 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003616 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 splitPointerCount += 1;
3618 }
3619 }
3620
3621 if (splitPointerCount != pointerIds.count()) {
3622 // This is bad. We are missing some of the pointers that we expected to deliver.
3623 // Most likely this indicates that we received an ACTION_MOVE events that has
3624 // different pointer ids than we expected based on the previous ACTION_DOWN
3625 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3626 // in this way.
3627 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003628 "we expected there to be %d pointers. This probably means we received "
3629 "a broken sequence of pointer ids from the input device.",
3630 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003631 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
3633
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003634 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003636 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3637 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3639 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003640 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 uint32_t pointerId = uint32_t(pointerProperties.id);
3642 if (pointerIds.hasBit(pointerId)) {
3643 if (pointerIds.count() == 1) {
3644 // The first/last pointer went down/up.
3645 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003646 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003647 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3648 ? AMOTION_EVENT_ACTION_CANCEL
3649 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 } else {
3651 // A secondary pointer went down/up.
3652 uint32_t splitPointerIndex = 0;
3653 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3654 splitPointerIndex += 1;
3655 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003656 action = maskedAction |
3657 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 }
3659 } else {
3660 // An unrelated pointer changed.
3661 action = AMOTION_EVENT_ACTION_MOVE;
3662 }
3663 }
3664
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003665 int32_t newId = mIdGenerator.nextId();
3666 if (ATRACE_ENABLED()) {
3667 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3668 ") to MotionEvent(id=0x%" PRIx32 ").",
3669 originalMotionEntry.id, newId);
3670 ATRACE_NAME(message.c_str());
3671 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003672 std::unique_ptr<MotionEntry> splitMotionEntry =
3673 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3674 originalMotionEntry.deviceId, originalMotionEntry.source,
3675 originalMotionEntry.displayId,
3676 originalMotionEntry.policyFlags, action,
3677 originalMotionEntry.actionButton,
3678 originalMotionEntry.flags, originalMotionEntry.metaState,
3679 originalMotionEntry.buttonState,
3680 originalMotionEntry.classification,
3681 originalMotionEntry.edgeFlags,
3682 originalMotionEntry.xPrecision,
3683 originalMotionEntry.yPrecision,
3684 originalMotionEntry.xCursorPosition,
3685 originalMotionEntry.yCursorPosition,
3686 originalMotionEntry.downTime, splitPointerCount,
3687 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003689 if (originalMotionEntry.injectionState) {
3690 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 splitMotionEntry->injectionState->refCount += 1;
3692 }
3693
3694 return splitMotionEntry;
3695}
3696
3697void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003698 if (DEBUG_INBOUND_EVENT_DETAILS) {
3699 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701
3702 bool needWake;
3703 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003704 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003706 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3707 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3708 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 } // release lock
3710
3711 if (needWake) {
3712 mLooper->wake();
3713 }
3714}
3715
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003716/**
3717 * If one of the meta shortcuts is detected, process them here:
3718 * Meta + Backspace -> generate BACK
3719 * Meta + Enter -> generate HOME
3720 * This will potentially overwrite keyCode and metaState.
3721 */
3722void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003723 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003724 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3725 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3726 if (keyCode == AKEYCODE_DEL) {
3727 newKeyCode = AKEYCODE_BACK;
3728 } else if (keyCode == AKEYCODE_ENTER) {
3729 newKeyCode = AKEYCODE_HOME;
3730 }
3731 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003732 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003733 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003734 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003735 keyCode = newKeyCode;
3736 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3737 }
3738 } else if (action == AKEY_EVENT_ACTION_UP) {
3739 // In order to maintain a consistent stream of up and down events, check to see if the key
3740 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3741 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003742 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003743 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003744 auto replacementIt = mReplacedKeys.find(replacement);
3745 if (replacementIt != mReplacedKeys.end()) {
3746 keyCode = replacementIt->second;
3747 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003748 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3749 }
3750 }
3751}
3752
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003754 if (DEBUG_INBOUND_EVENT_DETAILS) {
3755 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3756 "policyFlags=0x%x, action=0x%x, "
3757 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3758 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3759 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3760 args->downTime);
3761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 if (!validateKeyEvent(args->action)) {
3763 return;
3764 }
3765
3766 uint32_t policyFlags = args->policyFlags;
3767 int32_t flags = args->flags;
3768 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003769 // InputDispatcher tracks and generates key repeats on behalf of
3770 // whatever notifies it, so repeatCount should always be set to 0
3771 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3773 policyFlags |= POLICY_FLAG_VIRTUAL;
3774 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 if (policyFlags & POLICY_FLAG_FUNCTION) {
3777 metaState |= AMETA_FUNCTION_ON;
3778 }
3779
3780 policyFlags |= POLICY_FLAG_TRUSTED;
3781
Michael Wright78f24442014-08-06 15:55:28 -07003782 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003783 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003784
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003786 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003787 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3788 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
Michael Wright2b3c3302018-03-02 17:19:13 +00003790 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003792 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3793 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003794 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 bool needWake;
3798 { // acquire lock
3799 mLock.lock();
3800
3801 if (shouldSendKeyToInputFilterLocked(args)) {
3802 mLock.unlock();
3803
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003804 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3806 return; // event was consumed by the filter
3807 }
3808
3809 mLock.lock();
3810 }
3811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003812 std::unique_ptr<KeyEntry> newEntry =
3813 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3814 args->displayId, policyFlags, args->action, flags,
3815 keyCode, args->scanCode, metaState, repeatCount,
3816 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003818 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 mLock.unlock();
3820 } // release lock
3821
3822 if (needWake) {
3823 mLooper->wake();
3824 }
3825}
3826
3827bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3828 return mInputFilterEnabled;
3829}
3830
3831void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003832 if (DEBUG_INBOUND_EVENT_DETAILS) {
3833 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3834 "displayId=%" PRId32 ", policyFlags=0x%x, "
3835 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3836 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3837 "yCursorPosition=%f, downTime=%" PRId64,
3838 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3839 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3840 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3841 args->xCursorPosition, args->yCursorPosition, args->downTime);
3842 for (uint32_t i = 0; i < args->pointerCount; i++) {
3843 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3844 "x=%f, y=%f, pressure=%f, size=%f, "
3845 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3846 "orientation=%f",
3847 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3848 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3849 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3850 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3851 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3852 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3853 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3854 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3855 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3856 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003859 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3860 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 return;
3862 }
3863
3864 uint32_t policyFlags = args->policyFlags;
3865 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003866
3867 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003868 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003869 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3870 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003871 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
3874 bool needWake;
3875 { // acquire lock
3876 mLock.lock();
3877
3878 if (shouldSendMotionToInputFilterLocked(args)) {
3879 mLock.unlock();
3880
3881 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003882 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003883 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3884 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003885 args->metaState, args->buttonState, args->classification, transform,
3886 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003887 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3888 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3889 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890
3891 policyFlags |= POLICY_FLAG_FILTERED;
3892 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3893 return; // event was consumed by the filter
3894 }
3895
3896 mLock.lock();
3897 }
3898
3899 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003900 std::unique_ptr<MotionEntry> newEntry =
3901 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3902 args->source, args->displayId, policyFlags,
3903 args->action, args->actionButton, args->flags,
3904 args->metaState, args->buttonState,
3905 args->classification, args->edgeFlags,
3906 args->xPrecision, args->yPrecision,
3907 args->xCursorPosition, args->yCursorPosition,
3908 args->downTime, args->pointerCount,
3909 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003911 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3912 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3913 !mInputFilterEnabled) {
3914 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3915 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3916 }
3917
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003918 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 mLock.unlock();
3920 } // release lock
3921
3922 if (needWake) {
3923 mLooper->wake();
3924 }
3925}
3926
Chris Yef59a2f42020-10-16 12:55:26 -07003927void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003928 if (DEBUG_INBOUND_EVENT_DETAILS) {
3929 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3930 " sensorType=%s",
3931 args->id, args->eventTime, args->deviceId, args->source,
3932 NamedEnum::string(args->sensorType).c_str());
3933 }
Chris Yef59a2f42020-10-16 12:55:26 -07003934
3935 bool needWake;
3936 { // acquire lock
3937 mLock.lock();
3938
3939 // Just enqueue a new sensor event.
3940 std::unique_ptr<SensorEntry> newEntry =
3941 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3942 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3943 args->sensorType, args->accuracy,
3944 args->accuracyChanged, args->values);
3945
3946 needWake = enqueueInboundEventLocked(std::move(newEntry));
3947 mLock.unlock();
3948 } // release lock
3949
3950 if (needWake) {
3951 mLooper->wake();
3952 }
3953}
3954
Chris Yefb552902021-02-03 17:18:37 -08003955void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003956 if (DEBUG_INBOUND_EVENT_DETAILS) {
3957 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3958 args->deviceId, args->isOn);
3959 }
Chris Yefb552902021-02-03 17:18:37 -08003960 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3961}
3962
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003964 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965}
3966
3967void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003968 if (DEBUG_INBOUND_EVENT_DETAILS) {
3969 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
3970 "switchMask=0x%08x",
3971 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
3972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973
3974 uint32_t policyFlags = args->policyFlags;
3975 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003976 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977}
3978
3979void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003980 if (DEBUG_INBOUND_EVENT_DETAILS) {
3981 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3982 args->deviceId);
3983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984
3985 bool needWake;
3986 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003989 std::unique_ptr<DeviceResetEntry> newEntry =
3990 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3991 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 } // release lock
3993
3994 if (needWake) {
3995 mLooper->wake();
3996 }
3997}
3998
Prabir Pradhan7e186182020-11-10 13:56:45 -08003999void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004000 if (DEBUG_INBOUND_EVENT_DETAILS) {
4001 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
4002 args->enabled ? "true" : "false");
4003 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004004
Prabir Pradhan99987712020-11-10 18:43:05 -08004005 bool needWake;
4006 { // acquire lock
4007 std::scoped_lock _l(mLock);
4008 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4009 args->enabled);
4010 needWake = enqueueInboundEventLocked(std::move(entry));
4011 } // release lock
4012
4013 if (needWake) {
4014 mLooper->wake();
4015 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004016}
4017
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004018InputEventInjectionResult InputDispatcher::injectInputEvent(
4019 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4020 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 if (DEBUG_INBOUND_EVENT_DETAILS) {
4022 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4023 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4024 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4025 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004026 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027
4028 policyFlags |= POLICY_FLAG_INJECTED;
4029 if (hasInjectionPermission(injectorPid, injectorUid)) {
4030 policyFlags |= POLICY_FLAG_TRUSTED;
4031 }
4032
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004033 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004034 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4035 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4036 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4037 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4038 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004039 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004040 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004041 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004042 }
4043
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004044 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004047 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4048 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004050 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004053 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004054 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4055 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4056 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004057 int32_t keyCode = incomingKey.getKeyCode();
4058 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004059 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004061 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004062 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004063 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4064 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4065 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4068 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004069 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004070
4071 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4072 android::base::Timer t;
4073 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4074 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4075 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4076 std::to_string(t.duration().count()).c_str());
4077 }
4078 }
4079
4080 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081 std::unique_ptr<KeyEntry> injectedEntry =
4082 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004083 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084 incomingKey.getDisplayId(), policyFlags, action,
4085 flags, keyCode, incomingKey.getScanCode(), metaState,
4086 incomingKey.getRepeatCount(),
4087 incomingKey.getDownTime());
4088 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 }
4091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004093 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4094 int32_t action = motionEvent.getAction();
4095 size_t pointerCount = motionEvent.getPointerCount();
4096 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4097 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004098 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004099 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004100 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004101 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102 }
4103
4104 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004105 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 android::base::Timer t;
4107 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4108 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4109 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4110 std::to_string(t.duration().count()).c_str());
4111 }
4112 }
4113
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004114 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4115 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4116 }
4117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004119 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4120 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004121 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004122 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4123 resolvedDeviceId, motionEvent.getSource(),
4124 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004125 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004126 motionEvent.getButtonState(),
4127 motionEvent.getClassification(),
4128 motionEvent.getEdgeFlags(),
4129 motionEvent.getXPrecision(),
4130 motionEvent.getYPrecision(),
4131 motionEvent.getRawXCursorPosition(),
4132 motionEvent.getRawYCursorPosition(),
4133 motionEvent.getDownTime(), uint32_t(pointerCount),
4134 pointerProperties, samplePointerCoords,
4135 motionEvent.getXOffset(),
4136 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004137 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004139 sampleEventTimes += 1;
4140 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004141 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4143 resolvedDeviceId, motionEvent.getSource(),
4144 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004145 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004146 motionEvent.getMetaState(),
4147 motionEvent.getButtonState(),
4148 motionEvent.getClassification(),
4149 motionEvent.getEdgeFlags(),
4150 motionEvent.getXPrecision(),
4151 motionEvent.getYPrecision(),
4152 motionEvent.getRawXCursorPosition(),
4153 motionEvent.getRawYCursorPosition(),
4154 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004155 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004156 samplePointerCoords, motionEvent.getXOffset(),
4157 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004158 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159 }
4160 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004164 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004165 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 }
4167
4168 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004169 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 injectionState->injectionIsAsync = true;
4171 }
4172
4173 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004174 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
4176 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004177 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004178 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004179 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181
4182 mLock.unlock();
4183
4184 if (needWake) {
4185 mLooper->wake();
4186 }
4187
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004188 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004190 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004192 if (syncMode == InputEventInjectionSync::NONE) {
4193 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 } else {
4195 for (;;) {
4196 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004197 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 break;
4199 }
4200
4201 nsecs_t remainingTimeout = endTime - now();
4202 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004203 if (DEBUG_INJECTION) {
4204 ALOGD("injectInputEvent - Timed out waiting for injection result "
4205 "to become available.");
4206 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004207 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 break;
4209 }
4210
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004211 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 }
4213
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004214 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4215 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004217 if (DEBUG_INJECTION) {
4218 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4219 injectionState->pendingForegroundDispatches);
4220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 nsecs_t remainingTimeout = endTime - now();
4222 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004223 if (DEBUG_INJECTION) {
4224 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4225 "dispatches to finish.");
4226 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004227 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 break;
4229 }
4230
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004231 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 }
4233 }
4234 }
4235
4236 injectionState->release();
4237 } // release lock
4238
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004239 if (DEBUG_INJECTION) {
4240 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4241 injectionResult, injectorPid, injectorUid);
4242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243
4244 return injectionResult;
4245}
4246
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004247std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004248 std::array<uint8_t, 32> calculatedHmac;
4249 std::unique_ptr<VerifiedInputEvent> result;
4250 switch (event.getType()) {
4251 case AINPUT_EVENT_TYPE_KEY: {
4252 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4253 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4254 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004255 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004256 break;
4257 }
4258 case AINPUT_EVENT_TYPE_MOTION: {
4259 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4260 VerifiedMotionEvent verifiedMotionEvent =
4261 verifiedMotionEventFromMotionEvent(motionEvent);
4262 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004263 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004264 break;
4265 }
4266 default: {
4267 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4268 return nullptr;
4269 }
4270 }
4271 if (calculatedHmac == INVALID_HMAC) {
4272 return nullptr;
4273 }
4274 if (calculatedHmac != event.getHmac()) {
4275 return nullptr;
4276 }
4277 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004278}
4279
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 return injectorUid == 0 ||
4282 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283}
4284
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004285void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004289 if (DEBUG_INJECTION) {
4290 ALOGD("Setting input event injection result to %d. "
4291 "injectorPid=%d, injectorUid=%d",
4292 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 // Log the outcome since the injector did not wait for the injection result.
4297 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 ALOGV("Asynchronous input event injection succeeded.");
4300 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004302 ALOGW("Asynchronous input event injection failed.");
4303 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004304 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305 ALOGW("Asynchronous input event injection permission denied.");
4306 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 ALOGW("Asynchronous input event injection timed out.");
4309 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 case InputEventInjectionResult::PENDING:
4311 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4312 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314 }
4315
4316 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004317 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319}
4320
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004321void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4322 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 if (injectionState) {
4324 injectionState->pendingForegroundDispatches += 1;
4325 }
4326}
4327
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004328void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4329 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 if (injectionState) {
4331 injectionState->pendingForegroundDispatches -= 1;
4332
4333 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004334 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 }
4336 }
4337}
4338
chaviw98318de2021-05-19 16:45:23 -05004339const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004340 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004341 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004342 auto it = mWindowHandlesByDisplay.find(displayId);
4343 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004344}
4345
chaviw98318de2021-05-19 16:45:23 -05004346sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004347 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004348 if (windowHandleToken == nullptr) {
4349 return nullptr;
4350 }
4351
Arthur Hungb92218b2018-08-14 12:00:21 +08004352 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004353 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4354 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004355 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004356 return windowHandle;
4357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 }
4359 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004360 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361}
4362
chaviw98318de2021-05-19 16:45:23 -05004363sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4364 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004365 if (windowHandleToken == nullptr) {
4366 return nullptr;
4367 }
4368
chaviw98318de2021-05-19 16:45:23 -05004369 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004370 if (windowHandle->getToken() == windowHandleToken) {
4371 return windowHandle;
4372 }
4373 }
4374 return nullptr;
4375}
4376
chaviw98318de2021-05-19 16:45:23 -05004377sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4378 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004379 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004380 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4381 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004382 if (handle->getId() == windowHandle->getId() &&
4383 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004384 if (windowHandle->getInfo()->displayId != it.first) {
4385 ALOGE("Found window %s in display %" PRId32
4386 ", but it should belong to display %" PRId32,
4387 windowHandle->getName().c_str(), it.first,
4388 windowHandle->getInfo()->displayId);
4389 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004390 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 }
4393 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004394 return nullptr;
4395}
4396
chaviw98318de2021-05-19 16:45:23 -05004397sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004398 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4399 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400}
4401
chaviw98318de2021-05-19 16:45:23 -05004402bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004403 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4404 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004405 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004406 if (connection != nullptr && noInputChannel) {
4407 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4408 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4409 return false;
4410 }
4411
4412 if (connection == nullptr) {
4413 if (!noInputChannel) {
4414 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4415 }
4416 return false;
4417 }
4418 if (!connection->responsive) {
4419 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4420 return false;
4421 }
4422 return true;
4423}
4424
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004425std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4426 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004427 auto connectionIt = mConnectionsByToken.find(token);
4428 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004429 return nullptr;
4430 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004431 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004432}
4433
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004434void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004435 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4436 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004437 // Remove all handles on a display if there are no windows left.
4438 mWindowHandlesByDisplay.erase(displayId);
4439 return;
4440 }
4441
4442 // Since we compare the pointer of input window handles across window updates, we need
4443 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004444 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4445 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4446 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004447 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004448 }
4449
chaviw98318de2021-05-19 16:45:23 -05004450 std::vector<sp<WindowInfoHandle>> newHandles;
4451 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004452 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004453 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004454 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004455 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4456 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4457 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004458 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004459 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004460 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004461 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004462 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004463 }
4464
4465 if (info->displayId != displayId) {
4466 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4467 handle->getName().c_str(), displayId, info->displayId);
4468 continue;
4469 }
4470
Robert Carredd13602020-04-13 17:24:34 -07004471 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4472 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004473 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004474 oldHandle->updateFrom(handle);
4475 newHandles.push_back(oldHandle);
4476 } else {
4477 newHandles.push_back(handle);
4478 }
4479 }
4480
4481 // Insert or replace
4482 mWindowHandlesByDisplay[displayId] = newHandles;
4483}
4484
Arthur Hung72d8dc32020-03-28 00:48:39 +00004485void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004486 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004487 { // acquire lock
4488 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004489 for (const auto& [displayId, handles] : handlesPerDisplay) {
4490 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004491 }
4492 }
4493 // Wake up poll loop since it may need to make new input dispatching choices.
4494 mLooper->wake();
4495}
4496
Arthur Hungb92218b2018-08-14 12:00:21 +08004497/**
4498 * Called from InputManagerService, update window handle list by displayId that can receive input.
4499 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4500 * If set an empty list, remove all handles from the specific display.
4501 * For focused handle, check if need to change and send a cancel event to previous one.
4502 * For removed handle, check if need to send a cancel event if already in touch.
4503 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004504void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004505 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004506 if (DEBUG_FOCUS) {
4507 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004508 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004509 windowList += iwh->getName() + " ";
4510 }
4511 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004514 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004515 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004516 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004517 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004518 if (noInputWindow && window->getToken() != nullptr) {
4519 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4520 window->getName().c_str());
4521 window->releaseChannel();
4522 }
4523 }
4524
Arthur Hung72d8dc32020-03-28 00:48:39 +00004525 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004526 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004528 // Save the old windows' orientation by ID before it gets updated.
4529 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004530 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004531 oldWindowOrientations.emplace(handle->getId(),
4532 handle->getInfo()->transform.getOrientation());
4533 }
4534
chaviw98318de2021-05-19 16:45:23 -05004535 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004536
chaviw98318de2021-05-19 16:45:23 -05004537 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004538 if (mLastHoverWindowHandle &&
4539 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4540 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004541 mLastHoverWindowHandle = nullptr;
4542 }
4543
Vishnu Nairc519ff72021-01-21 08:23:08 -08004544 std::optional<FocusResolver::FocusChanges> changes =
4545 mFocusResolver.setInputWindows(displayId, windowHandles);
4546 if (changes) {
4547 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004550 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4551 mTouchStatesByDisplay.find(displayId);
4552 if (stateIt != mTouchStatesByDisplay.end()) {
4553 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004554 for (size_t i = 0; i < state.windows.size();) {
4555 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004556 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004557 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004558 ALOGD("Touched window was removed: %s in display %" PRId32,
4559 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004560 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004561 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004562 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4563 if (touchedInputChannel != nullptr) {
4564 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4565 "touched window was removed");
4566 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004568 state.windows.erase(state.windows.begin() + i);
4569 } else {
4570 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 }
4572 }
arthurhungb89ccb02020-12-30 16:19:01 +08004573
arthurhung6d4bed92021-03-17 11:59:33 +08004574 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004575 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004576 if (mDragState &&
4577 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004578 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004579 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004580 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004581 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004582
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004583 if (isPerWindowInputRotationEnabled()) {
4584 // Determine if the orientation of any of the input windows have changed, and cancel all
4585 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004586 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4587 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004588 if (newWindowHandle != nullptr &&
4589 newWindowHandle->getInfo()->transform.getOrientation() !=
4590 oldWindowOrientations[oldWindowHandle->getId()]) {
4591 std::shared_ptr<InputChannel> inputChannel =
4592 getInputChannelLocked(newWindowHandle->getToken());
4593 if (inputChannel != nullptr) {
4594 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4595 "touched window's orientation changed");
4596 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4597 }
4598 }
4599 }
4600 }
4601
Arthur Hung72d8dc32020-03-28 00:48:39 +00004602 // Release information for windows that are no longer present.
4603 // This ensures that unused input channels are released promptly.
4604 // Otherwise, they might stick around until the window handle is destroyed
4605 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004606 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004607 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004608 if (DEBUG_FOCUS) {
4609 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004610 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004611 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004612 // To avoid making too many calls into the compat framework, only
4613 // check for window flags when windows are going away.
4614 // TODO(b/157929241) : delete this. This is only needed temporarily
4615 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004616 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004617 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4618 oldWindowHandle->getName().c_str());
4619 if (mCompatService != nullptr) {
4620 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4621 oldWindowHandle->getInfo()->ownerUid);
4622 }
4623 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004624 }
chaviw291d88a2019-02-14 10:33:58 -08004625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626}
4627
4628void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004629 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004630 if (DEBUG_FOCUS) {
4631 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4632 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4633 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004634 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004635 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004636 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 } // release lock
4638
4639 // Wake up poll loop since it may need to make new input dispatching choices.
4640 mLooper->wake();
4641}
4642
Vishnu Nair599f1412021-06-21 10:39:58 -07004643void InputDispatcher::setFocusedApplicationLocked(
4644 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4645 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4646 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4647
4648 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4649 return; // This application is already focused. No need to wake up or change anything.
4650 }
4651
4652 // Set the new application handle.
4653 if (inputApplicationHandle != nullptr) {
4654 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4655 } else {
4656 mFocusedApplicationHandlesByDisplay.erase(displayId);
4657 }
4658
4659 // No matter what the old focused application was, stop waiting on it because it is
4660 // no longer focused.
4661 resetNoFocusedWindowTimeoutLocked();
4662}
4663
Tiger Huang721e26f2018-07-24 22:26:19 +08004664/**
4665 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4666 * the display not specified.
4667 *
4668 * We track any unreleased events for each window. If a window loses the ability to receive the
4669 * released event, we will send a cancel event to it. So when the focused display is changed, we
4670 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4671 * display. The display-specified events won't be affected.
4672 */
4673void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004674 if (DEBUG_FOCUS) {
4675 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4676 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004677 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004678 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004679
4680 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004681 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004682 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004683 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004684 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004685 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004686 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004687 CancelationOptions
4688 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4689 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004690 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004691 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4692 }
4693 }
4694 mFocusedDisplayId = displayId;
4695
Chris Ye3c2d6f52020-08-09 10:39:48 -07004696 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004697 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004698 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004699
Vishnu Nairad321cd2020-08-20 16:40:21 -07004700 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004701 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004702 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004703 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004704 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004705 }
4706 }
4707 }
4708
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004709 if (DEBUG_FOCUS) {
4710 logDispatchStateLocked();
4711 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004712 } // release lock
4713
4714 // Wake up poll loop since it may need to make new input dispatching choices.
4715 mLooper->wake();
4716}
4717
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004719 if (DEBUG_FOCUS) {
4720 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722
4723 bool changed;
4724 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004725 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4728 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 }
4731
4732 if (mDispatchEnabled && !enabled) {
4733 resetAndDropEverythingLocked("dispatcher is being disabled");
4734 }
4735
4736 mDispatchEnabled = enabled;
4737 mDispatchFrozen = frozen;
4738 changed = true;
4739 } else {
4740 changed = false;
4741 }
4742
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004743 if (DEBUG_FOCUS) {
4744 logDispatchStateLocked();
4745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 } // release lock
4747
4748 if (changed) {
4749 // Wake up poll loop since it may need to make new input dispatching choices.
4750 mLooper->wake();
4751 }
4752}
4753
4754void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004755 if (DEBUG_FOCUS) {
4756 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
4759 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004760 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761
4762 if (mInputFilterEnabled == enabled) {
4763 return;
4764 }
4765
4766 mInputFilterEnabled = enabled;
4767 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4768 } // release lock
4769
4770 // Wake up poll loop since there might be work to do to drop everything.
4771 mLooper->wake();
4772}
4773
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004774void InputDispatcher::setInTouchMode(bool inTouchMode) {
4775 std::scoped_lock lock(mLock);
4776 mInTouchMode = inTouchMode;
4777}
4778
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004779void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4780 if (opacity < 0 || opacity > 1) {
4781 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4782 return;
4783 }
4784
4785 std::scoped_lock lock(mLock);
4786 mMaximumObscuringOpacityForTouch = opacity;
4787}
4788
4789void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4790 std::scoped_lock lock(mLock);
4791 mBlockUntrustedTouchesMode = mode;
4792}
4793
arthurhungb89ccb02020-12-30 16:19:01 +08004794bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4795 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004796 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004797 if (DEBUG_FOCUS) {
4798 ALOGD("Trivial transfer to same window.");
4799 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004800 return true;
4801 }
4802
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004804 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805
chaviw98318de2021-05-19 16:45:23 -05004806 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4807 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004808 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004809 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 return false;
4811 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004812 if (DEBUG_FOCUS) {
4813 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4814 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004817 if (DEBUG_FOCUS) {
4818 ALOGD("Cannot transfer focus because windows are on different displays.");
4819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 return false;
4821 }
4822
4823 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004824 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4825 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004826 for (size_t i = 0; i < state.windows.size(); i++) {
4827 const TouchedWindow& touchedWindow = state.windows[i];
4828 if (touchedWindow.windowHandle == fromWindowHandle) {
4829 int32_t oldTargetFlags = touchedWindow.targetFlags;
4830 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004832 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004834 int32_t newTargetFlags = oldTargetFlags &
4835 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4836 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004837 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838
arthurhungb89ccb02020-12-30 16:19:01 +08004839 // Store the dragging window.
4840 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004841 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004842 }
4843
Jeff Brownf086ddb2014-02-11 14:28:48 -08004844 found = true;
4845 goto Found;
4846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
4848 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004851 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004852 if (DEBUG_FOCUS) {
4853 ALOGD("Focus transfer failed because from window did not have focus.");
4854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 return false;
4856 }
4857
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004858 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4859 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004860 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004861 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862 CancelationOptions
4863 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4864 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004866 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004869 if (DEBUG_FOCUS) {
4870 logDispatchStateLocked();
4871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 } // release lock
4873
4874 // Wake up poll loop since it may need to make new input dispatching choices.
4875 mLooper->wake();
4876 return true;
4877}
4878
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004879// Binder call
4880bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4881 sp<IBinder> fromToken;
4882 { // acquire lock
4883 std::scoped_lock _l(mLock);
4884
chaviw98318de2021-05-19 16:45:23 -05004885 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004886 if (toWindowHandle == nullptr) {
4887 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4888 return false;
4889 }
4890
4891 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4892
4893 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4894 if (touchStateIt == mTouchStatesByDisplay.end()) {
4895 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4896 displayId);
4897 return false;
4898 }
4899
4900 TouchState& state = touchStateIt->second;
4901 if (state.windows.size() != 1) {
4902 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4903 state.windows.size());
4904 return false;
4905 }
4906 const TouchedWindow& touchedWindow = state.windows[0];
4907 fromToken = touchedWindow.windowHandle->getToken();
4908 } // release lock
4909
4910 return transferTouchFocus(fromToken, destChannelToken);
4911}
4912
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004914 if (DEBUG_FOCUS) {
4915 ALOGD("Resetting and dropping all events (%s).", reason);
4916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917
4918 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4919 synthesizeCancelationEventsForAllConnectionsLocked(options);
4920
4921 resetKeyRepeatLocked();
4922 releasePendingEventLocked();
4923 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004926 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004927 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004929 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930}
4931
4932void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004933 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 dumpDispatchStateLocked(dump);
4935
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004936 std::istringstream stream(dump);
4937 std::string line;
4938
4939 while (std::getline(stream, line, '\n')) {
4940 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 }
4942}
4943
Prabir Pradhan99987712020-11-10 18:43:05 -08004944std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4945 std::string dump;
4946
4947 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4948 toString(mFocusedWindowRequestedPointerCapture));
4949
4950 std::string windowName = "None";
4951 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05004952 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08004953 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4954 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4955 : "token has capture without window";
4956 }
4957 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4958
4959 return dump;
4960}
4961
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004962void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004963 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4964 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4965 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004966 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967
Tiger Huang721e26f2018-07-24 22:26:19 +08004968 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4969 dump += StringPrintf(INDENT "FocusedApplications:\n");
4970 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4971 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004972 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004973 const std::chrono::duration timeout =
4974 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004975 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004976 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004977 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004980 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004982
Vishnu Nairc519ff72021-01-21 08:23:08 -08004983 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004984 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004986 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004987 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004988 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4989 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004990 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004991 state.displayId, toString(state.down), toString(state.split),
4992 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004993 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004994 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004995 for (size_t i = 0; i < state.windows.size(); i++) {
4996 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004997 dump += StringPrintf(INDENT4
4998 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4999 i, touchedWindow.windowHandle->getName().c_str(),
5000 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005001 }
5002 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005003 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 }
5006 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005007 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009
arthurhung6d4bed92021-03-17 11:59:33 +08005010 if (mDragState) {
5011 dump += StringPrintf(INDENT "DragState:\n");
5012 mDragState->dump(dump, INDENT2);
5013 }
5014
Arthur Hungb92218b2018-08-14 12:00:21 +08005015 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005017 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005018 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005019 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005020 dump += INDENT2 "Windows:\n";
5021 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005022 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5023 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005025 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005026 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005027 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005028 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005029 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005030 "applicationInfo.name=%s, "
5031 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005032 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005033 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005034 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005035 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005037 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005038 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005039 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005040 windowInfo->frameLeft, windowInfo->frameTop,
5041 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005042 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005043 windowInfo->applicationInfo.name.c_str(),
5044 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005045 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005046 dump += StringPrintf(", inputFeatures=%s",
5047 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005048 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005049 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan817f6062021-08-16 12:15:11 -07005050 "touchOcclusionMode=%s, displayOrientation=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005051 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005052 millis(windowInfo->dispatchingTimeout),
5053 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005054 toString(windowInfo->token != nullptr),
Prabir Pradhan817f6062021-08-16 12:15:11 -07005055 toString(windowInfo->touchOcclusionMode).c_str(),
5056 windowInfo->displayOrientation);
chaviw85b44202020-07-24 11:46:21 -07005057 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005058 }
5059 } else {
5060 dump += INDENT2 "Windows: <none>\n";
5061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 }
5063 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005064 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 }
5066
Michael Wright3dd60e22019-03-27 22:06:44 +00005067 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005068 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005069 const std::vector<Monitor>& monitors = it.second;
5070 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5071 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005072 }
5073 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005074 const std::vector<Monitor>& monitors = it.second;
5075 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5076 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005079 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081
5082 nsecs_t currentTime = now();
5083
5084 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005085 if (!mRecentQueue.empty()) {
5086 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005087 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005088 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005089 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005090 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
5092 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005093 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 }
5095
5096 // Dump event currently being dispatched.
5097 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005098 dump += INDENT "PendingEvent:\n";
5099 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005100 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005101 dump += StringPrintf(", age=%" PRId64 "ms\n",
5102 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005104 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 }
5106
5107 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005108 if (!mInboundQueue.empty()) {
5109 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005110 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005112 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005113 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 }
5115 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005116 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 }
5118
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005119 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005120 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005121 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5122 const KeyReplacement& replacement = pair.first;
5123 int32_t newKeyCode = pair.second;
5124 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005125 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005126 }
5127 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005128 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005129 }
5130
Prabir Pradhancef936d2021-07-21 16:17:52 +00005131 if (!mCommandQueue.empty()) {
5132 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5133 } else {
5134 dump += INDENT "CommandQueue: <empty>\n";
5135 }
5136
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005137 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005139 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005141 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005142 connection->inputChannel->getFd().get(),
5143 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005145 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005147 if (!connection->outboundQueue.empty()) {
5148 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5149 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005150 dump += dumpQueue(connection->outboundQueue, currentTime);
5151
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005156 if (!connection->waitQueue.empty()) {
5157 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5158 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005159 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005161 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163 }
5164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
5168 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005169 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5170 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005175 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005176 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5177 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5178 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005179 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005180 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Michael Wright3dd60e22019-03-27 22:06:44 +00005183void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5184 const size_t numMonitors = monitors.size();
5185 for (size_t i = 0; i < numMonitors; i++) {
5186 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005187 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005188 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5189 dump += "\n";
5190 }
5191}
5192
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005193class LooperEventCallback : public LooperCallback {
5194public:
5195 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5196 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5197
5198private:
5199 std::function<int(int events)> mCallback;
5200};
5201
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005202Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005203 if (DEBUG_CHANNEL_CREATION) {
5204 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005207 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005208 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005209 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005210
5211 if (result) {
5212 return base::Error(result) << "Failed to open input channel pair with name " << name;
5213 }
5214
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005216 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005217 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005218 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005219 sp<Connection> connection =
5220 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005222 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5223 ALOGE("Created a new connection, but the token %p is already known", token.get());
5224 }
5225 mConnectionsByToken.emplace(token, connection);
5226
5227 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5228 this, std::placeholders::_1, token);
5229
5230 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 } // release lock
5232
5233 // Wake the looper because some connections have changed.
5234 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005235 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236}
5237
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005238Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5239 bool isGestureMonitor,
5240 const std::string& name,
5241 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005242 std::shared_ptr<InputChannel> serverChannel;
5243 std::unique_ptr<InputChannel> clientChannel;
5244 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5245 if (result) {
5246 return base::Error(result) << "Failed to open input channel pair with name " << name;
5247 }
5248
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 { // acquire lock
5250 std::scoped_lock _l(mLock);
5251
5252 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005253 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5254 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005255 }
5256
Garfield Tan15601662020-09-22 15:32:38 -07005257 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005258 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005259 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005260
5261 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5262 ALOGE("Created a new connection, but the token %p is already known", token.get());
5263 }
5264 mConnectionsByToken.emplace(token, connection);
5265 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5266 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 auto& monitorsByDisplay =
5269 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005270 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005273 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5274 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005275 }
Garfield Tan15601662020-09-22 15:32:38 -07005276
Michael Wright3dd60e22019-03-27 22:06:44 +00005277 // Wake the looper because some connections have changed.
5278 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005279 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005280}
5281
Garfield Tan15601662020-09-22 15:32:38 -07005282status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005284 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285
Garfield Tan15601662020-09-22 15:32:38 -07005286 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 if (status) {
5288 return status;
5289 }
5290 } // release lock
5291
5292 // Wake the poll loop because removing the connection may have changed the current
5293 // synchronization state.
5294 mLooper->wake();
5295 return OK;
5296}
5297
Garfield Tan15601662020-09-22 15:32:38 -07005298status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5299 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005300 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005301 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005302 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 return BAD_VALUE;
5304 }
5305
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005306 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005307
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005309 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005312 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 nsecs_t currentTime = now();
5315 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5316
5317 connection->status = Connection::STATUS_ZOMBIE;
5318 return OK;
5319}
5320
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005321void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5322 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5323 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005324}
5325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005327 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005328 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005330 std::vector<Monitor>& monitors = it->second;
5331 const size_t numMonitors = monitors.size();
5332 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005333 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005334 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5335 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005336 monitors.erase(monitors.begin() + i);
5337 break;
5338 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005339 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 if (monitors.empty()) {
5341 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005342 } else {
5343 ++it;
5344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346}
5347
Michael Wright3dd60e22019-03-27 22:06:44 +00005348status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5349 { // acquire lock
5350 std::scoped_lock _l(mLock);
5351 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5352
5353 if (!foundDisplayId) {
5354 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5355 return BAD_VALUE;
5356 }
5357 int32_t displayId = foundDisplayId.value();
5358
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005359 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5360 mTouchStatesByDisplay.find(displayId);
5361 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005362 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5363 return BAD_VALUE;
5364 }
5365
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005366 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005367 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005368 std::optional<int32_t> foundDeviceId;
5369 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005370 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005371 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005372 foundDeviceId = state.deviceId;
5373 }
5374 }
5375 if (!foundDeviceId || !state.down) {
5376 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005377 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005378 return BAD_VALUE;
5379 }
5380 int32_t deviceId = foundDeviceId.value();
5381
5382 // Send cancel events to all the input channels we're stealing from.
5383 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 options.deviceId = deviceId;
5386 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005387 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005388 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005389 std::shared_ptr<InputChannel> channel =
5390 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005391 if (channel != nullptr) {
5392 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005393 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005394 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005396 canceledWindows += "]";
5397 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5398 canceledWindows.c_str());
5399
Michael Wright3dd60e22019-03-27 22:06:44 +00005400 // Then clear the current touch state so we stop dispatching to them as well.
5401 state.filterNonMonitors();
5402 }
5403 return OK;
5404}
5405
Prabir Pradhan99987712020-11-10 18:43:05 -08005406void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5407 { // acquire lock
5408 std::scoped_lock _l(mLock);
5409 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005410 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005411 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5412 windowHandle != nullptr ? windowHandle->getName().c_str()
5413 : "token without window");
5414 }
5415
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005417 if (focusedToken != windowToken) {
5418 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5419 enabled ? "enable" : "disable");
5420 return;
5421 }
5422
5423 if (enabled == mFocusedWindowRequestedPointerCapture) {
5424 ALOGW("Ignoring request to %s Pointer Capture: "
5425 "window has %s requested pointer capture.",
5426 enabled ? "enable" : "disable", enabled ? "already" : "not");
5427 return;
5428 }
5429
5430 mFocusedWindowRequestedPointerCapture = enabled;
5431 setPointerCaptureLocked(enabled);
5432 } // release lock
5433
5434 // Wake the thread to process command entries.
5435 mLooper->wake();
5436}
5437
Michael Wright3dd60e22019-03-27 22:06:44 +00005438std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5439 const sp<IBinder>& token) {
5440 for (const auto& it : mGestureMonitorsByDisplay) {
5441 const std::vector<Monitor>& monitors = it.second;
5442 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005443 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005444 return it.first;
5445 }
5446 }
5447 }
5448 return std::nullopt;
5449}
5450
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005451std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5452 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5453 if (gesturePid.has_value()) {
5454 return gesturePid;
5455 }
5456 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5457}
5458
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005459sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005460 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005461 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005462 }
5463
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005464 for (const auto& [token, connection] : mConnectionsByToken) {
5465 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005466 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 }
5468 }
Robert Carr4e670e52018-08-15 13:26:12 -07005469
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005470 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471}
5472
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005473std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5474 sp<Connection> connection = getConnectionLocked(connectionToken);
5475 if (connection == nullptr) {
5476 return "<nullptr>";
5477 }
5478 return connection->getInputChannelName();
5479}
5480
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005481void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005482 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005483 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005484}
5485
Prabir Pradhancef936d2021-07-21 16:17:52 +00005486void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5487 const sp<Connection>& connection, uint32_t seq,
5488 bool handled, nsecs_t consumeTime) {
5489 // Handle post-event policy actions.
5490 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5491 if (dispatchEntryIt == connection->waitQueue.end()) {
5492 return;
5493 }
5494 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5495 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5496 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5497 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5498 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5499 }
5500 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5501 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5502 connection->inputChannel->getConnectionToken(),
5503 dispatchEntry->deliveryTime, consumeTime, finishTime);
5504 }
5505
5506 bool restartEvent;
5507 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5508 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5509 restartEvent =
5510 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5511 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5512 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5513 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5514 handled);
5515 } else {
5516 restartEvent = false;
5517 }
5518
5519 // Dequeue the event and start the next cycle.
5520 // Because the lock might have been released, it is possible that the
5521 // contents of the wait queue to have been drained, so we need to double-check
5522 // a few things.
5523 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5524 if (dispatchEntryIt != connection->waitQueue.end()) {
5525 dispatchEntry = *dispatchEntryIt;
5526 connection->waitQueue.erase(dispatchEntryIt);
5527 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5528 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5529 if (!connection->responsive) {
5530 connection->responsive = isConnectionResponsive(*connection);
5531 if (connection->responsive) {
5532 // The connection was unresponsive, and now it's responsive.
5533 processConnectionResponsiveLocked(*connection);
5534 }
5535 }
5536 traceWaitQueueLength(*connection);
5537 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5538 connection->outboundQueue.push_front(dispatchEntry);
5539 traceOutboundQueueLength(*connection);
5540 } else {
5541 releaseDispatchEntry(dispatchEntry);
5542 }
5543 }
5544
5545 // Start the next dispatch cycle for this connection.
5546 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547}
5548
Prabir Pradhancef936d2021-07-21 16:17:52 +00005549void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5550 const sp<IBinder>& newToken) {
5551 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5552 scoped_unlock unlock(mLock);
5553 mPolicy->notifyFocusChanged(oldToken, newToken);
5554 };
5555 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556}
5557
Prabir Pradhancef936d2021-07-21 16:17:52 +00005558void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5559 auto command = [this, token, x, y]() REQUIRES(mLock) {
5560 scoped_unlock unlock(mLock);
5561 mPolicy->notifyDropWindow(token, x, y);
5562 };
5563 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005564}
5565
Prabir Pradhancef936d2021-07-21 16:17:52 +00005566void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5567 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5568 scoped_unlock unlock(mLock);
5569 mPolicy->notifyUntrustedTouch(obscuringPackage);
5570 };
5571 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005572}
5573
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005574void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5575 if (connection == nullptr) {
5576 LOG_ALWAYS_FATAL("Caller must check for nullness");
5577 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005578 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5579 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005580 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005581 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005582 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005583 return;
5584 }
5585 /**
5586 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5587 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5588 * has changed. This could cause newer entries to time out before the already dispatched
5589 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5590 * processes the events linearly. So providing information about the oldest entry seems to be
5591 * most useful.
5592 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005593 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005594 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5595 std::string reason =
5596 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005597 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005598 ns2ms(currentWait),
5599 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005600 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005601 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005602
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005603 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5604
5605 // Stop waking up for events on this connection, it is already unresponsive
5606 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005607}
5608
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005609void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5610 std::string reason =
5611 StringPrintf("%s does not have a focused window", application->getName().c_str());
5612 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005613
Prabir Pradhancef936d2021-07-21 16:17:52 +00005614 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5615 scoped_unlock unlock(mLock);
5616 mPolicy->notifyNoFocusedWindowAnr(application);
5617 };
5618 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005619}
5620
chaviw98318de2021-05-19 16:45:23 -05005621void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005622 const std::string& reason) {
5623 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5624 updateLastAnrStateLocked(windowLabel, reason);
5625}
5626
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005627void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5628 const std::string& reason) {
5629 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005630 updateLastAnrStateLocked(windowLabel, reason);
5631}
5632
5633void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5634 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005636 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 struct tm tm;
5638 localtime_r(&t, &tm);
5639 char timestr[64];
5640 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005641 mLastAnrState.clear();
5642 mLastAnrState += INDENT "ANR:\n";
5643 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005644 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5645 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005646 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647}
5648
Prabir Pradhancef936d2021-07-21 16:17:52 +00005649void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5650 KeyEntry& entry) {
5651 const KeyEvent event = createKeyEvent(entry);
5652 nsecs_t delay = 0;
5653 { // release lock
5654 scoped_unlock unlock(mLock);
5655 android::base::Timer t;
5656 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5657 entry.policyFlags);
5658 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5659 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5660 std::to_string(t.duration().count()).c_str());
5661 }
5662 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663
5664 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005665 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005666 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005667 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005669 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5670 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672}
5673
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005674void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005675 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5676 scoped_unlock unlock(mLock);
5677 mPolicy->notifyMonitorUnresponsive(pid, reason);
5678 };
5679 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005680}
5681
Prabir Pradhancef936d2021-07-21 16:17:52 +00005682void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005683 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005684 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5685 scoped_unlock unlock(mLock);
5686 mPolicy->notifyWindowUnresponsive(token, reason);
5687 };
5688 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005689}
5690
5691void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005692 auto command = [this, pid]() REQUIRES(mLock) {
5693 scoped_unlock unlock(mLock);
5694 mPolicy->notifyMonitorResponsive(pid);
5695 };
5696 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005697}
5698
Prabir Pradhancef936d2021-07-21 16:17:52 +00005699void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5700 auto command = [this, connectionToken]() REQUIRES(mLock) {
5701 scoped_unlock unlock(mLock);
5702 mPolicy->notifyWindowResponsive(connectionToken);
5703 };
5704 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005705}
5706
5707/**
5708 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5709 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5710 * command entry to the command queue.
5711 */
5712void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5713 std::string reason) {
5714 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5715 if (connection.monitor) {
5716 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5717 reason.c_str());
5718 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5719 if (!pid.has_value()) {
5720 ALOGE("Could not find unresponsive monitor for connection %s",
5721 connection.inputChannel->getName().c_str());
5722 return;
5723 }
5724 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5725 return;
5726 }
5727 // If not a monitor, must be a window
5728 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5729 reason.c_str());
5730 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5731}
5732
5733/**
5734 * Tell the policy that a connection has become responsive so that it can stop ANR.
5735 */
5736void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5737 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5738 if (connection.monitor) {
5739 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5740 if (!pid.has_value()) {
5741 ALOGE("Could not find responsive monitor for connection %s",
5742 connection.inputChannel->getName().c_str());
5743 return;
5744 }
5745 sendMonitorResponsiveCommandLocked(pid.value());
5746 return;
5747 }
5748 // If not a monitor, must be a window
5749 sendWindowResponsiveCommandLocked(connectionToken);
5750}
5751
Prabir Pradhancef936d2021-07-21 16:17:52 +00005752bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005753 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005754 KeyEntry& keyEntry, bool handled) {
5755 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005756 if (!handled) {
5757 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005758 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005759 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005760 return false;
5761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005763 // Get the fallback key state.
5764 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005765 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005766 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005767 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005768 connection->inputState.removeFallbackKey(originalKeyCode);
5769 }
5770
5771 if (handled || !dispatchEntry->hasForegroundTarget()) {
5772 // If the application handles the original key for which we previously
5773 // generated a fallback or if the window is not a foreground window,
5774 // then cancel the associated fallback key, if any.
5775 if (fallbackKeyCode != -1) {
5776 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005777 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5778 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5779 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5780 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5781 keyEntry.policyFlags);
5782 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005783 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005784 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785
5786 mLock.unlock();
5787
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005788 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005789 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790
5791 mLock.lock();
5792
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005793 // Cancel the fallback key.
5794 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005796 "application handled the original non-fallback key "
5797 "or is no longer a foreground target, "
5798 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799 options.keyCode = fallbackKeyCode;
5800 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005802 connection->inputState.removeFallbackKey(originalKeyCode);
5803 }
5804 } else {
5805 // If the application did not handle a non-fallback key, first check
5806 // that we are in a good state to perform unhandled key event processing
5807 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005808 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005809 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005810 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5811 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5812 "since this is not an initial down. "
5813 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5814 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5815 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005816 return false;
5817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005819 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005820 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5821 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5822 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5823 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5824 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005825 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005826
5827 mLock.unlock();
5828
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005829 bool fallback =
5830 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005831 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005832
5833 mLock.lock();
5834
5835 if (connection->status != Connection::STATUS_NORMAL) {
5836 connection->inputState.removeFallbackKey(originalKeyCode);
5837 return false;
5838 }
5839
5840 // Latch the fallback keycode for this key on an initial down.
5841 // The fallback keycode cannot change at any other point in the lifecycle.
5842 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005844 fallbackKeyCode = event.getKeyCode();
5845 } else {
5846 fallbackKeyCode = AKEYCODE_UNKNOWN;
5847 }
5848 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5849 }
5850
5851 ALOG_ASSERT(fallbackKeyCode != -1);
5852
5853 // Cancel the fallback key if the policy decides not to send it anymore.
5854 // We will continue to dispatch the key to the policy but we will no
5855 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005856 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5857 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005858 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5859 if (fallback) {
5860 ALOGD("Unhandled key event: Policy requested to send key %d"
5861 "as a fallback for %d, but on the DOWN it had requested "
5862 "to send %d instead. Fallback canceled.",
5863 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5864 } else {
5865 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5866 "but on the DOWN it had requested to send %d. "
5867 "Fallback canceled.",
5868 originalKeyCode, fallbackKeyCode);
5869 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005870 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005871
5872 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5873 "canceling fallback, policy no longer desires it");
5874 options.keyCode = fallbackKeyCode;
5875 synthesizeCancelationEventsForConnectionLocked(connection, options);
5876
5877 fallback = false;
5878 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005879 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005880 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 }
5882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005884 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5885 {
5886 std::string msg;
5887 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5888 connection->inputState.getFallbackKeys();
5889 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5890 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5891 }
5892 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5893 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005895 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005896
5897 if (fallback) {
5898 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005899 keyEntry.eventTime = event.getEventTime();
5900 keyEntry.deviceId = event.getDeviceId();
5901 keyEntry.source = event.getSource();
5902 keyEntry.displayId = event.getDisplayId();
5903 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5904 keyEntry.keyCode = fallbackKeyCode;
5905 keyEntry.scanCode = event.getScanCode();
5906 keyEntry.metaState = event.getMetaState();
5907 keyEntry.repeatCount = event.getRepeatCount();
5908 keyEntry.downTime = event.getDownTime();
5909 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005910
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005911 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5912 ALOGD("Unhandled key event: Dispatching fallback key. "
5913 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5914 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
5915 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005916 return true; // restart the event
5917 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005918 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5919 ALOGD("Unhandled key event: No fallback key.");
5920 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005921
5922 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005923 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 }
5925 }
5926 return false;
5927}
5928
Prabir Pradhancef936d2021-07-21 16:17:52 +00005929bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005930 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005931 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 return false;
5933}
5934
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935void InputDispatcher::traceInboundQueueLengthLocked() {
5936 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005937 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 }
5939}
5940
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005941void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 if (ATRACE_ENABLED()) {
5943 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005944 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
5945 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946 }
5947}
5948
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005949void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950 if (ATRACE_ENABLED()) {
5951 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005952 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
5953 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 }
5955}
5956
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005957void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005958 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005960 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 dumpDispatchStateLocked(dump);
5962
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005963 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005964 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005965 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966 }
5967}
5968
5969void InputDispatcher::monitor() {
5970 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005971 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005973 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974}
5975
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005976/**
5977 * Wake up the dispatcher and wait until it processes all events and commands.
5978 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5979 * this method can be safely called from any thread, as long as you've ensured that
5980 * the work you are interested in completing has already been queued.
5981 */
5982bool InputDispatcher::waitForIdle() {
5983 /**
5984 * Timeout should represent the longest possible time that a device might spend processing
5985 * events and commands.
5986 */
5987 constexpr std::chrono::duration TIMEOUT = 100ms;
5988 std::unique_lock lock(mLock);
5989 mLooper->wake();
5990 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5991 return result == std::cv_status::no_timeout;
5992}
5993
Vishnu Naire798b472020-07-23 13:52:21 -07005994/**
5995 * Sets focus to the window identified by the token. This must be called
5996 * after updating any input window handles.
5997 *
5998 * Params:
5999 * request.token - input channel token used to identify the window that should gain focus.
6000 * request.focusedToken - the token that the caller expects currently to be focused. If the
6001 * specified token does not match the currently focused window, this request will be dropped.
6002 * If the specified focused token matches the currently focused window, the call will succeed.
6003 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6004 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6005 * when requesting the focus change. This determines which request gets
6006 * precedence if there is a focus change request from another source such as pointer down.
6007 */
Vishnu Nair958da932020-08-21 17:12:37 -07006008void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6009 { // acquire lock
6010 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006011 std::optional<FocusResolver::FocusChanges> changes =
6012 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6013 if (changes) {
6014 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006015 }
6016 } // release lock
6017 // Wake up poll loop since it may need to make new input dispatching choices.
6018 mLooper->wake();
6019}
6020
Vishnu Nairc519ff72021-01-21 08:23:08 -08006021void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6022 if (changes.oldFocus) {
6023 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006024 if (focusedInputChannel) {
6025 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6026 "focus left window");
6027 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006028 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006029 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006030 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006031 if (changes.newFocus) {
6032 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006033 }
6034
Prabir Pradhan99987712020-11-10 18:43:05 -08006035 // If a window has pointer capture, then it must have focus. We need to ensure that this
6036 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6037 // If the window loses focus before it loses pointer capture, then the window can be in a state
6038 // where it has pointer capture but not focus, violating the contract. Therefore we must
6039 // dispatch the pointer capture event before the focus event. Since focus events are added to
6040 // the front of the queue (above), we add the pointer capture event to the front of the queue
6041 // after the focus events are added. This ensures the pointer capture event ends up at the
6042 // front.
6043 disablePointerCaptureForcedLocked();
6044
Vishnu Nairc519ff72021-01-21 08:23:08 -08006045 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006046 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006047 }
6048}
Vishnu Nair958da932020-08-21 17:12:37 -07006049
Prabir Pradhan99987712020-11-10 18:43:05 -08006050void InputDispatcher::disablePointerCaptureForcedLocked() {
6051 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6052 return;
6053 }
6054
6055 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6056
6057 if (mFocusedWindowRequestedPointerCapture) {
6058 mFocusedWindowRequestedPointerCapture = false;
6059 setPointerCaptureLocked(false);
6060 }
6061
6062 if (!mWindowTokenWithPointerCapture) {
6063 // No need to send capture changes because no window has capture.
6064 return;
6065 }
6066
6067 if (mPendingEvent != nullptr) {
6068 // Move the pending event to the front of the queue. This will give the chance
6069 // for the pending event to be dropped if it is a captured event.
6070 mInboundQueue.push_front(mPendingEvent);
6071 mPendingEvent = nullptr;
6072 }
6073
6074 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6075 false /* hasCapture */);
6076 mInboundQueue.push_front(std::move(entry));
6077}
6078
Prabir Pradhan99987712020-11-10 18:43:05 -08006079void InputDispatcher::setPointerCaptureLocked(bool enabled) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006080 auto command = [this, enabled]() REQUIRES(mLock) {
6081 scoped_unlock unlock(mLock);
6082 mPolicy->setPointerCapture(enabled);
6083 };
6084 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006085}
6086
Vishnu Nair599f1412021-06-21 10:39:58 -07006087void InputDispatcher::displayRemoved(int32_t displayId) {
6088 { // acquire lock
6089 std::scoped_lock _l(mLock);
6090 // Set an empty list to remove all handles from the specific display.
6091 setInputWindowsLocked(/* window handles */ {}, displayId);
6092 setFocusedApplicationLocked(displayId, nullptr);
6093 // Call focus resolver to clean up stale requests. This must be called after input windows
6094 // have been removed for the removed display.
6095 mFocusResolver.displayRemoved(displayId);
6096 } // release lock
6097
6098 // Wake up poll loop since it may need to make new input dispatching choices.
6099 mLooper->wake();
6100}
6101
chaviw15fab6f2021-06-07 14:15:52 -05006102void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6103 // The listener sends the windows as a flattened array. Separate the windows by display for
6104 // more convenient parsing.
6105 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6106
6107 for (const auto& info : windowInfos) {
6108 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6109 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6110 }
6111 setInputWindows(handlesPerDisplay);
6112}
6113
Garfield Tane84e6f92019-08-29 17:28:41 -07006114} // namespace android::inputdispatcher