blob: 81c64e20e9d39017ad70b4853491ae7896e663e5 [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 =
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700114 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
115
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
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700829 case EventEntry::Type::TOUCH_MODE_CHANGED: {
830 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
831 dispatchTouchModeChangeLocked(currentTime, typedEntry);
832 done = true;
833 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
834 break;
835 }
836
Prabir Pradhan99987712020-11-10 18:43:05 -0800837 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
838 const auto typedEntry =
839 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
840 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
841 done = true;
842 break;
843 }
844
arthurhungb89ccb02020-12-30 16:19:01 +0800845 case EventEntry::Type::DRAG: {
846 std::shared_ptr<DragEntry> typedEntry =
847 std::static_pointer_cast<DragEntry>(mPendingEvent);
848 dispatchDragLocked(currentTime, typedEntry);
849 done = true;
850 break;
851 }
852
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700853 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700854 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 resetPendingAppSwitchLocked(true);
858 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 } else if (dropReason == DropReason::NOT_DROPPED) {
860 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 }
862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700864 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
867 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 break;
871 }
872
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700873 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 std::shared_ptr<MotionEntry> motionEntry =
875 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
877 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700880 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
883 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700885 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 }
Chris Yef59a2f42020-10-16 12:55:26 -0700888
889 case EventEntry::Type::SENSOR: {
890 std::shared_ptr<SensorEntry> sensorEntry =
891 std::static_pointer_cast<SensorEntry>(mPendingEvent);
892 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
893 dropReason = DropReason::APP_SWITCH;
894 }
895 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
896 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
897 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
898 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
899 dropReason = DropReason::STALE;
900 }
901 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
902 done = true;
903 break;
904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
906
907 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700908 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700909 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
Michael Wright3a981722015-06-10 15:26:13 +0100911 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
913 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 }
916}
917
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700918/**
919 * Return true if the events preceding this incoming motion event should be dropped
920 * Return false otherwise (the default behaviour)
921 */
922bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925
926 // Optimize case where the current application is unresponsive and the user
927 // decides to touch a window in a different application.
928 // If the application takes too long to catch up then we drop all events preceding
929 // the touch into the other window.
930 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700931 int32_t displayId = motionEntry.displayId;
932 int32_t x = static_cast<int32_t>(
933 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
934 int32_t y = static_cast<int32_t>(
935 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500936 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 findTouchedWindowAtLocked(displayId, x, y, nullptr);
938 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 touchedWindowHandle->getApplicationToken() !=
940 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 ALOGI("Pruning input queue because user touched a different application while waiting "
943 "for %s",
944 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700945 return true;
946 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947
948 // Alternatively, maybe there's a gesture monitor that could handle this event
Siarhei Vishniakou64452932020-11-06 17:51:32 -0600949 std::vector<TouchedMonitor> gestureMonitors = findTouchedGestureMonitorsLocked(displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
951 sp<Connection> connection =
952 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000953 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700954 // This monitor could take more input. Drop all events preceding this
955 // event, so that gesture monitor could get a chance to receive the stream
956 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
957 "responsive gesture monitor that may handle the event",
958 mAwaitedFocusedApplication->getName().c_str());
959 return true;
960 }
961 }
962 }
963
964 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
965 // yet been processed by some connections, the dispatcher will wait for these motion
966 // events to be processed before dispatching the key event. This is because these motion events
967 // may cause a new window to be launched, which the user might expect to receive focus.
968 // To prevent waiting forever for such events, just send the key to the currently focused window
969 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
970 ALOGD("Received a new pointer down event, stop waiting for events to process and "
971 "just send the pending key event to the focused window.");
972 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700973 }
974 return false;
975}
976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700978 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 mInboundQueue.push_back(std::move(newEntry));
980 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 traceInboundQueueLengthLocked();
982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700984 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 // Optimize app switch latency.
986 // If the application takes too long to catch up then we drop all events preceding
987 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700988 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700990 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000994 if (DEBUG_APP_SWITCH) {
995 ALOGD("App switch is pending!");
996 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 mAppSwitchSawKeyDown = false;
999 needWake = true;
1000 }
1001 }
1002 }
1003 break;
1004 }
1005
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001006 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001007 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1008 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001009 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001013 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001014 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1015 break;
1016 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001017 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001018 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001019 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001020 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001021 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1022 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 // nothing to do
1024 break;
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027
1028 return needWake;
1029}
1030
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001031void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001032 // Do not store sensor event in recent queue to avoid flooding the queue.
1033 if (entry->type != EventEntry::Type::SENSOR) {
1034 mRecentQueue.push_back(entry);
1035 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001036 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001037 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
1039}
1040
chaviw98318de2021-05-19 16:45:23 -05001041sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1042 int32_t y, TouchState* touchState,
1043 bool addOutsideTargets,
1044 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001045 if (addOutsideTargets && touchState == nullptr) {
1046 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001049 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1050 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001051 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001052 continue;
1053 }
chaviw98318de2021-05-19 16:45:23 -05001054 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001056 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057
1058 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001059 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1060 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1061 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1063 // Found window.
1064 return windowHandle;
1065 }
1066 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001067
chaviw98318de2021-05-19 16:45:23 -05001068 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001069 touchState->addOrUpdateWindow(windowHandle,
1070 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1071 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
1075 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001076 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077}
1078
Garfield Tane84e6f92019-08-29 17:28:41 -07001079std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001080 int32_t displayId) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001081 std::vector<TouchedMonitor> touchedMonitors;
1082
1083 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1084 addGestureMonitors(monitors, touchedMonitors);
Michael Wright3dd60e22019-03-27 22:06:44 +00001085 return touchedMonitors;
1086}
1087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001088void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 const char* reason;
1090 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001092 if (DEBUG_INBOUND_EVENT_DETAILS) {
1093 ALOGD("Dropped event because policy consumed it.");
1094 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 reason = "inbound event was dropped because the policy consumed it";
1096 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 case DropReason::DISABLED:
1098 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 ALOGI("Dropped event because input dispatch is disabled.");
1100 }
1101 reason = "inbound event was dropped because input dispatch is disabled";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because of pending overdue app switch.");
1105 reason = "inbound event was dropped because of pending overdue app switch";
1106 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001107 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 ALOGI("Dropped event because the current application is not responding and the user "
1109 "has started interacting with a different application.");
1110 reason = "inbound event was dropped because the current application is not responding "
1111 "and the user has started interacting with a different application";
1112 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 ALOGI("Dropped event because it is stale.");
1115 reason = "inbound event was dropped because it is stale";
1116 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001117 case DropReason::NO_POINTER_CAPTURE:
1118 ALOGI("Dropped event because there is no window with Pointer Capture.");
1119 reason = "inbound event was dropped because there is no window with Pointer Capture";
1120 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 case DropReason::NOT_DROPPED: {
1122 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001127 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001128 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1130 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001134 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1135 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1137 synthesizeCancelationEventsForAllConnectionsLocked(options);
1138 } else {
1139 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1140 synthesizeCancelationEventsForAllConnectionsLocked(options);
1141 }
1142 break;
1143 }
Chris Yef59a2f42020-10-16 12:55:26 -07001144 case EventEntry::Type::SENSOR: {
1145 break;
1146 }
arthurhungb89ccb02020-12-30 16:19:01 +08001147 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1148 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001149 break;
1150 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001151 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001152 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001153 case EventEntry::Type::CONFIGURATION_CHANGED:
1154 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001155 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001156 break;
1157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159}
1160
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001161static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1163 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164}
1165
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1167 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1168 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1169 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170}
1171
1172bool InputDispatcher::isAppSwitchPendingLocked() {
1173 return mAppSwitchDueTime != LONG_LONG_MAX;
1174}
1175
1176void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1177 mAppSwitchDueTime = LONG_LONG_MAX;
1178
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001179 if (DEBUG_APP_SWITCH) {
1180 if (handled) {
1181 ALOGD("App switch has arrived.");
1182 } else {
1183 ALOGD("App switch was abandoned.");
1184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186}
1187
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190}
1191
Prabir Pradhancef936d2021-07-21 16:17:52 +00001192bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001193 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return false;
1195 }
1196
1197 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001198 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001199 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001200 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1201 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001202 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 return true;
1204}
1205
Prabir Pradhancef936d2021-07-21 16:17:52 +00001206void InputDispatcher::postCommandLocked(Command&& command) {
1207 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
1210void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001211 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001212 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001213 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 releaseInboundEventLocked(entry);
1215 }
1216 traceInboundQueueLengthLocked();
1217}
1218
1219void InputDispatcher::releasePendingEventLocked() {
1220 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001222 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224}
1225
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001226void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001228 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001229 if (DEBUG_DISPATCH_CYCLE) {
1230 ALOGD("Injected inbound event was dropped.");
1231 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001235 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 }
1237 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238}
1239
1240void InputDispatcher::resetKeyRepeatLocked() {
1241 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001242 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244}
1245
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1247 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
Michael Wright2e732952014-09-24 13:26:59 -07001249 uint32_t policyFlags = entry->policyFlags &
1250 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 std::shared_ptr<KeyEntry> newEntry =
1253 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1254 entry->source, entry->displayId, policyFlags, entry->action,
1255 entry->flags, entry->keyCode, entry->scanCode,
1256 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001258 newEntry->syntheticRepeat = true;
1259 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262}
1263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001266 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1267 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269
1270 // Reset key repeating in case a keyboard device was added or removed or something.
1271 resetKeyRepeatLocked();
1272
1273 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001274 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1275 scoped_unlock unlock(mLock);
1276 mPolicy->notifyConfigurationChanged(eventTime);
1277 };
1278 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280}
1281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1283 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001284 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1285 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1286 entry.deviceId);
1287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
liushenxiang42232912021-05-21 20:24:09 +08001289 // Reset key repeating in case a keyboard device was disabled or enabled.
1290 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1291 resetKeyRepeatLocked();
1292 }
1293
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 synthesizeCancelationEventsForAllConnectionsLocked(options);
1297 return true;
1298}
1299
Vishnu Nairad321cd2020-08-20 16:40:21 -07001300void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001301 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302 if (mPendingEvent != nullptr) {
1303 // Move the pending event to the front of the queue. This will give the chance
1304 // for the pending event to get dispatched to the newly focused window
1305 mInboundQueue.push_front(mPendingEvent);
1306 mPendingEvent = nullptr;
1307 }
1308
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001309 std::unique_ptr<FocusEntry> focusEntry =
1310 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1311 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001312
1313 // This event should go to the front of the queue, but behind all other focus events
1314 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001316 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001317 [](const std::shared_ptr<EventEntry>& event) {
1318 return event->type == EventEntry::Type::FOCUS;
1319 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001320
1321 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001322 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001323}
1324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001326 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001327 if (channel == nullptr) {
1328 return; // Window has gone away
1329 }
1330 InputTarget target;
1331 target.inputChannel = channel;
1332 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1333 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001334 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1335 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001336 std::string reason = std::string("reason=").append(entry->reason);
1337 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001338 dispatchEventLocked(currentTime, entry, {target});
1339}
1340
Prabir Pradhan99987712020-11-10 18:43:05 -08001341void InputDispatcher::dispatchPointerCaptureChangedLocked(
1342 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1343 DropReason& dropReason) {
1344 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001345 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1346 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1347 }
1348 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 // Pointer capture was already forcefully disabled because of focus change.
1350 dropReason = DropReason::NOT_DROPPED;
1351 return;
1352 }
1353
1354 // Set drop reason for early returns
1355 dropReason = DropReason::NO_POINTER_CAPTURE;
1356
1357 sp<IBinder> token;
1358 if (entry->pointerCaptureEnabled) {
1359 // Enable Pointer Capture
1360 if (!mFocusedWindowRequestedPointerCapture) {
1361 // This can happen if a window requests capture and immediately releases capture.
1362 ALOGW("No window requested Pointer Capture.");
1363 return;
1364 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001365 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001366 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1367 mWindowTokenWithPointerCapture = token;
1368 } else {
1369 // Disable Pointer Capture
1370 token = mWindowTokenWithPointerCapture;
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 }
1377
1378 auto channel = getInputChannelLocked(token);
1379 if (channel == nullptr) {
1380 // Window has gone away, clean up Pointer Capture state.
1381 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001382 if (mFocusedWindowRequestedPointerCapture) {
1383 mFocusedWindowRequestedPointerCapture = false;
1384 setPointerCaptureLocked(false);
1385 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001386 return;
1387 }
1388 InputTarget target;
1389 target.inputChannel = channel;
1390 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1391 entry->dispatchInProgress = true;
1392 dispatchEventLocked(currentTime, entry, {target});
1393
1394 dropReason = DropReason::NOT_DROPPED;
1395}
1396
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001397void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1398 const std::shared_ptr<TouchModeEntry>& entry) {
1399 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1400 getWindowHandlesLocked(mFocusedDisplayId);
1401 if (windowHandles.empty()) {
1402 return;
1403 }
1404 const std::vector<InputTarget> inputTargets =
1405 getInputTargetsFromWindowHandlesLocked(windowHandles);
1406 if (inputTargets.empty()) {
1407 return;
1408 }
1409 entry->dispatchInProgress = true;
1410 dispatchEventLocked(currentTime, entry, inputTargets);
1411}
1412
1413std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1414 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1415 std::vector<InputTarget> inputTargets;
1416 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1417 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1418 const sp<IBinder>& token = handle->getToken();
1419 if (token == nullptr) {
1420 continue;
1421 }
1422 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1423 if (channel == nullptr) {
1424 continue; // Window has gone away
1425 }
1426 InputTarget target;
1427 target.inputChannel = channel;
1428 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1429 inputTargets.push_back(target);
1430 }
1431 return inputTargets;
1432}
1433
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001434bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001437 if (!entry->dispatchInProgress) {
1438 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1439 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1440 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1441 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001442 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 // We have seen two identical key downs in a row which indicates that the device
1444 // driver is automatically generating key repeats itself. We take note of the
1445 // repeat here, but we disable our own next key repeat timer since it is clear that
1446 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001447 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1448 // Make sure we don't get key down from a different device. If a different
1449 // device Id has same key pressed down, the new device Id will replace the
1450 // current one to hold the key repeat with repeat count reset.
1451 // In the future when got a KEY_UP on the device id, drop it and do not
1452 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1454 resetKeyRepeatLocked();
1455 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1456 } else {
1457 // Not a repeat. Save key down state in case we do see a repeat later.
1458 resetKeyRepeatLocked();
1459 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1460 }
1461 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001462 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1463 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001464 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001465 if (DEBUG_INBOUND_EVENT_DETAILS) {
1466 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1467 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 resetKeyRepeatLocked();
1470 }
1471
1472 if (entry->repeatCount == 1) {
1473 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1474 } else {
1475 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1476 }
1477
1478 entry->dispatchInProgress = true;
1479
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 }
1482
1483 // Handle case where the policy asked us to try again later last time.
1484 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1485 if (currentTime < entry->interceptKeyWakeupTime) {
1486 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1487 *nextWakeupTime = entry->interceptKeyWakeupTime;
1488 }
1489 return false; // wait until next wakeup
1490 }
1491 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1492 entry->interceptKeyWakeupTime = 0;
1493 }
1494
1495 // Give the policy a chance to intercept the key.
1496 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1497 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001498 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001499 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001500
1501 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1502 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1503 };
1504 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return false; // wait for the command to run
1506 } else {
1507 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1508 }
1509 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001510 if (*dropReason == DropReason::NOT_DROPPED) {
1511 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513 }
1514
1515 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001516 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001517 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1519 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001520 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 return true;
1522 }
1523
1524 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001525 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001526 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001527 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001528 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 return false;
1530 }
1531
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001532 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001533 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 return true;
1535 }
1536
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001537 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539
1540 // Dispatch the key.
1541 dispatchEventLocked(currentTime, entry, inputTargets);
1542 return true;
1543}
1544
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001545void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001546 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1547 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1548 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1549 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1550 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1551 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1552 entry.metaState, entry.repeatCount, entry.downTime);
1553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554}
1555
Prabir Pradhancef936d2021-07-21 16:17:52 +00001556void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1557 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001558 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001559 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1560 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1561 "source=0x%x, sensorType=%s",
1562 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1563 NamedEnum::string(entry->sensorType).c_str());
1564 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001565 auto command = [this, entry]() REQUIRES(mLock) {
1566 scoped_unlock unlock(mLock);
1567
1568 if (entry->accuracyChanged) {
1569 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1570 }
1571 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1572 entry->hwTimestamp, entry->values);
1573 };
1574 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001575}
1576
1577bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001578 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1579 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1580 NamedEnum::string(sensorType).c_str());
1581 }
Chris Yef59a2f42020-10-16 12:55:26 -07001582 { // acquire lock
1583 std::scoped_lock _l(mLock);
1584
1585 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1586 std::shared_ptr<EventEntry> entry = *it;
1587 if (entry->type == EventEntry::Type::SENSOR) {
1588 it = mInboundQueue.erase(it);
1589 releaseInboundEventLocked(entry);
1590 }
1591 }
1592 }
1593 return true;
1594}
1595
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001596bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001598 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001600 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 entry->dispatchInProgress = true;
1602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
1605
1606 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001607 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001608 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001609 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1610 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 return true;
1612 }
1613
1614 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1615
1616 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001617 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618
1619 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 if (isPointerEvent) {
1622 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001623 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001624 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001625 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 } else {
1627 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001628 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001629 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001631 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 return false;
1633 }
1634
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001635 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001636 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001637 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1638 return true;
1639 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001641 CancelationOptions::Mode mode(isPointerEvent
1642 ? CancelationOptions::CANCEL_POINTER_EVENTS
1643 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1644 CancelationOptions options(mode, "input event injection failed");
1645 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 return true;
1647 }
1648
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001649 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 // Dispatch the motion.
1653 if (conflictingPointerActions) {
1654 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 synthesizeCancelationEventsForAllConnectionsLocked(options);
1657 }
1658 dispatchEventLocked(currentTime, entry, inputTargets);
1659 return true;
1660}
1661
chaviw98318de2021-05-19 16:45:23 -05001662void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001663 bool isExiting, const MotionEntry& motionEntry) {
1664 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1665 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1666 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1667 PointerCoords pointerCoords;
1668 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1669 pointerCoords.transform(windowHandle->getInfo()->transform);
1670
1671 std::unique_ptr<DragEntry> dragEntry =
1672 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1673 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1674 pointerCoords.getY());
1675
1676 enqueueInboundEventLocked(std::move(dragEntry));
1677}
1678
1679void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1680 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1681 if (channel == nullptr) {
1682 return; // Window has gone away
1683 }
1684 InputTarget target;
1685 target.inputChannel = channel;
1686 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1687 entry->dispatchInProgress = true;
1688 dispatchEventLocked(currentTime, entry, {target});
1689}
1690
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001691void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001692 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1693 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1694 ", policyFlags=0x%x, "
1695 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1696 "metaState=0x%x, buttonState=0x%x,"
1697 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1698 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1699 entry.policyFlags, entry.action, entry.actionButton, entry.flags, entry.metaState,
1700 entry.buttonState, entry.edgeFlags, entry.xPrecision, entry.yPrecision,
1701 entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001703 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1704 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1705 "x=%f, y=%f, pressure=%f, size=%f, "
1706 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1707 "orientation=%f",
1708 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1709 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1710 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1711 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1712 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1713 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1714 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1717 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720}
1721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001722void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1723 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001724 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001725 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001726 if (DEBUG_DISPATCH_CYCLE) {
1727 ALOGD("dispatchEventToCurrentInputTargets");
1728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001730 updateInteractionTokensLocked(*eventEntry, inputTargets);
1731
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001736 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001737 sp<Connection> connection =
1738 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001739 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001740 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001742 if (DEBUG_FOCUS) {
1743 ALOGD("Dropping event delivery to target with channel '%s' because it "
1744 "is no longer registered with the input dispatcher.",
1745 inputTarget.inputChannel->getName().c_str());
1746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 }
1748 }
1749}
1750
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001751void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1752 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1753 // If the policy decides to close the app, we will get a channel removal event via
1754 // unregisterInputChannel, and will clean up the connection that way. We are already not
1755 // sending new pointers to the connection when it blocked, but focused events will continue to
1756 // pile up.
1757 ALOGW("Canceling events for %s because it is unresponsive",
1758 connection->inputChannel->getName().c_str());
1759 if (connection->status == Connection::STATUS_NORMAL) {
1760 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1761 "application not responding");
1762 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 }
1764}
1765
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001767 if (DEBUG_FOCUS) {
1768 ALOGD("Resetting ANR timeouts.");
1769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770
1771 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001773 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774}
1775
Tiger Huang721e26f2018-07-24 22:26:19 +08001776/**
1777 * Get the display id that the given event should go to. If this event specifies a valid display id,
1778 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1779 * Focused display is the display that the user most recently interacted with.
1780 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001781int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001782 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001783 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001784 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001785 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1786 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 break;
1788 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001789 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1791 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001792 break;
1793 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001794 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001795 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001796 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001797 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001798 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001799 case EventEntry::Type::SENSOR:
1800 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001801 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001802 return ADISPLAY_ID_NONE;
1803 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001804 }
1805 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1806}
1807
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001808bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1809 const char* focusedWindowName) {
1810 if (mAnrTracker.empty()) {
1811 // already processed all events that we waited for
1812 mKeyIsWaitingForEventsTimeout = std::nullopt;
1813 return false;
1814 }
1815
1816 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1817 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001818 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001819 mKeyIsWaitingForEventsTimeout = currentTime +
1820 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1821 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822 return true;
1823 }
1824
1825 // We still have pending events, and already started the timer
1826 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1827 return true; // Still waiting
1828 }
1829
1830 // Waited too long, and some connection still hasn't processed all motions
1831 // Just send the key to the focused window
1832 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1833 focusedWindowName);
1834 mKeyIsWaitingForEventsTimeout = std::nullopt;
1835 return false;
1836}
1837
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001838InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1839 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1840 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842
Tiger Huang721e26f2018-07-24 22:26:19 +08001843 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001844 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001845 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001846 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1847
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 // If there is no currently focused window and no focused application
1849 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1851 ALOGI("Dropping %s event because there is no focused window or focused application in "
1852 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001853 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001854 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 }
1856
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001857 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1858 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1859 // start interacting with another application via touch (app switch). This code can be removed
1860 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1861 // an app is expected to have a focused window.
1862 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1863 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1864 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001865 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1866 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1867 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001868 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001869 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001870 ALOGW("Waiting because no window has focus but %s may eventually add a "
1871 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001872 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001873 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001875 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1876 // Already raised ANR. Drop the event
1877 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001878 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001880 } else {
1881 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001882 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001883 }
1884 }
1885
1886 // we have a valid, non-null focused window
1887 resetNoFocusedWindowTimeoutLocked();
1888
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001890 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001891 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 }
1893
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 if (focusedWindowHandle->getInfo()->paused) {
1895 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001896 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001897 }
1898
1899 // If the event is a key event, then we must wait for all previous events to
1900 // complete before delivering it because previous events may have the
1901 // side-effect of transferring focus to a different window and we want to
1902 // ensure that the following keys are sent to the new window.
1903 //
1904 // Suppose the user touches a button in a window then immediately presses "A".
1905 // If the button causes a pop-up window to appear then we want to ensure that
1906 // the "A" key is delivered to the new pop-up window. This is because users
1907 // often anticipate pending UI changes when typing on a keyboard.
1908 // To obtain this behavior, we must serialize key events with respect to all
1909 // prior input events.
1910 if (entry.type == EventEntry::Type::KEY) {
1911 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1912 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001913 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 }
1916
1917 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001918 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001919 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1920 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
1922 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001923 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924}
1925
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001926/**
1927 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1928 * that are currently unresponsive.
1929 */
1930std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1931 const std::vector<TouchedMonitor>& monitors) const {
1932 std::vector<TouchedMonitor> responsiveMonitors;
1933 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1934 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1935 sp<Connection> connection = getConnectionLocked(
1936 monitor.monitor.inputChannel->getConnectionToken());
1937 if (connection == nullptr) {
1938 ALOGE("Could not find connection for monitor %s",
1939 monitor.monitor.inputChannel->getName().c_str());
1940 return false;
1941 }
1942 if (!connection->responsive) {
1943 ALOGW("Unresponsive monitor %s will not get the new gesture",
1944 connection->inputChannel->getName().c_str());
1945 return false;
1946 }
1947 return true;
1948 });
1949 return responsiveMonitors;
1950}
1951
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001952InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1953 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1954 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001955 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 enum InjectionPermission {
1957 INJECTION_PERMISSION_UNKNOWN,
1958 INJECTION_PERMISSION_GRANTED,
1959 INJECTION_PERMISSION_DENIED
1960 };
1961
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 // For security reasons, we defer updating the touch state until we are sure that
1963 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001964 int32_t displayId = entry.displayId;
1965 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1967
1968 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001971 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1972 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001974 // Copy current touch state into tempTouchState.
1975 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1976 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001977 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001978 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001979 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1980 mTouchStatesByDisplay.find(displayId);
1981 if (oldStateIt != mTouchStatesByDisplay.end()) {
1982 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001983 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001984 }
1985
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 bool isSplit = tempTouchState.split;
1987 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1988 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1989 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001990 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1991 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1992 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1993 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1994 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001995 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 bool wrongDevice = false;
1997 if (newGesture) {
1998 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002000 ALOGI("Dropping event because a pointer for a different device is already down "
2001 "in display %" PRId32,
2002 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002003 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002004 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 switchedDevice = false;
2006 wrongDevice = true;
2007 goto Failed;
2008 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002009 tempTouchState.reset();
2010 tempTouchState.down = down;
2011 tempTouchState.deviceId = entry.deviceId;
2012 tempTouchState.source = entry.source;
2013 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002015 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002016 ALOGI("Dropping move event because a pointer for a different device is already active "
2017 "in display %" PRId32,
2018 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002019 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002020 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002021 switchedDevice = false;
2022 wrongDevice = true;
2023 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
2025
2026 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2027 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2028
Garfield Tan00f511d2019-06-12 16:55:40 -07002029 int32_t x;
2030 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002032 // Always dispatch mouse events to cursor position.
2033 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 x = int32_t(entry.xCursorPosition);
2035 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002036 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002037 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2038 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002039 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002040 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002041 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2042 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002043
2044 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002045 ? findTouchedGestureMonitorsLocked(displayId)
Michael Wright3dd60e22019-03-27 22:06:44 +00002046 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002049 if (newTouchedWindowHandle != nullptr &&
2050 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002051 // New window supports splitting, but we should never split mouse events.
2052 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 } else if (isSplit) {
2054 // New window does not support splitting but we have already split events.
2055 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002056 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058
2059 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002060 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002062 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 }
2064
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002065 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2066 ALOGI("Not sending touch event to %s because it is paused",
2067 newTouchedWindowHandle->getName().c_str());
2068 newTouchedWindowHandle = nullptr;
2069 }
2070
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002071 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002073 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2074 if (!isResponsive) {
2075 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002076 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2077 newTouchedWindowHandle = nullptr;
2078 }
2079 }
2080
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002081 // Drop events that can't be trusted due to occlusion
2082 if (newTouchedWindowHandle != nullptr &&
2083 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2084 TouchOcclusionInfo occlusionInfo =
2085 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002086 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002087 if (DEBUG_TOUCH_OCCLUSION) {
2088 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2089 for (const auto& log : occlusionInfo.debugInfo) {
2090 ALOGD("%s", log.c_str());
2091 }
2092 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002093 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002094 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2095 ALOGW("Dropping untrusted touch event due to %s/%d",
2096 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2097 newTouchedWindowHandle = nullptr;
2098 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002099 }
2100 }
2101
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002102 // Also don't send the new touch event to unresponsive gesture monitors
2103 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2104
Michael Wright3dd60e22019-03-27 22:06:44 +00002105 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2106 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002107 "(%d, %d) in display %" PRId32 ".",
2108 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002109 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002110 goto Failed;
2111 }
2112
2113 if (newTouchedWindowHandle != nullptr) {
2114 // Set target flags.
2115 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2116 if (isSplit) {
2117 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2120 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2121 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2122 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2123 }
2124
2125 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002126 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2127 newHoverWindowHandle = nullptr;
2128 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002129 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002130 }
2131
2132 // Update the temporary touch state.
2133 BitSet32 pointerIds;
2134 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002135 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002136 pointerIds.markBit(pointerId);
2137 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002138 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 }
2140
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002141 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 } else {
2143 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2144
2145 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002146 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002147 if (DEBUG_FOCUS) {
2148 ALOGD("Dropping event because the pointer is not down or we previously "
2149 "dropped the pointer down event in display %" PRId32,
2150 displayId);
2151 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002152 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 goto Failed;
2154 }
2155
arthurhung6d4bed92021-03-17 11:59:33 +08002156 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002157
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002159 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002160 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002161 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2162 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163
chaviw98318de2021-05-19 16:45:23 -05002164 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002165 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002166 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002167 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2168 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002169 if (DEBUG_FOCUS) {
2170 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2171 oldTouchedWindowHandle->getName().c_str(),
2172 newTouchedWindowHandle->getName().c_str(), displayId);
2173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002175 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2176 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2177 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178
2179 // Make a slippery entrance into the new window.
2180 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2181 isSplit = true;
2182 }
2183
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 int32_t targetFlags =
2185 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 if (isSplit) {
2187 targetFlags |= InputTarget::FLAG_SPLIT;
2188 }
2189 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2190 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002191 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2192 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
2194
2195 BitSet32 pointerIds;
2196 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002197 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002199 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201 }
2202 }
2203
2204 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002205 // Let the previous window know that the hover sequence is over, unless we already did it
2206 // when dispatching it as is to newTouchedWindowHandle.
2207 if (mLastHoverWindowHandle != nullptr &&
2208 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2209 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002210 if (DEBUG_HOVER) {
2211 ALOGD("Sending hover exit event to window %s.",
2212 mLastHoverWindowHandle->getName().c_str());
2213 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002214 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2215 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217
Garfield Tandf26e862020-07-01 20:18:19 -07002218 // Let the new window know that the hover sequence is starting, unless we already did it
2219 // when dispatching it as is to newTouchedWindowHandle.
2220 if (newHoverWindowHandle != nullptr &&
2221 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2222 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002223 if (DEBUG_HOVER) {
2224 ALOGD("Sending hover enter event to window %s.",
2225 newHoverWindowHandle->getName().c_str());
2226 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2228 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2229 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231 }
2232
2233 // Check permission to inject into all touched foreground windows and ensure there
2234 // is at least one touched foreground window.
2235 {
2236 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2239 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002240 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002241 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 injectionPermission = INJECTION_PERMISSION_DENIED;
2243 goto Failed;
2244 }
2245 }
2246 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002248 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002249 ALOGI("Dropping event because there is no touched foreground window in display "
2250 "%" PRId32 " or gesture monitor to receive it.",
2251 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002252 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 goto Failed;
2254 }
2255
2256 // Permission granted to injection into all touched foreground windows.
2257 injectionPermission = INJECTION_PERMISSION_GRANTED;
2258 }
2259
2260 // Check whether windows listening for outside touches are owned by the same UID. If it is
2261 // set the policy flag that we will not reveal coordinate information to this window.
2262 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002263 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002264 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002265 if (foregroundWindowHandle) {
2266 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002269 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2270 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2271 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 InputTarget::FLAG_ZERO_COORDS,
2273 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276 }
2277 }
2278 }
2279
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 // If this is the first pointer going down and the touched window has a wallpaper
2281 // then also add the touched wallpaper windows so they are locked in for the duration
2282 // of the touch gesture.
2283 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2284 // engine only supports touch events. We would need to add a mechanism similar
2285 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2286 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002287 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002289 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002290 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002291 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002292 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2293 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002294 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002295 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002296 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 .addOrUpdateWindow(windowHandle,
2298 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2299 InputTarget::
2300 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2301 InputTarget::FLAG_DISPATCH_AS_IS,
2302 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 }
2304 }
2305 }
2306 }
2307
2308 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002309 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002313 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002316 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002317 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002319 }
2320
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // Drop the outside or hover touch windows since we will not care about them
2322 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002323 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324
2325Failed:
2326 // Check injection permission once and for all.
2327 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 injectionPermission = INJECTION_PERMISSION_GRANTED;
2330 } else {
2331 injectionPermission = INJECTION_PERMISSION_DENIED;
2332 }
2333 }
2334
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002335 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2336 return injectionResult;
2337 }
2338
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002340 if (!wrongDevice) {
2341 if (switchedDevice) {
2342 if (DEBUG_FOCUS) {
2343 ALOGD("Conflicting pointer actions: Switched to a different device.");
2344 }
2345 *outConflictingPointerActions = true;
2346 }
2347
2348 if (isHoverAction) {
2349 // Started hovering, therefore no longer down.
2350 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002351 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002352 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2353 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 *outConflictingPointerActions = true;
2356 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002357 tempTouchState.reset();
2358 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2359 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2360 tempTouchState.deviceId = entry.deviceId;
2361 tempTouchState.source = entry.source;
2362 tempTouchState.displayId = displayId;
2363 }
2364 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2365 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2366 // All pointers up or canceled.
2367 tempTouchState.reset();
2368 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2369 // First pointer went down.
2370 if (oldState && oldState->down) {
2371 if (DEBUG_FOCUS) {
2372 ALOGD("Conflicting pointer actions: Down received while already down.");
2373 }
2374 *outConflictingPointerActions = true;
2375 }
2376 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2377 // One pointer went up.
2378 if (isSplit) {
2379 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2380 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002382 for (size_t i = 0; i < tempTouchState.windows.size();) {
2383 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2384 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2385 touchedWindow.pointerIds.clearBit(pointerId);
2386 if (touchedWindow.pointerIds.isEmpty()) {
2387 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2388 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002391 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002393 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002395
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002396 // Save changes unless the action was scroll in which case the temporary touch
2397 // state was only valid for this one action.
2398 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2399 if (tempTouchState.displayId >= 0) {
2400 mTouchStatesByDisplay[displayId] = tempTouchState;
2401 } else {
2402 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002406 // Update hover state.
2407 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 return injectionResult;
2411}
2412
arthurhung6d4bed92021-03-17 11:59:33 +08002413void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002414 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002415 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002416 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002417 if (dropWindow) {
2418 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002419 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002420 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002421 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002422 }
2423 mDragState.reset();
2424}
2425
2426void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2427 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002428 return;
2429 }
2430
arthurhung6d4bed92021-03-17 11:59:33 +08002431 if (!mDragState->isStartDrag) {
2432 mDragState->isStartDrag = true;
2433 mDragState->isStylusButtonDownAtStart =
2434 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2435 }
2436
arthurhungb89ccb02020-12-30 16:19:01 +08002437 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2438 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2439 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2440 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002441 // Handle the special case : stylus button no longer pressed.
2442 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2443 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2444 finishDragAndDrop(entry.displayId, x, y);
2445 return;
2446 }
2447
chaviw98318de2021-05-19 16:45:23 -05002448 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002449 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002450 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002451 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002452 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2453 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2454 if (mDragState->dragHoverWindowHandle != nullptr) {
2455 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2456 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002457 }
arthurhung6d4bed92021-03-17 11:59:33 +08002458 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002459 }
2460 // enqueue drag location if needed.
2461 if (hoverWindowHandle != nullptr) {
2462 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2463 }
arthurhung6d4bed92021-03-17 11:59:33 +08002464 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2465 finishDragAndDrop(entry.displayId, x, y);
2466 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002467 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002468 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002469 }
2470}
2471
chaviw98318de2021-05-19 16:45:23 -05002472void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 int32_t targetFlags, BitSet32 pointerIds,
2474 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002475 std::vector<InputTarget>::iterator it =
2476 std::find_if(inputTargets.begin(), inputTargets.end(),
2477 [&windowHandle](const InputTarget& inputTarget) {
2478 return inputTarget.inputChannel->getConnectionToken() ==
2479 windowHandle->getToken();
2480 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002481
chaviw98318de2021-05-19 16:45:23 -05002482 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002483
2484 if (it == inputTargets.end()) {
2485 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002486 std::shared_ptr<InputChannel> inputChannel =
2487 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002488 if (inputChannel == nullptr) {
2489 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2490 return;
2491 }
2492 inputTarget.inputChannel = inputChannel;
2493 inputTarget.flags = targetFlags;
2494 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky09576692021-07-01 12:22:09 -07002495 inputTarget.displayOrientation = windowInfo->displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -07002496 inputTarget.displaySize =
Evan Rosky44edce92021-05-14 18:09:55 -07002497 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002498 inputTargets.push_back(inputTarget);
2499 it = inputTargets.end() - 1;
2500 }
2501
2502 ALOG_ASSERT(it->flags == targetFlags);
2503 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2504
chaviw1ff3d1e2020-07-01 15:53:47 -07002505 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506}
2507
Michael Wright3dd60e22019-03-27 22:06:44 +00002508void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 int32_t displayId, float xOffset,
2510 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002511 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2512 mGlobalMonitorsByDisplay.find(displayId);
2513
2514 if (it != mGlobalMonitorsByDisplay.end()) {
2515 const std::vector<Monitor>& monitors = it->second;
2516 for (const Monitor& monitor : monitors) {
2517 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
2520}
2521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2523 float yOffset,
2524 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002525 InputTarget target;
2526 target.inputChannel = monitor.inputChannel;
2527 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002528 ui::Transform t;
2529 t.set(xOffset, yOffset);
2530 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002531 inputTargets.push_back(target);
2532}
2533
chaviw98318de2021-05-19 16:45:23 -05002534bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 const InjectionState* injectionState) {
2536 if (injectionState &&
2537 (windowHandle == nullptr ||
2538 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2539 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002540 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 "owned by uid %d",
2543 injectionState->injectorPid, injectionState->injectorUid,
2544 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 } else {
2546 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549 return false;
2550 }
2551 return true;
2552}
2553
Robert Carrc9bf1d32020-04-13 17:21:08 -07002554/**
2555 * Indicate whether one window handle should be considered as obscuring
2556 * another window handle. We only check a few preconditions. Actually
2557 * checking the bounds is left to the caller.
2558 */
chaviw98318de2021-05-19 16:45:23 -05002559static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2560 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002561 // Compare by token so cloned layers aren't counted
2562 if (haveSameToken(windowHandle, otherHandle)) {
2563 return false;
2564 }
2565 auto info = windowHandle->getInfo();
2566 auto otherInfo = otherHandle->getInfo();
2567 if (!otherInfo->visible) {
2568 return false;
chaviw98318de2021-05-19 16:45:23 -05002569 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002570 // Those act as if they were invisible, so we don't need to flag them.
2571 // We do want to potentially flag touchable windows even if they have 0
2572 // opacity, since they can consume touches and alter the effects of the
2573 // user interaction (eg. apps that rely on
2574 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2575 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2576 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002577 } else if (info->ownerUid == otherInfo->ownerUid) {
2578 // If ownerUid is the same we don't generate occlusion events as there
2579 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002580 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002581 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002582 return false;
2583 } else if (otherInfo->displayId != info->displayId) {
2584 return false;
2585 }
2586 return true;
2587}
2588
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002589/**
2590 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2591 * untrusted, one should check:
2592 *
2593 * 1. If result.hasBlockingOcclusion is true.
2594 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2595 * BLOCK_UNTRUSTED.
2596 *
2597 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2598 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2599 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2600 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2601 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2602 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2603 *
2604 * If neither of those is true, then it means the touch can be allowed.
2605 */
2606InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002607 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2608 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002609 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002610 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002611 TouchOcclusionInfo info;
2612 info.hasBlockingOcclusion = false;
2613 info.obscuringOpacity = 0;
2614 info.obscuringUid = -1;
2615 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002616 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002617 if (windowHandle == otherHandle) {
2618 break; // All future windows are below us. Exit early.
2619 }
chaviw98318de2021-05-19 16:45:23 -05002620 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002621 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2622 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002623 if (DEBUG_TOUCH_OCCLUSION) {
2624 info.debugInfo.push_back(
2625 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2626 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002627 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2628 // we perform the checks below to see if the touch can be propagated or not based on the
2629 // window's touch occlusion mode
2630 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2631 info.hasBlockingOcclusion = true;
2632 info.obscuringUid = otherInfo->ownerUid;
2633 info.obscuringPackage = otherInfo->packageName;
2634 break;
2635 }
2636 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2637 uint32_t uid = otherInfo->ownerUid;
2638 float opacity =
2639 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2640 // Given windows A and B:
2641 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2642 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2643 opacityByUid[uid] = opacity;
2644 if (opacity > info.obscuringOpacity) {
2645 info.obscuringOpacity = opacity;
2646 info.obscuringUid = uid;
2647 info.obscuringPackage = otherInfo->packageName;
2648 }
2649 }
2650 }
2651 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002652 if (DEBUG_TOUCH_OCCLUSION) {
2653 info.debugInfo.push_back(
2654 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2655 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002656 return info;
2657}
2658
chaviw98318de2021-05-19 16:45:23 -05002659std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002660 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002661 return StringPrintf(INDENT2
2662 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2663 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2664 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2665 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002666 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002667 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002668 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002669 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2670 info->frameTop, info->frameRight, info->frameBottom,
2671 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002672 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2673 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2674 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002675}
2676
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002677bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2678 if (occlusionInfo.hasBlockingOcclusion) {
2679 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2680 occlusionInfo.obscuringUid);
2681 return false;
2682 }
2683 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2684 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2685 "%.2f, maximum allowed = %.2f)",
2686 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2687 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2688 return false;
2689 }
2690 return true;
2691}
2692
chaviw98318de2021-05-19 16:45:23 -05002693bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002694 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002696 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2697 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002698 if (windowHandle == otherHandle) {
2699 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 }
chaviw98318de2021-05-19 16:45:23 -05002701 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002702 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002703 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 return true;
2705 }
2706 }
2707 return false;
2708}
2709
chaviw98318de2021-05-19 16:45:23 -05002710bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002711 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002712 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2713 const WindowInfo* windowInfo = windowHandle->getInfo();
2714 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002715 if (windowHandle == otherHandle) {
2716 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002717 }
chaviw98318de2021-05-19 16:45:23 -05002718 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002719 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002720 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002721 return true;
2722 }
2723 }
2724 return false;
2725}
2726
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002727std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002728 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002729 if (applicationHandle != nullptr) {
2730 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002731 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 } else {
2733 return applicationHandle->getName();
2734 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002735 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002736 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002738 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
2740}
2741
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002742void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002743 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002744 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2745 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002746 // Focus or pointer capture changed events are passed to apps, but do not represent user
2747 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002748 return;
2749 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002750 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002751 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002752 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002753 const WindowInfo* info = focusedWindowHandle->getInfo();
2754 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002755 if (DEBUG_DISPATCH_CYCLE) {
2756 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 return;
2759 }
2760 }
2761
2762 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002763 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002764 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002765 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2766 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002767 return;
2768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002770 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771 eventType = USER_ACTIVITY_EVENT_TOUCH;
2772 }
2773 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002775 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002776 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2777 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 return;
2779 }
2780 eventType = USER_ACTIVITY_EVENT_BUTTON;
2781 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07002783 case EventEntry::Type::TOUCH_MODE_CHANGED: {
2784 break;
2785 }
2786
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002787 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002788 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002789 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002790 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002791 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2792 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002793 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002794 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002795 break;
2796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 }
2798
Prabir Pradhancef936d2021-07-21 16:17:52 +00002799 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2800 REQUIRES(mLock) {
2801 scoped_unlock unlock(mLock);
2802 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2803 };
2804 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805}
2806
2807void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002809 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002810 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002811 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002813 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002814 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002815 ATRACE_NAME(message.c_str());
2816 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002817 if (DEBUG_DISPATCH_CYCLE) {
2818 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2819 "globalScaleFactor=%f, pointerIds=0x%x %s",
2820 connection->getInputChannelName().c_str(), inputTarget.flags,
2821 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2822 inputTarget.getPointerInfoString().c_str());
2823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824
2825 // Skip this event if the connection status is not normal.
2826 // We don't want to enqueue additional outbound events if the connection is broken.
2827 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002828 if (DEBUG_DISPATCH_CYCLE) {
2829 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2830 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 return;
2833 }
2834
2835 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002836 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2837 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2838 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002839 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002841 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002842 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002843 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002844 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 if (!splitMotionEntry) {
2846 return; // split event was dropped
2847 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002848 if (DEBUG_FOCUS) {
2849 ALOGD("channel '%s' ~ Split motion event.",
2850 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002851 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002852 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002853 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2854 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 return;
2856 }
2857 }
2858
2859 // Not splitting. Enqueue dispatch entries for the event as is.
2860 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2861}
2862
2863void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002865 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002866 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002867 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002868 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002869 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002870 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002871 ATRACE_NAME(message.c_str());
2872 }
2873
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002874 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875
2876 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002877 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002879 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002880 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002881 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002883 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002885 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002887 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889
2890 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002891 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 startDispatchCycleLocked(currentTime, connection);
2893 }
2894}
2895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002897 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002898 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002900 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2902 connection->getInputChannelName().c_str(),
2903 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002904 ATRACE_NAME(message.c_str());
2905 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002906 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 if (!(inputTargetFlags & dispatchMode)) {
2908 return;
2909 }
2910 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2911
2912 // This is a new event.
2913 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002914 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002915 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002917 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2918 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002919 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002921 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002922 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002923 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002924 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002925 dispatchEntry->resolvedAction = keyEntry.action;
2926 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2929 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002930 if (DEBUG_DISPATCH_CYCLE) {
2931 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2932 "event",
2933 connection->getInputChannelName().c_str());
2934 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 return; // skip the inconsistent event
2936 }
2937 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002940 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002941 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002942 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2943 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2944 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2945 static_cast<int32_t>(IdGenerator::Source::OTHER);
2946 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2948 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2949 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2950 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2951 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2952 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2953 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2954 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2955 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2956 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2957 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002959 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 }
2961 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002962 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2963 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002964 if (DEBUG_DISPATCH_CYCLE) {
2965 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2966 "enter event",
2967 connection->getInputChannelName().c_str());
2968 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002969 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2970 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002974 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002975 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2976 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2977 }
2978 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2979 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2983 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002984 if (DEBUG_DISPATCH_CYCLE) {
2985 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2986 "event",
2987 connection->getInputChannelName().c_str());
2988 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 return; // skip the inconsistent event
2990 }
2991
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002992 dispatchEntry->resolvedEventId =
2993 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2994 ? mIdGenerator.nextId()
2995 : motionEntry.id;
2996 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2997 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2998 ") to MotionEvent(id=0x%" PRIx32 ").",
2999 motionEntry.id, dispatchEntry->resolvedEventId);
3000 ATRACE_NAME(message.c_str());
3001 }
3002
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003003 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3004 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3005 // Skip reporting pointer down outside focus to the policy.
3006 break;
3007 }
3008
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003009 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003010 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011
3012 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003014 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003015 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003016 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3017 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003018 break;
3019 }
Chris Yef59a2f42020-10-16 12:55:26 -07003020 case EventEntry::Type::SENSOR: {
3021 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3022 break;
3023 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003024 case EventEntry::Type::CONFIGURATION_CHANGED:
3025 case EventEntry::Type::DEVICE_RESET: {
3026 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07003027 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003028 break;
3029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 }
3031
3032 // Remember that we are waiting for this dispatch to complete.
3033 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003034 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 }
3036
3037 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003038 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003039 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003040}
3041
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003042/**
3043 * This function is purely for debugging. It helps us understand where the user interaction
3044 * was taking place. For example, if user is touching launcher, we will see a log that user
3045 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3046 * We will see both launcher and wallpaper in that list.
3047 * Once the interaction with a particular set of connections starts, no new logs will be printed
3048 * until the set of interacted connections changes.
3049 *
3050 * The following items are skipped, to reduce the logspam:
3051 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3052 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3053 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3054 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3055 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003056 */
3057void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3058 const std::vector<InputTarget>& targets) {
3059 // Skip ACTION_UP events, and all events other than keys and motions
3060 if (entry.type == EventEntry::Type::KEY) {
3061 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3062 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3063 return;
3064 }
3065 } else if (entry.type == EventEntry::Type::MOTION) {
3066 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3067 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3068 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3069 return;
3070 }
3071 } else {
3072 return; // Not a key or a motion
3073 }
3074
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003075 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003076 std::vector<sp<Connection>> newConnections;
3077 for (const InputTarget& target : targets) {
3078 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3079 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3080 continue; // Skip windows that receive ACTION_OUTSIDE
3081 }
3082
3083 sp<IBinder> token = target.inputChannel->getConnectionToken();
3084 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003085 if (connection == nullptr) {
3086 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003087 }
3088 newConnectionTokens.insert(std::move(token));
3089 newConnections.emplace_back(connection);
3090 }
3091 if (newConnectionTokens == mInteractionConnectionTokens) {
3092 return; // no change
3093 }
3094 mInteractionConnectionTokens = newConnectionTokens;
3095
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003096 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003097 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003098 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003099 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003100 std::string message = "Interaction with: " + targetList;
3101 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003102 message += "<none>";
3103 }
3104 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3105}
3106
chaviwfd6d3512019-03-25 13:23:49 -07003107void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003108 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003109 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003110 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3111 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003112 return;
3113 }
3114
Vishnu Nairc519ff72021-01-21 08:23:08 -08003115 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003116 if (focusedToken == token) {
3117 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003118 return;
3119 }
3120
Prabir Pradhancef936d2021-07-21 16:17:52 +00003121 auto command = [this, token]() REQUIRES(mLock) {
3122 scoped_unlock unlock(mLock);
3123 mPolicy->onPointerDownOutsideFocus(token);
3124 };
3125 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126}
3127
3128void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003130 if (ATRACE_ENABLED()) {
3131 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003133 ATRACE_NAME(message.c_str());
3134 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003135 if (DEBUG_DISPATCH_CYCLE) {
3136 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003139 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3140 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003142 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003143 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003144 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145
3146 // Publish the event.
3147 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003148 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3149 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003150 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003151 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3152 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003155 status = connection->inputPublisher
3156 .publishKeyEvent(dispatchEntry->seq,
3157 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3158 keyEntry.source, keyEntry.displayId,
3159 std::move(hmac), dispatchEntry->resolvedAction,
3160 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3161 keyEntry.scanCode, keyEntry.metaState,
3162 keyEntry.repeatCount, keyEntry.downTime,
3163 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003167 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003168 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172
chaviw82357092020-01-28 13:13:06 -08003173 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003174 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3176 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003177 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003178 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3179 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003180 // Don't apply window scale here since we don't want scale to affect raw
3181 // coordinates. The scale will be sent back to the client and applied
3182 // later when requesting relative coordinates.
3183 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3184 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185 }
3186 usingCoords = scaledCoords;
3187 }
3188 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 // We don't want the dispatch target to know.
3190 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003191 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 scaledCoords[i].clear();
3193 }
3194 usingCoords = scaledCoords;
3195 }
3196 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003197
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003198 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199
3200 // Publish the motion event.
3201 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003202 .publishMotionEvent(dispatchEntry->seq,
3203 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 motionEntry.deviceId, motionEntry.source,
3205 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003206 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003207 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003209 motionEntry.edgeFlags, motionEntry.metaState,
3210 motionEntry.buttonState,
3211 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003212 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003213 motionEntry.xPrecision, motionEntry.yPrecision,
3214 motionEntry.xCursorPosition,
3215 motionEntry.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003216 dispatchEntry->displayOrientation,
Evan Rosky84f07f02021-04-16 10:42:42 -07003217 dispatchEntry->displaySize.x,
3218 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003219 motionEntry.downTime, motionEntry.eventTime,
3220 motionEntry.pointerCount,
3221 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 break;
3223 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003224
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003225 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003226 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003227 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003228 focusEntry.id,
3229 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003230 mInTouchMode);
3231 break;
3232 }
3233
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003234 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3235 const TouchModeEntry& touchModeEntry =
3236 static_cast<const TouchModeEntry&>(eventEntry);
3237 status = connection->inputPublisher
3238 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3239 touchModeEntry.inTouchMode);
3240
3241 break;
3242 }
3243
Prabir Pradhan99987712020-11-10 18:43:05 -08003244 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3245 const auto& captureEntry =
3246 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3247 status = connection->inputPublisher
3248 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3249 captureEntry.pointerCaptureEnabled);
3250 break;
3251 }
3252
arthurhungb89ccb02020-12-30 16:19:01 +08003253 case EventEntry::Type::DRAG: {
3254 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3255 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3256 dragEntry.id, dragEntry.x,
3257 dragEntry.y,
3258 dragEntry.isExiting);
3259 break;
3260 }
3261
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003262 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003263 case EventEntry::Type::DEVICE_RESET:
3264 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003265 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003266 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
3270
3271 // Check the result.
3272 if (status) {
3273 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003274 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276 "This is unexpected because the wait queue is empty, so the pipe "
3277 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003278 "event to it, status=%s(%d)",
3279 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3280 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3282 } else {
3283 // Pipe is full and we are waiting for the app to finish process some events
3284 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003285 if (DEBUG_DISPATCH_CYCLE) {
3286 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3287 "waiting for the application to catch up",
3288 connection->getInputChannelName().c_str());
3289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 }
3291 } else {
3292 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003293 "status=%s(%d)",
3294 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3295 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3297 }
3298 return;
3299 }
3300
3301 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003302 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3303 connection->outboundQueue.end(),
3304 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003305 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003306 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003307 if (connection->responsive) {
3308 mAnrTracker.insert(dispatchEntry->timeoutTime,
3309 connection->inputChannel->getConnectionToken());
3310 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003311 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
3313}
3314
chaviw09c8d2d2020-08-24 15:48:26 -07003315std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3316 size_t size;
3317 switch (event.type) {
3318 case VerifiedInputEvent::Type::KEY: {
3319 size = sizeof(VerifiedKeyEvent);
3320 break;
3321 }
3322 case VerifiedInputEvent::Type::MOTION: {
3323 size = sizeof(VerifiedMotionEvent);
3324 break;
3325 }
3326 }
3327 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3328 return mHmacKeyManager.sign(start, size);
3329}
3330
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003331const std::array<uint8_t, 32> InputDispatcher::getSignature(
3332 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3333 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3334 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3335 // Only sign events up and down events as the purely move events
3336 // are tied to their up/down counterparts so signing would be redundant.
3337 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3338 verifiedEvent.actionMasked = actionMasked;
3339 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003340 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003341 }
3342 return INVALID_HMAC;
3343}
3344
3345const std::array<uint8_t, 32> InputDispatcher::getSignature(
3346 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3347 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3348 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3349 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003350 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003351}
3352
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003355 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003356 if (DEBUG_DISPATCH_CYCLE) {
3357 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3358 connection->getInputChannelName().c_str(), seq, toString(handled));
3359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 if (connection->status == Connection::STATUS_BROKEN ||
3362 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 return;
3364 }
3365
3366 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003367 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3368 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3369 };
3370 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371}
3372
3373void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 const sp<Connection>& connection,
3375 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003376 if (DEBUG_DISPATCH_CYCLE) {
3377 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3378 connection->getInputChannelName().c_str(), toString(notify));
3379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
3381 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003382 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003383 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003384 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003385 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386
3387 // The connection appears to be unrecoverably broken.
3388 // Ignore already broken or zombie connections.
3389 if (connection->status == Connection::STATUS_NORMAL) {
3390 connection->status = Connection::STATUS_BROKEN;
3391
3392 if (notify) {
3393 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003394 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3395 connection->getInputChannelName().c_str());
3396
3397 auto command = [this, connection]() REQUIRES(mLock) {
3398 if (connection->status == Connection::STATUS_ZOMBIE) return;
3399 scoped_unlock unlock(mLock);
3400 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3401 };
3402 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
3404 }
3405}
3406
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003407void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3408 while (!queue.empty()) {
3409 DispatchEntry* dispatchEntry = queue.front();
3410 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003411 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 }
3413}
3414
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003415void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003417 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 }
3419 delete dispatchEntry;
3420}
3421
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003422int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3423 std::scoped_lock _l(mLock);
3424 sp<Connection> connection = getConnectionLocked(connectionToken);
3425 if (connection == nullptr) {
3426 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3427 connectionToken.get(), events);
3428 return 0; // remove the callback
3429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003431 bool notify;
3432 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3433 if (!(events & ALOOPER_EVENT_INPUT)) {
3434 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3435 "events=0x%x",
3436 connection->getInputChannelName().c_str(), events);
3437 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 }
3439
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003440 nsecs_t currentTime = now();
3441 bool gotOne = false;
3442 status_t status = OK;
3443 for (;;) {
3444 Result<InputPublisher::ConsumerResponse> result =
3445 connection->inputPublisher.receiveConsumerResponse();
3446 if (!result.ok()) {
3447 status = result.error().code();
3448 break;
3449 }
3450
3451 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3452 const InputPublisher::Finished& finish =
3453 std::get<InputPublisher::Finished>(*result);
3454 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3455 finish.consumeTime);
3456 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003457 if (shouldReportMetricsForConnection(*connection)) {
3458 const InputPublisher::Timeline& timeline =
3459 std::get<InputPublisher::Timeline>(*result);
3460 mLatencyTracker
3461 .trackGraphicsLatency(timeline.inputEventId,
3462 connection->inputChannel->getConnectionToken(),
3463 std::move(timeline.graphicsTimeline));
3464 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003465 }
3466 gotOne = true;
3467 }
3468 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003469 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003470 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 return 1;
3472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 }
3474
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003475 notify = status != DEAD_OBJECT || !connection->monitor;
3476 if (notify) {
3477 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3478 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3479 status);
3480 }
3481 } else {
3482 // Monitor channels are never explicitly unregistered.
3483 // We do it automatically when the remote endpoint is closed so don't warn about them.
3484 const bool stillHaveWindowHandle =
3485 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3486 notify = !connection->monitor && stillHaveWindowHandle;
3487 if (notify) {
3488 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3489 connection->getInputChannelName().c_str(), events);
3490 }
3491 }
3492
3493 // Remove the channel.
3494 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3495 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496}
3497
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003500 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003501 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
3503}
3504
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003505void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003506 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003507 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3508 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3509}
3510
3511void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3512 const CancelationOptions& options,
3513 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3514 for (const auto& it : monitorsByDisplay) {
3515 const std::vector<Monitor>& monitors = it.second;
3516 for (const Monitor& monitor : monitors) {
3517 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003518 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003519 }
3520}
3521
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003523 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003524 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003525 if (connection == nullptr) {
3526 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003528
3529 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530}
3531
3532void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3533 const sp<Connection>& connection, const CancelationOptions& options) {
3534 if (connection->status == Connection::STATUS_BROKEN) {
3535 return;
3536 }
3537
3538 nsecs_t currentTime = now();
3539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003540 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003541 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003543 if (cancelationEvents.empty()) {
3544 return;
3545 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003546 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3547 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3548 "with reality: %s, mode=%d.",
3549 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3550 options.mode);
3551 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003552
3553 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003554 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003555 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3556 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003557 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003558 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003559 target.globalScaleFactor = windowInfo->globalScaleFactor;
3560 }
3561 target.inputChannel = connection->inputChannel;
3562 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3563
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003564 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003565 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003566 switch (cancelationEventEntry->type) {
3567 case EventEntry::Type::KEY: {
3568 logOutboundKeyDetails("cancel - ",
3569 static_cast<const KeyEntry&>(*cancelationEventEntry));
3570 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003572 case EventEntry::Type::MOTION: {
3573 logOutboundMotionDetails("cancel - ",
3574 static_cast<const MotionEntry&>(*cancelationEventEntry));
3575 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003577 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003578 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003579 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3580 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003581 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003582 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003583 break;
3584 }
3585 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003586 case EventEntry::Type::DEVICE_RESET:
3587 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003588 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003589 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003590 break;
3591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 }
3593
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003594 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3595 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003597
3598 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599}
3600
Svet Ganov5d3bc372020-01-26 23:11:07 -08003601void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3602 const sp<Connection>& connection) {
3603 if (connection->status == Connection::STATUS_BROKEN) {
3604 return;
3605 }
3606
3607 nsecs_t currentTime = now();
3608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003609 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003610 connection->inputState.synthesizePointerDownEvents(currentTime);
3611
3612 if (downEvents.empty()) {
3613 return;
3614 }
3615
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003616 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003617 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3618 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003619 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003620
3621 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003622 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3624 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003625 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003626 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003627 target.globalScaleFactor = windowInfo->globalScaleFactor;
3628 }
3629 target.inputChannel = connection->inputChannel;
3630 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3631
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003633 switch (downEventEntry->type) {
3634 case EventEntry::Type::MOTION: {
3635 logOutboundMotionDetails("down - ",
3636 static_cast<const MotionEntry&>(*downEventEntry));
3637 break;
3638 }
3639
3640 case EventEntry::Type::KEY:
3641 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003642 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003643 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003644 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003645 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003646 case EventEntry::Type::SENSOR:
3647 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003648 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003649 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003650 break;
3651 }
3652 }
3653
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003654 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3655 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003656 }
3657
3658 startDispatchCycleLocked(currentTime, connection);
3659}
3660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003661std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3662 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 ALOG_ASSERT(pointerIds.value != 0);
3664
3665 uint32_t splitPointerIndexMap[MAX_POINTERS];
3666 PointerProperties splitPointerProperties[MAX_POINTERS];
3667 PointerCoords splitPointerCoords[MAX_POINTERS];
3668
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003669 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 uint32_t splitPointerCount = 0;
3671
3672 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003673 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003675 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 uint32_t pointerId = uint32_t(pointerProperties.id);
3677 if (pointerIds.hasBit(pointerId)) {
3678 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3679 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3680 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003681 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 splitPointerCount += 1;
3683 }
3684 }
3685
3686 if (splitPointerCount != pointerIds.count()) {
3687 // This is bad. We are missing some of the pointers that we expected to deliver.
3688 // Most likely this indicates that we received an ACTION_MOVE events that has
3689 // different pointer ids than we expected based on the previous ACTION_DOWN
3690 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3691 // in this way.
3692 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003693 "we expected there to be %d pointers. This probably means we received "
3694 "a broken sequence of pointer ids from the input device.",
3695 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003696 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003699 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003701 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3702 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3704 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003705 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 uint32_t pointerId = uint32_t(pointerProperties.id);
3707 if (pointerIds.hasBit(pointerId)) {
3708 if (pointerIds.count() == 1) {
3709 // The first/last pointer went down/up.
3710 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003711 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003712 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3713 ? AMOTION_EVENT_ACTION_CANCEL
3714 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 } else {
3716 // A secondary pointer went down/up.
3717 uint32_t splitPointerIndex = 0;
3718 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3719 splitPointerIndex += 1;
3720 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721 action = maskedAction |
3722 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 }
3724 } else {
3725 // An unrelated pointer changed.
3726 action = AMOTION_EVENT_ACTION_MOVE;
3727 }
3728 }
3729
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003730 int32_t newId = mIdGenerator.nextId();
3731 if (ATRACE_ENABLED()) {
3732 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3733 ") to MotionEvent(id=0x%" PRIx32 ").",
3734 originalMotionEntry.id, newId);
3735 ATRACE_NAME(message.c_str());
3736 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003737 std::unique_ptr<MotionEntry> splitMotionEntry =
3738 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3739 originalMotionEntry.deviceId, originalMotionEntry.source,
3740 originalMotionEntry.displayId,
3741 originalMotionEntry.policyFlags, action,
3742 originalMotionEntry.actionButton,
3743 originalMotionEntry.flags, originalMotionEntry.metaState,
3744 originalMotionEntry.buttonState,
3745 originalMotionEntry.classification,
3746 originalMotionEntry.edgeFlags,
3747 originalMotionEntry.xPrecision,
3748 originalMotionEntry.yPrecision,
3749 originalMotionEntry.xCursorPosition,
3750 originalMotionEntry.yCursorPosition,
3751 originalMotionEntry.downTime, splitPointerCount,
3752 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003754 if (originalMotionEntry.injectionState) {
3755 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 splitMotionEntry->injectionState->refCount += 1;
3757 }
3758
3759 return splitMotionEntry;
3760}
3761
3762void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003763 if (DEBUG_INBOUND_EVENT_DETAILS) {
3764 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766
3767 bool needWake;
3768 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003769 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003771 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3772 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3773 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 } // release lock
3775
3776 if (needWake) {
3777 mLooper->wake();
3778 }
3779}
3780
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003781/**
3782 * If one of the meta shortcuts is detected, process them here:
3783 * Meta + Backspace -> generate BACK
3784 * Meta + Enter -> generate HOME
3785 * This will potentially overwrite keyCode and metaState.
3786 */
3787void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003789 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3790 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3791 if (keyCode == AKEYCODE_DEL) {
3792 newKeyCode = AKEYCODE_BACK;
3793 } else if (keyCode == AKEYCODE_ENTER) {
3794 newKeyCode = AKEYCODE_HOME;
3795 }
3796 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003797 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003798 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003799 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003800 keyCode = newKeyCode;
3801 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3802 }
3803 } else if (action == AKEY_EVENT_ACTION_UP) {
3804 // In order to maintain a consistent stream of up and down events, check to see if the key
3805 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3806 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003807 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003808 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003809 auto replacementIt = mReplacedKeys.find(replacement);
3810 if (replacementIt != mReplacedKeys.end()) {
3811 keyCode = replacementIt->second;
3812 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003813 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3814 }
3815 }
3816}
3817
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003819 if (DEBUG_INBOUND_EVENT_DETAILS) {
3820 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3821 "policyFlags=0x%x, action=0x%x, "
3822 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3823 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3824 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3825 args->downTime);
3826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 if (!validateKeyEvent(args->action)) {
3828 return;
3829 }
3830
3831 uint32_t policyFlags = args->policyFlags;
3832 int32_t flags = args->flags;
3833 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003834 // InputDispatcher tracks and generates key repeats on behalf of
3835 // whatever notifies it, so repeatCount should always be set to 0
3836 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3838 policyFlags |= POLICY_FLAG_VIRTUAL;
3839 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 if (policyFlags & POLICY_FLAG_FUNCTION) {
3842 metaState |= AMETA_FUNCTION_ON;
3843 }
3844
3845 policyFlags |= POLICY_FLAG_TRUSTED;
3846
Michael Wright78f24442014-08-06 15:55:28 -07003847 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003848 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003849
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003851 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003852 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3853 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854
Michael Wright2b3c3302018-03-02 17:19:13 +00003855 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003857 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3858 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003859 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 bool needWake;
3863 { // acquire lock
3864 mLock.lock();
3865
3866 if (shouldSendKeyToInputFilterLocked(args)) {
3867 mLock.unlock();
3868
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003869 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3871 return; // event was consumed by the filter
3872 }
3873
3874 mLock.lock();
3875 }
3876
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003877 std::unique_ptr<KeyEntry> newEntry =
3878 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3879 args->displayId, policyFlags, args->action, flags,
3880 keyCode, args->scanCode, metaState, repeatCount,
3881 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003883 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 mLock.unlock();
3885 } // release lock
3886
3887 if (needWake) {
3888 mLooper->wake();
3889 }
3890}
3891
3892bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3893 return mInputFilterEnabled;
3894}
3895
3896void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003897 if (DEBUG_INBOUND_EVENT_DETAILS) {
3898 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3899 "displayId=%" PRId32 ", policyFlags=0x%x, "
3900 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3901 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3902 "yCursorPosition=%f, downTime=%" PRId64,
3903 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3904 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3905 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3906 args->xCursorPosition, args->yCursorPosition, args->downTime);
3907 for (uint32_t i = 0; i < args->pointerCount; i++) {
3908 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3909 "x=%f, y=%f, pressure=%f, size=%f, "
3910 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3911 "orientation=%f",
3912 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3913 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3914 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3915 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3916 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3917 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3918 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3919 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3920 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3921 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003924 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3925 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 return;
3927 }
3928
3929 uint32_t policyFlags = args->policyFlags;
3930 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003931
3932 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003933 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003934 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3935 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
3939 bool needWake;
3940 { // acquire lock
3941 mLock.lock();
3942
3943 if (shouldSendMotionToInputFilterLocked(args)) {
3944 mLock.unlock();
3945
3946 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003947 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003948 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3949 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003950 args->metaState, args->buttonState, args->classification, transform,
3951 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07003952 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3953 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3954 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
3956 policyFlags |= POLICY_FLAG_FILTERED;
3957 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3958 return; // event was consumed by the filter
3959 }
3960
3961 mLock.lock();
3962 }
3963
3964 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003965 std::unique_ptr<MotionEntry> newEntry =
3966 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3967 args->source, args->displayId, policyFlags,
3968 args->action, args->actionButton, args->flags,
3969 args->metaState, args->buttonState,
3970 args->classification, args->edgeFlags,
3971 args->xPrecision, args->yPrecision,
3972 args->xCursorPosition, args->yCursorPosition,
3973 args->downTime, args->pointerCount,
3974 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003976 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3977 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3978 !mInputFilterEnabled) {
3979 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3980 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3981 }
3982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003983 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 mLock.unlock();
3985 } // release lock
3986
3987 if (needWake) {
3988 mLooper->wake();
3989 }
3990}
3991
Chris Yef59a2f42020-10-16 12:55:26 -07003992void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003993 if (DEBUG_INBOUND_EVENT_DETAILS) {
3994 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3995 " sensorType=%s",
3996 args->id, args->eventTime, args->deviceId, args->source,
3997 NamedEnum::string(args->sensorType).c_str());
3998 }
Chris Yef59a2f42020-10-16 12:55:26 -07003999
4000 bool needWake;
4001 { // acquire lock
4002 mLock.lock();
4003
4004 // Just enqueue a new sensor event.
4005 std::unique_ptr<SensorEntry> newEntry =
4006 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4007 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4008 args->sensorType, args->accuracy,
4009 args->accuracyChanged, args->values);
4010
4011 needWake = enqueueInboundEventLocked(std::move(newEntry));
4012 mLock.unlock();
4013 } // release lock
4014
4015 if (needWake) {
4016 mLooper->wake();
4017 }
4018}
4019
Chris Yefb552902021-02-03 17:18:37 -08004020void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 if (DEBUG_INBOUND_EVENT_DETAILS) {
4022 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4023 args->deviceId, args->isOn);
4024 }
Chris Yefb552902021-02-03 17:18:37 -08004025 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4026}
4027
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004029 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030}
4031
4032void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004033 if (DEBUG_INBOUND_EVENT_DETAILS) {
4034 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4035 "switchMask=0x%08x",
4036 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038
4039 uint32_t policyFlags = args->policyFlags;
4040 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042}
4043
4044void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004045 if (DEBUG_INBOUND_EVENT_DETAILS) {
4046 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4047 args->deviceId);
4048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049
4050 bool needWake;
4051 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004052 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004054 std::unique_ptr<DeviceResetEntry> newEntry =
4055 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4056 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 } // release lock
4058
4059 if (needWake) {
4060 mLooper->wake();
4061 }
4062}
4063
Prabir Pradhan7e186182020-11-10 13:56:45 -08004064void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004065 if (DEBUG_INBOUND_EVENT_DETAILS) {
4066 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
4067 args->enabled ? "true" : "false");
4068 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004069
Prabir Pradhan99987712020-11-10 18:43:05 -08004070 bool needWake;
4071 { // acquire lock
4072 std::scoped_lock _l(mLock);
4073 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4074 args->enabled);
4075 needWake = enqueueInboundEventLocked(std::move(entry));
4076 } // release lock
4077
4078 if (needWake) {
4079 mLooper->wake();
4080 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004081}
4082
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004083InputEventInjectionResult InputDispatcher::injectInputEvent(
4084 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4085 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 if (DEBUG_INBOUND_EVENT_DETAILS) {
4087 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4088 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4089 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4090 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004091 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092
4093 policyFlags |= POLICY_FLAG_INJECTED;
4094 if (hasInjectionPermission(injectorPid, injectorUid)) {
4095 policyFlags |= POLICY_FLAG_TRUSTED;
4096 }
4097
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004098 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004099 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4100 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4101 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4102 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4103 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004104 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004105 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004106 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004107 }
4108
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004109 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004111 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004112 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4113 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004114 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004115 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004118 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004119 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4120 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4121 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004122 int32_t keyCode = incomingKey.getKeyCode();
4123 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004124 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004126 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004127 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004128 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4129 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4130 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4133 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004134 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135
4136 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4137 android::base::Timer t;
4138 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4139 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4140 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4141 std::to_string(t.duration().count()).c_str());
4142 }
4143 }
4144
4145 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 std::unique_ptr<KeyEntry> injectedEntry =
4147 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004148 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004149 incomingKey.getDisplayId(), policyFlags, action,
4150 flags, keyCode, incomingKey.getScanCode(), metaState,
4151 incomingKey.getRepeatCount(),
4152 incomingKey.getDownTime());
4153 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
4156
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004158 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4159 int32_t action = motionEvent.getAction();
4160 size_t pointerCount = motionEvent.getPointerCount();
4161 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4162 int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004163 int32_t flags = motionEvent.getFlags();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004164 int32_t displayId = motionEvent.getDisplayId();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004166 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 }
4168
4169 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004170 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 android::base::Timer t;
4172 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4173 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4174 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4175 std::to_string(t.duration().count()).c_str());
4176 }
4177 }
4178
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004179 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4180 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4181 }
4182
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004184 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4185 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004186 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004187 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4188 resolvedDeviceId, motionEvent.getSource(),
4189 motionEvent.getDisplayId(), policyFlags, action,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004190 actionButton, flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004191 motionEvent.getButtonState(),
4192 motionEvent.getClassification(),
4193 motionEvent.getEdgeFlags(),
4194 motionEvent.getXPrecision(),
4195 motionEvent.getYPrecision(),
4196 motionEvent.getRawXCursorPosition(),
4197 motionEvent.getRawYCursorPosition(),
4198 motionEvent.getDownTime(), uint32_t(pointerCount),
4199 pointerProperties, samplePointerCoords,
4200 motionEvent.getXOffset(),
4201 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004202 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004203 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 sampleEventTimes += 1;
4205 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004206 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004207 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4208 resolvedDeviceId, motionEvent.getSource(),
4209 motionEvent.getDisplayId(), policyFlags,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004210 action, actionButton, flags,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004211 motionEvent.getMetaState(),
4212 motionEvent.getButtonState(),
4213 motionEvent.getClassification(),
4214 motionEvent.getEdgeFlags(),
4215 motionEvent.getXPrecision(),
4216 motionEvent.getYPrecision(),
4217 motionEvent.getRawXCursorPosition(),
4218 motionEvent.getRawYCursorPosition(),
4219 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004220 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004221 samplePointerCoords, motionEvent.getXOffset(),
4222 motionEvent.getYOffset());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004223 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 }
4225 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004229 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004230 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232
4233 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004234 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 injectionState->injectionIsAsync = true;
4236 }
4237
4238 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004239 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
4241 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004242 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004243 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004244 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 }
4246
4247 mLock.unlock();
4248
4249 if (needWake) {
4250 mLooper->wake();
4251 }
4252
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004253 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004255 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004257 if (syncMode == InputEventInjectionSync::NONE) {
4258 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 } else {
4260 for (;;) {
4261 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004262 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 break;
4264 }
4265
4266 nsecs_t remainingTimeout = endTime - now();
4267 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004268 if (DEBUG_INJECTION) {
4269 ALOGD("injectInputEvent - Timed out waiting for injection result "
4270 "to become available.");
4271 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004272 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 break;
4274 }
4275
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004276 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004279 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4280 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004282 if (DEBUG_INJECTION) {
4283 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4284 injectionState->pendingForegroundDispatches);
4285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 nsecs_t remainingTimeout = endTime - now();
4287 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004288 if (DEBUG_INJECTION) {
4289 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4290 "dispatches to finish.");
4291 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 break;
4294 }
4295
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004296 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 }
4298 }
4299 }
4300
4301 injectionState->release();
4302 } // release lock
4303
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004304 if (DEBUG_INJECTION) {
4305 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4306 injectionResult, injectorPid, injectorUid);
4307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
4309 return injectionResult;
4310}
4311
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004312std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004313 std::array<uint8_t, 32> calculatedHmac;
4314 std::unique_ptr<VerifiedInputEvent> result;
4315 switch (event.getType()) {
4316 case AINPUT_EVENT_TYPE_KEY: {
4317 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4318 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4319 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004320 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004321 break;
4322 }
4323 case AINPUT_EVENT_TYPE_MOTION: {
4324 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4325 VerifiedMotionEvent verifiedMotionEvent =
4326 verifiedMotionEventFromMotionEvent(motionEvent);
4327 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004328 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004329 break;
4330 }
4331 default: {
4332 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4333 return nullptr;
4334 }
4335 }
4336 if (calculatedHmac == INVALID_HMAC) {
4337 return nullptr;
4338 }
4339 if (calculatedHmac != event.getHmac()) {
4340 return nullptr;
4341 }
4342 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004343}
4344
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004346 return injectorUid == 0 ||
4347 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348}
4349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004351 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004352 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004354 if (DEBUG_INJECTION) {
4355 ALOGD("Setting input event injection result to %d. "
4356 "injectorPid=%d, injectorUid=%d",
4357 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004360 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 // Log the outcome since the injector did not wait for the injection result.
4362 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 ALOGV("Asynchronous input event injection succeeded.");
4365 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004366 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 ALOGW("Asynchronous input event injection failed.");
4368 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 ALOGW("Asynchronous input event injection permission denied.");
4371 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004373 ALOGW("Asynchronous input event injection timed out.");
4374 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004375 case InputEventInjectionResult::PENDING:
4376 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4377 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 }
4379 }
4380
4381 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004382 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 }
4384}
4385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004386void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4387 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 if (injectionState) {
4389 injectionState->pendingForegroundDispatches += 1;
4390 }
4391}
4392
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004393void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4394 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 if (injectionState) {
4396 injectionState->pendingForegroundDispatches -= 1;
4397
4398 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004399 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 }
4401 }
4402}
4403
chaviw98318de2021-05-19 16:45:23 -05004404const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004405 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004406 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004407 auto it = mWindowHandlesByDisplay.find(displayId);
4408 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004409}
4410
chaviw98318de2021-05-19 16:45:23 -05004411sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004412 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004413 if (windowHandleToken == nullptr) {
4414 return nullptr;
4415 }
4416
Arthur Hungb92218b2018-08-14 12:00:21 +08004417 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004418 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4419 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004420 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004421 return windowHandle;
4422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 }
4424 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004425 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426}
4427
chaviw98318de2021-05-19 16:45:23 -05004428sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4429 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004430 if (windowHandleToken == nullptr) {
4431 return nullptr;
4432 }
4433
chaviw98318de2021-05-19 16:45:23 -05004434 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004435 if (windowHandle->getToken() == windowHandleToken) {
4436 return windowHandle;
4437 }
4438 }
4439 return nullptr;
4440}
4441
chaviw98318de2021-05-19 16:45:23 -05004442sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4443 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004444 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004445 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4446 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004447 if (handle->getId() == windowHandle->getId() &&
4448 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004449 if (windowHandle->getInfo()->displayId != it.first) {
4450 ALOGE("Found window %s in display %" PRId32
4451 ", but it should belong to display %" PRId32,
4452 windowHandle->getName().c_str(), it.first,
4453 windowHandle->getInfo()->displayId);
4454 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004455 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 }
4458 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004459 return nullptr;
4460}
4461
chaviw98318de2021-05-19 16:45:23 -05004462sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004463 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4464 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465}
4466
chaviw98318de2021-05-19 16:45:23 -05004467bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004468 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4469 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004470 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004471 if (connection != nullptr && noInputChannel) {
4472 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4473 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4474 return false;
4475 }
4476
4477 if (connection == nullptr) {
4478 if (!noInputChannel) {
4479 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4480 }
4481 return false;
4482 }
4483 if (!connection->responsive) {
4484 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4485 return false;
4486 }
4487 return true;
4488}
4489
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004490std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4491 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004492 auto connectionIt = mConnectionsByToken.find(token);
4493 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004494 return nullptr;
4495 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004496 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004497}
4498
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004499void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004500 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4501 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004502 // Remove all handles on a display if there are no windows left.
4503 mWindowHandlesByDisplay.erase(displayId);
4504 return;
4505 }
4506
4507 // Since we compare the pointer of input window handles across window updates, we need
4508 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004509 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4510 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4511 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004512 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004513 }
4514
chaviw98318de2021-05-19 16:45:23 -05004515 std::vector<sp<WindowInfoHandle>> newHandles;
4516 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004517 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004518 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004519 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004520 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4521 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4522 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004523 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004524 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004525 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004526 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004527 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004528 }
4529
4530 if (info->displayId != displayId) {
4531 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4532 handle->getName().c_str(), displayId, info->displayId);
4533 continue;
4534 }
4535
Robert Carredd13602020-04-13 17:24:34 -07004536 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4537 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004538 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004539 oldHandle->updateFrom(handle);
4540 newHandles.push_back(oldHandle);
4541 } else {
4542 newHandles.push_back(handle);
4543 }
4544 }
4545
4546 // Insert or replace
4547 mWindowHandlesByDisplay[displayId] = newHandles;
4548}
4549
Arthur Hung72d8dc32020-03-28 00:48:39 +00004550void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004551 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004552 { // acquire lock
4553 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004554 for (const auto& [displayId, handles] : handlesPerDisplay) {
4555 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004556 }
4557 }
4558 // Wake up poll loop since it may need to make new input dispatching choices.
4559 mLooper->wake();
4560}
4561
Arthur Hungb92218b2018-08-14 12:00:21 +08004562/**
4563 * Called from InputManagerService, update window handle list by displayId that can receive input.
4564 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4565 * If set an empty list, remove all handles from the specific display.
4566 * For focused handle, check if need to change and send a cancel event to previous one.
4567 * For removed handle, check if need to send a cancel event if already in touch.
4568 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004569void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004570 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004571 if (DEBUG_FOCUS) {
4572 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004573 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004574 windowList += iwh->getName() + " ";
4575 }
4576 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004579 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004580 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004581 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004582 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004583 if (noInputWindow && window->getToken() != nullptr) {
4584 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4585 window->getName().c_str());
4586 window->releaseChannel();
4587 }
4588 }
4589
Arthur Hung72d8dc32020-03-28 00:48:39 +00004590 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004591 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004593 // Save the old windows' orientation by ID before it gets updated.
4594 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004595 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004596 oldWindowOrientations.emplace(handle->getId(),
4597 handle->getInfo()->transform.getOrientation());
4598 }
4599
chaviw98318de2021-05-19 16:45:23 -05004600 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004601
chaviw98318de2021-05-19 16:45:23 -05004602 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004603 if (mLastHoverWindowHandle &&
4604 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4605 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606 mLastHoverWindowHandle = nullptr;
4607 }
4608
Vishnu Nairc519ff72021-01-21 08:23:08 -08004609 std::optional<FocusResolver::FocusChanges> changes =
4610 mFocusResolver.setInputWindows(displayId, windowHandles);
4611 if (changes) {
4612 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004615 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4616 mTouchStatesByDisplay.find(displayId);
4617 if (stateIt != mTouchStatesByDisplay.end()) {
4618 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619 for (size_t i = 0; i < state.windows.size();) {
4620 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004621 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004622 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004623 ALOGD("Touched window was removed: %s in display %" PRId32,
4624 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004625 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004626 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004627 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4628 if (touchedInputChannel != nullptr) {
4629 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4630 "touched window was removed");
4631 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004633 state.windows.erase(state.windows.begin() + i);
4634 } else {
4635 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 }
4637 }
arthurhungb89ccb02020-12-30 16:19:01 +08004638
arthurhung6d4bed92021-03-17 11:59:33 +08004639 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004640 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004641 if (mDragState &&
4642 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004643 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004644 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004645 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004646 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004647
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004648 if (isPerWindowInputRotationEnabled()) {
4649 // Determine if the orientation of any of the input windows have changed, and cancel all
4650 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004651 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4652 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004653 if (newWindowHandle != nullptr &&
4654 newWindowHandle->getInfo()->transform.getOrientation() !=
4655 oldWindowOrientations[oldWindowHandle->getId()]) {
4656 std::shared_ptr<InputChannel> inputChannel =
4657 getInputChannelLocked(newWindowHandle->getToken());
4658 if (inputChannel != nullptr) {
4659 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4660 "touched window's orientation changed");
4661 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4662 }
4663 }
4664 }
4665 }
4666
Arthur Hung72d8dc32020-03-28 00:48:39 +00004667 // Release information for windows that are no longer present.
4668 // This ensures that unused input channels are released promptly.
4669 // Otherwise, they might stick around until the window handle is destroyed
4670 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004671 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004672 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004673 if (DEBUG_FOCUS) {
4674 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004675 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004676 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004677 // To avoid making too many calls into the compat framework, only
4678 // check for window flags when windows are going away.
4679 // TODO(b/157929241) : delete this. This is only needed temporarily
4680 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004681 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004682 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4683 oldWindowHandle->getName().c_str());
4684 if (mCompatService != nullptr) {
4685 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4686 oldWindowHandle->getInfo()->ownerUid);
4687 }
4688 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004689 }
chaviw291d88a2019-02-14 10:33:58 -08004690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691}
4692
4693void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004694 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004695 if (DEBUG_FOCUS) {
4696 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4697 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4698 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004699 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004700 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004701 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 } // release lock
4703
4704 // Wake up poll loop since it may need to make new input dispatching choices.
4705 mLooper->wake();
4706}
4707
Vishnu Nair599f1412021-06-21 10:39:58 -07004708void InputDispatcher::setFocusedApplicationLocked(
4709 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4710 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4711 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4712
4713 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4714 return; // This application is already focused. No need to wake up or change anything.
4715 }
4716
4717 // Set the new application handle.
4718 if (inputApplicationHandle != nullptr) {
4719 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4720 } else {
4721 mFocusedApplicationHandlesByDisplay.erase(displayId);
4722 }
4723
4724 // No matter what the old focused application was, stop waiting on it because it is
4725 // no longer focused.
4726 resetNoFocusedWindowTimeoutLocked();
4727}
4728
Tiger Huang721e26f2018-07-24 22:26:19 +08004729/**
4730 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4731 * the display not specified.
4732 *
4733 * We track any unreleased events for each window. If a window loses the ability to receive the
4734 * released event, we will send a cancel event to it. So when the focused display is changed, we
4735 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4736 * display. The display-specified events won't be affected.
4737 */
4738void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004739 if (DEBUG_FOCUS) {
4740 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4741 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004742 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004743 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004744
4745 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004746 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004747 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004748 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004749 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004750 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004751 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752 CancelationOptions
4753 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4754 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004755 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004756 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4757 }
4758 }
4759 mFocusedDisplayId = displayId;
4760
Chris Ye3c2d6f52020-08-09 10:39:48 -07004761 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004762 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004763 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004764
Vishnu Nairad321cd2020-08-20 16:40:21 -07004765 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004766 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004767 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004768 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004769 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004770 }
4771 }
4772 }
4773
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004774 if (DEBUG_FOCUS) {
4775 logDispatchStateLocked();
4776 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004777 } // release lock
4778
4779 // Wake up poll loop since it may need to make new input dispatching choices.
4780 mLooper->wake();
4781}
4782
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004784 if (DEBUG_FOCUS) {
4785 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787
4788 bool changed;
4789 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004790 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791
4792 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4793 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 }
4796
4797 if (mDispatchEnabled && !enabled) {
4798 resetAndDropEverythingLocked("dispatcher is being disabled");
4799 }
4800
4801 mDispatchEnabled = enabled;
4802 mDispatchFrozen = frozen;
4803 changed = true;
4804 } else {
4805 changed = false;
4806 }
4807
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004808 if (DEBUG_FOCUS) {
4809 logDispatchStateLocked();
4810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 } // release lock
4812
4813 if (changed) {
4814 // Wake up poll loop since it may need to make new input dispatching choices.
4815 mLooper->wake();
4816 }
4817}
4818
4819void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004820 if (DEBUG_FOCUS) {
4821 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823
4824 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004825 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826
4827 if (mInputFilterEnabled == enabled) {
4828 return;
4829 }
4830
4831 mInputFilterEnabled = enabled;
4832 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4833 } // release lock
4834
4835 // Wake up poll loop since there might be work to do to drop everything.
4836 mLooper->wake();
4837}
4838
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004839void InputDispatcher::setInTouchMode(bool inTouchMode) {
4840 std::scoped_lock lock(mLock);
4841 mInTouchMode = inTouchMode;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004842 // TODO(b/193718270): Fire TouchModeEvent here.
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004843}
4844
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004845void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4846 if (opacity < 0 || opacity > 1) {
4847 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4848 return;
4849 }
4850
4851 std::scoped_lock lock(mLock);
4852 mMaximumObscuringOpacityForTouch = opacity;
4853}
4854
4855void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4856 std::scoped_lock lock(mLock);
4857 mBlockUntrustedTouchesMode = mode;
4858}
4859
arthurhungb89ccb02020-12-30 16:19:01 +08004860bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4861 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004862 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004863 if (DEBUG_FOCUS) {
4864 ALOGD("Trivial transfer to same window.");
4865 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004866 return true;
4867 }
4868
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004870 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871
chaviw98318de2021-05-19 16:45:23 -05004872 sp<WindowInfoHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4873 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004874 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004875 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 return false;
4877 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004878 if (DEBUG_FOCUS) {
4879 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4880 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004883 if (DEBUG_FOCUS) {
4884 ALOGD("Cannot transfer focus because windows are on different displays.");
4885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 return false;
4887 }
4888
4889 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004890 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4891 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004892 for (size_t i = 0; i < state.windows.size(); i++) {
4893 const TouchedWindow& touchedWindow = state.windows[i];
4894 if (touchedWindow.windowHandle == fromWindowHandle) {
4895 int32_t oldTargetFlags = touchedWindow.targetFlags;
4896 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004898 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004900 int32_t newTargetFlags = oldTargetFlags &
4901 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4902 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004903 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904
arthurhungb89ccb02020-12-30 16:19:01 +08004905 // Store the dragging window.
4906 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004907 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004908 }
4909
Jeff Brownf086ddb2014-02-11 14:28:48 -08004910 found = true;
4911 goto Found;
4912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 }
4914 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004915 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004917 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004918 if (DEBUG_FOCUS) {
4919 ALOGD("Focus transfer failed because from window did not have focus.");
4920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 return false;
4922 }
4923
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004924 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4925 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004926 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004927 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004928 CancelationOptions
4929 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4930 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004932 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 }
4934
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004935 if (DEBUG_FOCUS) {
4936 logDispatchStateLocked();
4937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 } // release lock
4939
4940 // Wake up poll loop since it may need to make new input dispatching choices.
4941 mLooper->wake();
4942 return true;
4943}
4944
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004945// Binder call
4946bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4947 sp<IBinder> fromToken;
4948 { // acquire lock
4949 std::scoped_lock _l(mLock);
4950
chaviw98318de2021-05-19 16:45:23 -05004951 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004952 if (toWindowHandle == nullptr) {
4953 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4954 return false;
4955 }
4956
4957 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4958
4959 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4960 if (touchStateIt == mTouchStatesByDisplay.end()) {
4961 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4962 displayId);
4963 return false;
4964 }
4965
4966 TouchState& state = touchStateIt->second;
4967 if (state.windows.size() != 1) {
4968 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4969 state.windows.size());
4970 return false;
4971 }
4972 const TouchedWindow& touchedWindow = state.windows[0];
4973 fromToken = touchedWindow.windowHandle->getToken();
4974 } // release lock
4975
4976 return transferTouchFocus(fromToken, destChannelToken);
4977}
4978
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004980 if (DEBUG_FOCUS) {
4981 ALOGD("Resetting and dropping all events (%s).", reason);
4982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
4984 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4985 synthesizeCancelationEventsForAllConnectionsLocked(options);
4986
4987 resetKeyRepeatLocked();
4988 releasePendingEventLocked();
4989 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004990 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004992 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004993 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004995 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996}
4997
4998void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004999 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 dumpDispatchStateLocked(dump);
5001
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005002 std::istringstream stream(dump);
5003 std::string line;
5004
5005 while (std::getline(stream, line, '\n')) {
5006 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 }
5008}
5009
Prabir Pradhan99987712020-11-10 18:43:05 -08005010std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5011 std::string dump;
5012
5013 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
5014 toString(mFocusedWindowRequestedPointerCapture));
5015
5016 std::string windowName = "None";
5017 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005018 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005019 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5020 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5021 : "token has capture without window";
5022 }
5023 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
5024
5025 return dump;
5026}
5027
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005028void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005029 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5030 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5031 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005032 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033
Tiger Huang721e26f2018-07-24 22:26:19 +08005034 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5035 dump += StringPrintf(INDENT "FocusedApplications:\n");
5036 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5037 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005038 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005039 const std::chrono::duration timeout =
5040 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005042 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005043 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005046 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005048
Vishnu Nairc519ff72021-01-21 08:23:08 -08005049 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005050 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005052 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005053 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005054 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5055 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005056 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005057 state.displayId, toString(state.down), toString(state.split),
5058 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005059 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005060 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005061 for (size_t i = 0; i < state.windows.size(); i++) {
5062 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 dump += StringPrintf(INDENT4
5064 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5065 i, touchedWindow.windowHandle->getName().c_str(),
5066 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005067 }
5068 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005069 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
5072 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005073 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 }
5075
arthurhung6d4bed92021-03-17 11:59:33 +08005076 if (mDragState) {
5077 dump += StringPrintf(INDENT "DragState:\n");
5078 mDragState->dump(dump, INDENT2);
5079 }
5080
Arthur Hungb92218b2018-08-14 12:00:21 +08005081 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005082 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05005083 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08005084 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005085 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005086 dump += INDENT2 "Windows:\n";
5087 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005088 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5089 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005091 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005092 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005093 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005094 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005095 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005096 "applicationInfo.name=%s, "
5097 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005098 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005099 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005100 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005101 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005102 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005103 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005104 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005105 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005106 windowInfo->frameLeft, windowInfo->frameTop,
5107 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005108 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005109 windowInfo->applicationInfo.name.c_str(),
5110 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005111 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005112 dump += StringPrintf(", inputFeatures=%s",
5113 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005114 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005115 "ms, trustedOverlay=%s, hasToken=%s, "
5116 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005117 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005118 millis(windowInfo->dispatchingTimeout),
5119 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005120 toString(windowInfo->token != nullptr),
5121 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005122 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005123 }
5124 } else {
5125 dump += INDENT2 "Windows: <none>\n";
5126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 }
5128 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005129 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131
Michael Wright3dd60e22019-03-27 22:06:44 +00005132 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005133 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005134 const std::vector<Monitor>& monitors = it.second;
5135 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5136 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005137 }
5138 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005139 const std::vector<Monitor>& monitors = it.second;
5140 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5141 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005144 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146
5147 nsecs_t currentTime = now();
5148
5149 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005150 if (!mRecentQueue.empty()) {
5151 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005152 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005153 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005154 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005155 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 }
5157 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005158 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 }
5160
5161 // Dump event currently being dispatched.
5162 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005163 dump += INDENT "PendingEvent:\n";
5164 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005165 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005166 dump += StringPrintf(", age=%" PRId64 "ms\n",
5167 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005169 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171
5172 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005173 if (!mInboundQueue.empty()) {
5174 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005175 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005176 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005177 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005178 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 }
5180 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005181 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 }
5183
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005184 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005185 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005186 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5187 const KeyReplacement& replacement = pair.first;
5188 int32_t newKeyCode = pair.second;
5189 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005190 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005191 }
5192 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005193 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005194 }
5195
Prabir Pradhancef936d2021-07-21 16:17:52 +00005196 if (!mCommandQueue.empty()) {
5197 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5198 } else {
5199 dump += INDENT "CommandQueue: <empty>\n";
5200 }
5201
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005202 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005203 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005204 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005205 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005206 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005207 connection->inputChannel->getFd().get(),
5208 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005209 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005210 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005212 if (!connection->outboundQueue.empty()) {
5213 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5214 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005215 dump += dumpQueue(connection->outboundQueue, currentTime);
5216
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005218 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 }
5220
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005221 if (!connection->waitQueue.empty()) {
5222 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5223 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005224 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005226 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 }
5228 }
5229 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005230 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 }
5232
5233 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005234 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5235 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005237 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 }
5239
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005240 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005241 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5242 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5243 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005244 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005245 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246}
5247
Michael Wright3dd60e22019-03-27 22:06:44 +00005248void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5249 const size_t numMonitors = monitors.size();
5250 for (size_t i = 0; i < numMonitors; i++) {
5251 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005252 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005253 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5254 dump += "\n";
5255 }
5256}
5257
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005258class LooperEventCallback : public LooperCallback {
5259public:
5260 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5261 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5262
5263private:
5264 std::function<int(int events)> mCallback;
5265};
5266
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005267Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005268 if (DEBUG_CHANNEL_CREATION) {
5269 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005272 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005273 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005274 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005275
5276 if (result) {
5277 return base::Error(result) << "Failed to open input channel pair with name " << name;
5278 }
5279
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005281 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005282 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005283 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005284 sp<Connection> connection =
5285 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005287 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5288 ALOGE("Created a new connection, but the token %p is already known", token.get());
5289 }
5290 mConnectionsByToken.emplace(token, connection);
5291
5292 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5293 this, std::placeholders::_1, token);
5294
5295 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 } // release lock
5297
5298 // Wake the looper because some connections have changed.
5299 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005300 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301}
5302
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005303Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5304 bool isGestureMonitor,
5305 const std::string& name,
5306 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005307 std::shared_ptr<InputChannel> serverChannel;
5308 std::unique_ptr<InputChannel> clientChannel;
5309 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5310 if (result) {
5311 return base::Error(result) << "Failed to open input channel pair with name " << name;
5312 }
5313
Michael Wright3dd60e22019-03-27 22:06:44 +00005314 { // acquire lock
5315 std::scoped_lock _l(mLock);
5316
5317 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005318 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5319 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005320 }
5321
Garfield Tan15601662020-09-22 15:32:38 -07005322 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005323 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005324 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005325
5326 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5327 ALOGE("Created a new connection, but the token %p is already known", token.get());
5328 }
5329 mConnectionsByToken.emplace(token, connection);
5330 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5331 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005332
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005333 auto& monitorsByDisplay =
5334 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005335 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005336
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005337 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005338 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5339 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005340 }
Garfield Tan15601662020-09-22 15:32:38 -07005341
Michael Wright3dd60e22019-03-27 22:06:44 +00005342 // Wake the looper because some connections have changed.
5343 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005344 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005345}
5346
Garfield Tan15601662020-09-22 15:32:38 -07005347status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005349 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350
Garfield Tan15601662020-09-22 15:32:38 -07005351 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352 if (status) {
5353 return status;
5354 }
5355 } // release lock
5356
5357 // Wake the poll loop because removing the connection may have changed the current
5358 // synchronization state.
5359 mLooper->wake();
5360 return OK;
5361}
5362
Garfield Tan15601662020-09-22 15:32:38 -07005363status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5364 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005365 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005366 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005367 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 return BAD_VALUE;
5369 }
5370
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005371 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005372
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005374 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 }
5376
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005377 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
5379 nsecs_t currentTime = now();
5380 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5381
5382 connection->status = Connection::STATUS_ZOMBIE;
5383 return OK;
5384}
5385
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005386void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5387 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5388 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005389}
5390
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005391void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005392 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005393 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005394 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 std::vector<Monitor>& monitors = it->second;
5396 const size_t numMonitors = monitors.size();
5397 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005398 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005399 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5400 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005401 monitors.erase(monitors.begin() + i);
5402 break;
5403 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005404 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005405 if (monitors.empty()) {
5406 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005407 } else {
5408 ++it;
5409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 }
5411}
5412
Michael Wright3dd60e22019-03-27 22:06:44 +00005413status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5414 { // acquire lock
5415 std::scoped_lock _l(mLock);
5416 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5417
5418 if (!foundDisplayId) {
5419 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5420 return BAD_VALUE;
5421 }
5422 int32_t displayId = foundDisplayId.value();
5423
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005424 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5425 mTouchStatesByDisplay.find(displayId);
5426 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005427 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5428 return BAD_VALUE;
5429 }
5430
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005431 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005432 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005433 std::optional<int32_t> foundDeviceId;
5434 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005435 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005436 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005437 foundDeviceId = state.deviceId;
5438 }
5439 }
5440 if (!foundDeviceId || !state.down) {
5441 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005442 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005443 return BAD_VALUE;
5444 }
5445 int32_t deviceId = foundDeviceId.value();
5446
5447 // Send cancel events to all the input channels we're stealing from.
5448 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005449 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005450 options.deviceId = deviceId;
5451 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005452 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005453 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005454 std::shared_ptr<InputChannel> channel =
5455 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005456 if (channel != nullptr) {
5457 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005458 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005459 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005460 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005461 canceledWindows += "]";
5462 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5463 canceledWindows.c_str());
5464
Michael Wright3dd60e22019-03-27 22:06:44 +00005465 // Then clear the current touch state so we stop dispatching to them as well.
5466 state.filterNonMonitors();
5467 }
5468 return OK;
5469}
5470
Prabir Pradhan99987712020-11-10 18:43:05 -08005471void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5472 { // acquire lock
5473 std::scoped_lock _l(mLock);
5474 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005475 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005476 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5477 windowHandle != nullptr ? windowHandle->getName().c_str()
5478 : "token without window");
5479 }
5480
Vishnu Nairc519ff72021-01-21 08:23:08 -08005481 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005482 if (focusedToken != windowToken) {
5483 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5484 enabled ? "enable" : "disable");
5485 return;
5486 }
5487
5488 if (enabled == mFocusedWindowRequestedPointerCapture) {
5489 ALOGW("Ignoring request to %s Pointer Capture: "
5490 "window has %s requested pointer capture.",
5491 enabled ? "enable" : "disable", enabled ? "already" : "not");
5492 return;
5493 }
5494
5495 mFocusedWindowRequestedPointerCapture = enabled;
5496 setPointerCaptureLocked(enabled);
5497 } // release lock
5498
5499 // Wake the thread to process command entries.
5500 mLooper->wake();
5501}
5502
Michael Wright3dd60e22019-03-27 22:06:44 +00005503std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5504 const sp<IBinder>& token) {
5505 for (const auto& it : mGestureMonitorsByDisplay) {
5506 const std::vector<Monitor>& monitors = it.second;
5507 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005508 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005509 return it.first;
5510 }
5511 }
5512 }
5513 return std::nullopt;
5514}
5515
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005516std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5517 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5518 if (gesturePid.has_value()) {
5519 return gesturePid;
5520 }
5521 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5522}
5523
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005524sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005525 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005526 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005527 }
5528
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005529 for (const auto& [token, connection] : mConnectionsByToken) {
5530 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005531 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 }
5533 }
Robert Carr4e670e52018-08-15 13:26:12 -07005534
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005535 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536}
5537
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005538std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5539 sp<Connection> connection = getConnectionLocked(connectionToken);
5540 if (connection == nullptr) {
5541 return "<nullptr>";
5542 }
5543 return connection->getInputChannelName();
5544}
5545
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005546void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005548 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005549}
5550
Prabir Pradhancef936d2021-07-21 16:17:52 +00005551void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5552 const sp<Connection>& connection, uint32_t seq,
5553 bool handled, nsecs_t consumeTime) {
5554 // Handle post-event policy actions.
5555 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5556 if (dispatchEntryIt == connection->waitQueue.end()) {
5557 return;
5558 }
5559 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5560 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5561 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5562 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5563 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5564 }
5565 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5566 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5567 connection->inputChannel->getConnectionToken(),
5568 dispatchEntry->deliveryTime, consumeTime, finishTime);
5569 }
5570
5571 bool restartEvent;
5572 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5573 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5574 restartEvent =
5575 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5576 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5577 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5578 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5579 handled);
5580 } else {
5581 restartEvent = false;
5582 }
5583
5584 // Dequeue the event and start the next cycle.
5585 // Because the lock might have been released, it is possible that the
5586 // contents of the wait queue to have been drained, so we need to double-check
5587 // a few things.
5588 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5589 if (dispatchEntryIt != connection->waitQueue.end()) {
5590 dispatchEntry = *dispatchEntryIt;
5591 connection->waitQueue.erase(dispatchEntryIt);
5592 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5593 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5594 if (!connection->responsive) {
5595 connection->responsive = isConnectionResponsive(*connection);
5596 if (connection->responsive) {
5597 // The connection was unresponsive, and now it's responsive.
5598 processConnectionResponsiveLocked(*connection);
5599 }
5600 }
5601 traceWaitQueueLength(*connection);
5602 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5603 connection->outboundQueue.push_front(dispatchEntry);
5604 traceOutboundQueueLength(*connection);
5605 } else {
5606 releaseDispatchEntry(dispatchEntry);
5607 }
5608 }
5609
5610 // Start the next dispatch cycle for this connection.
5611 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612}
5613
Prabir Pradhancef936d2021-07-21 16:17:52 +00005614void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5615 const sp<IBinder>& newToken) {
5616 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5617 scoped_unlock unlock(mLock);
5618 mPolicy->notifyFocusChanged(oldToken, newToken);
5619 };
5620 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621}
5622
Prabir Pradhancef936d2021-07-21 16:17:52 +00005623void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5624 auto command = [this, token, x, y]() REQUIRES(mLock) {
5625 scoped_unlock unlock(mLock);
5626 mPolicy->notifyDropWindow(token, x, y);
5627 };
5628 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005629}
5630
Prabir Pradhancef936d2021-07-21 16:17:52 +00005631void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5632 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5633 scoped_unlock unlock(mLock);
5634 mPolicy->notifyUntrustedTouch(obscuringPackage);
5635 };
5636 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005637}
5638
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005639void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5640 if (connection == nullptr) {
5641 LOG_ALWAYS_FATAL("Caller must check for nullness");
5642 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005643 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5644 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005645 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005646 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005647 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005648 return;
5649 }
5650 /**
5651 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5652 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5653 * has changed. This could cause newer entries to time out before the already dispatched
5654 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5655 * processes the events linearly. So providing information about the oldest entry seems to be
5656 * most useful.
5657 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005658 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005659 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5660 std::string reason =
5661 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005662 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005663 ns2ms(currentWait),
5664 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005665 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005666 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005667
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005668 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5669
5670 // Stop waking up for events on this connection, it is already unresponsive
5671 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672}
5673
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005674void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5675 std::string reason =
5676 StringPrintf("%s does not have a focused window", application->getName().c_str());
5677 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005678
Prabir Pradhancef936d2021-07-21 16:17:52 +00005679 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5680 scoped_unlock unlock(mLock);
5681 mPolicy->notifyNoFocusedWindowAnr(application);
5682 };
5683 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005684}
5685
chaviw98318de2021-05-19 16:45:23 -05005686void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005687 const std::string& reason) {
5688 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5689 updateLastAnrStateLocked(windowLabel, reason);
5690}
5691
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005692void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5693 const std::string& reason) {
5694 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005695 updateLastAnrStateLocked(windowLabel, reason);
5696}
5697
5698void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5699 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005701 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 struct tm tm;
5703 localtime_r(&t, &tm);
5704 char timestr[64];
5705 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005706 mLastAnrState.clear();
5707 mLastAnrState += INDENT "ANR:\n";
5708 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005709 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5710 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005711 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712}
5713
Prabir Pradhancef936d2021-07-21 16:17:52 +00005714void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5715 KeyEntry& entry) {
5716 const KeyEvent event = createKeyEvent(entry);
5717 nsecs_t delay = 0;
5718 { // release lock
5719 scoped_unlock unlock(mLock);
5720 android::base::Timer t;
5721 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5722 entry.policyFlags);
5723 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5724 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5725 std::to_string(t.duration().count()).c_str());
5726 }
5727 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728
5729 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005730 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005731 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005732 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005734 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5735 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737}
5738
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005739void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005740 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5741 scoped_unlock unlock(mLock);
5742 mPolicy->notifyMonitorUnresponsive(pid, reason);
5743 };
5744 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005745}
5746
Prabir Pradhancef936d2021-07-21 16:17:52 +00005747void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005748 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005749 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5750 scoped_unlock unlock(mLock);
5751 mPolicy->notifyWindowUnresponsive(token, reason);
5752 };
5753 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005754}
5755
5756void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005757 auto command = [this, pid]() REQUIRES(mLock) {
5758 scoped_unlock unlock(mLock);
5759 mPolicy->notifyMonitorResponsive(pid);
5760 };
5761 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005762}
5763
Prabir Pradhancef936d2021-07-21 16:17:52 +00005764void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5765 auto command = [this, connectionToken]() REQUIRES(mLock) {
5766 scoped_unlock unlock(mLock);
5767 mPolicy->notifyWindowResponsive(connectionToken);
5768 };
5769 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005770}
5771
5772/**
5773 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5774 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5775 * command entry to the command queue.
5776 */
5777void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5778 std::string reason) {
5779 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5780 if (connection.monitor) {
5781 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5782 reason.c_str());
5783 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5784 if (!pid.has_value()) {
5785 ALOGE("Could not find unresponsive monitor for connection %s",
5786 connection.inputChannel->getName().c_str());
5787 return;
5788 }
5789 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5790 return;
5791 }
5792 // If not a monitor, must be a window
5793 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5794 reason.c_str());
5795 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5796}
5797
5798/**
5799 * Tell the policy that a connection has become responsive so that it can stop ANR.
5800 */
5801void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5802 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5803 if (connection.monitor) {
5804 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5805 if (!pid.has_value()) {
5806 ALOGE("Could not find responsive monitor for connection %s",
5807 connection.inputChannel->getName().c_str());
5808 return;
5809 }
5810 sendMonitorResponsiveCommandLocked(pid.value());
5811 return;
5812 }
5813 // If not a monitor, must be a window
5814 sendWindowResponsiveCommandLocked(connectionToken);
5815}
5816
Prabir Pradhancef936d2021-07-21 16:17:52 +00005817bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005818 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005819 KeyEntry& keyEntry, bool handled) {
5820 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005821 if (!handled) {
5822 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005823 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005824 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005825 return false;
5826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005828 // Get the fallback key state.
5829 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005830 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005831 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005832 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005833 connection->inputState.removeFallbackKey(originalKeyCode);
5834 }
5835
5836 if (handled || !dispatchEntry->hasForegroundTarget()) {
5837 // If the application handles the original key for which we previously
5838 // generated a fallback or if the window is not a foreground window,
5839 // then cancel the associated fallback key, if any.
5840 if (fallbackKeyCode != -1) {
5841 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005842 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5843 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5844 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5845 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5846 keyEntry.policyFlags);
5847 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005848 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005849 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850
5851 mLock.unlock();
5852
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005853 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005854 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855
5856 mLock.lock();
5857
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005858 // Cancel the fallback key.
5859 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005861 "application handled the original non-fallback key "
5862 "or is no longer a foreground target, "
5863 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 options.keyCode = fallbackKeyCode;
5865 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005866 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005867 connection->inputState.removeFallbackKey(originalKeyCode);
5868 }
5869 } else {
5870 // If the application did not handle a non-fallback key, first check
5871 // that we are in a good state to perform unhandled key event processing
5872 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005873 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005874 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005875 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5876 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5877 "since this is not an initial down. "
5878 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5879 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5880 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 return false;
5882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005884 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005885 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5886 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5887 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5888 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5889 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005891
5892 mLock.unlock();
5893
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005894 bool fallback =
5895 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005896 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897
5898 mLock.lock();
5899
5900 if (connection->status != Connection::STATUS_NORMAL) {
5901 connection->inputState.removeFallbackKey(originalKeyCode);
5902 return false;
5903 }
5904
5905 // Latch the fallback keycode for this key on an initial down.
5906 // The fallback keycode cannot change at any other point in the lifecycle.
5907 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005909 fallbackKeyCode = event.getKeyCode();
5910 } else {
5911 fallbackKeyCode = AKEYCODE_UNKNOWN;
5912 }
5913 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5914 }
5915
5916 ALOG_ASSERT(fallbackKeyCode != -1);
5917
5918 // Cancel the fallback key if the policy decides not to send it anymore.
5919 // We will continue to dispatch the key to the policy but we will no
5920 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005921 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5922 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5924 if (fallback) {
5925 ALOGD("Unhandled key event: Policy requested to send key %d"
5926 "as a fallback for %d, but on the DOWN it had requested "
5927 "to send %d instead. Fallback canceled.",
5928 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5929 } else {
5930 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5931 "but on the DOWN it had requested to send %d. "
5932 "Fallback canceled.",
5933 originalKeyCode, fallbackKeyCode);
5934 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005935 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005936
5937 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5938 "canceling fallback, policy no longer desires it");
5939 options.keyCode = fallbackKeyCode;
5940 synthesizeCancelationEventsForConnectionLocked(connection, options);
5941
5942 fallback = false;
5943 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005944 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005945 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005946 }
5947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005949 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5950 {
5951 std::string msg;
5952 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5953 connection->inputState.getFallbackKeys();
5954 for (size_t i = 0; i < fallbackKeys.size(); i++) {
5955 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
5956 }
5957 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
5958 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005960 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961
5962 if (fallback) {
5963 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005964 keyEntry.eventTime = event.getEventTime();
5965 keyEntry.deviceId = event.getDeviceId();
5966 keyEntry.source = event.getSource();
5967 keyEntry.displayId = event.getDisplayId();
5968 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5969 keyEntry.keyCode = fallbackKeyCode;
5970 keyEntry.scanCode = event.getScanCode();
5971 keyEntry.metaState = event.getMetaState();
5972 keyEntry.repeatCount = event.getRepeatCount();
5973 keyEntry.downTime = event.getDownTime();
5974 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005975
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005976 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5977 ALOGD("Unhandled key event: Dispatching fallback key. "
5978 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5979 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
5980 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005981 return true; // restart the event
5982 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005983 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5984 ALOGD("Unhandled key event: No fallback key.");
5985 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005986
5987 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005988 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989 }
5990 }
5991 return false;
5992}
5993
Prabir Pradhancef936d2021-07-21 16:17:52 +00005994bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005995 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005996 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997 return false;
5998}
5999
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000void InputDispatcher::traceInboundQueueLengthLocked() {
6001 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006002 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003 }
6004}
6005
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006006void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007 if (ATRACE_ENABLED()) {
6008 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006009 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6010 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011 }
6012}
6013
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006014void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 if (ATRACE_ENABLED()) {
6016 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006017 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6018 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006019 }
6020}
6021
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006022void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006023 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006025 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 dumpDispatchStateLocked(dump);
6027
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006028 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006029 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006030 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 }
6032}
6033
6034void InputDispatcher::monitor() {
6035 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006036 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006038 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039}
6040
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006041/**
6042 * Wake up the dispatcher and wait until it processes all events and commands.
6043 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6044 * this method can be safely called from any thread, as long as you've ensured that
6045 * the work you are interested in completing has already been queued.
6046 */
6047bool InputDispatcher::waitForIdle() {
6048 /**
6049 * Timeout should represent the longest possible time that a device might spend processing
6050 * events and commands.
6051 */
6052 constexpr std::chrono::duration TIMEOUT = 100ms;
6053 std::unique_lock lock(mLock);
6054 mLooper->wake();
6055 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6056 return result == std::cv_status::no_timeout;
6057}
6058
Vishnu Naire798b472020-07-23 13:52:21 -07006059/**
6060 * Sets focus to the window identified by the token. This must be called
6061 * after updating any input window handles.
6062 *
6063 * Params:
6064 * request.token - input channel token used to identify the window that should gain focus.
6065 * request.focusedToken - the token that the caller expects currently to be focused. If the
6066 * specified token does not match the currently focused window, this request will be dropped.
6067 * If the specified focused token matches the currently focused window, the call will succeed.
6068 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6069 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6070 * when requesting the focus change. This determines which request gets
6071 * precedence if there is a focus change request from another source such as pointer down.
6072 */
Vishnu Nair958da932020-08-21 17:12:37 -07006073void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6074 { // acquire lock
6075 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006076 std::optional<FocusResolver::FocusChanges> changes =
6077 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6078 if (changes) {
6079 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006080 }
6081 } // release lock
6082 // Wake up poll loop since it may need to make new input dispatching choices.
6083 mLooper->wake();
6084}
6085
Vishnu Nairc519ff72021-01-21 08:23:08 -08006086void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6087 if (changes.oldFocus) {
6088 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006089 if (focusedInputChannel) {
6090 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6091 "focus left window");
6092 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006093 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006094 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006095 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006096 if (changes.newFocus) {
6097 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006098 }
6099
Prabir Pradhan99987712020-11-10 18:43:05 -08006100 // If a window has pointer capture, then it must have focus. We need to ensure that this
6101 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6102 // If the window loses focus before it loses pointer capture, then the window can be in a state
6103 // where it has pointer capture but not focus, violating the contract. Therefore we must
6104 // dispatch the pointer capture event before the focus event. Since focus events are added to
6105 // the front of the queue (above), we add the pointer capture event to the front of the queue
6106 // after the focus events are added. This ensures the pointer capture event ends up at the
6107 // front.
6108 disablePointerCaptureForcedLocked();
6109
Vishnu Nairc519ff72021-01-21 08:23:08 -08006110 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006111 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006112 }
6113}
Vishnu Nair958da932020-08-21 17:12:37 -07006114
Prabir Pradhan99987712020-11-10 18:43:05 -08006115void InputDispatcher::disablePointerCaptureForcedLocked() {
6116 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6117 return;
6118 }
6119
6120 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6121
6122 if (mFocusedWindowRequestedPointerCapture) {
6123 mFocusedWindowRequestedPointerCapture = false;
6124 setPointerCaptureLocked(false);
6125 }
6126
6127 if (!mWindowTokenWithPointerCapture) {
6128 // No need to send capture changes because no window has capture.
6129 return;
6130 }
6131
6132 if (mPendingEvent != nullptr) {
6133 // Move the pending event to the front of the queue. This will give the chance
6134 // for the pending event to be dropped if it is a captured event.
6135 mInboundQueue.push_front(mPendingEvent);
6136 mPendingEvent = nullptr;
6137 }
6138
6139 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6140 false /* hasCapture */);
6141 mInboundQueue.push_front(std::move(entry));
6142}
6143
Prabir Pradhan99987712020-11-10 18:43:05 -08006144void InputDispatcher::setPointerCaptureLocked(bool enabled) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006145 auto command = [this, enabled]() REQUIRES(mLock) {
6146 scoped_unlock unlock(mLock);
6147 mPolicy->setPointerCapture(enabled);
6148 };
6149 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006150}
6151
Vishnu Nair599f1412021-06-21 10:39:58 -07006152void InputDispatcher::displayRemoved(int32_t displayId) {
6153 { // acquire lock
6154 std::scoped_lock _l(mLock);
6155 // Set an empty list to remove all handles from the specific display.
6156 setInputWindowsLocked(/* window handles */ {}, displayId);
6157 setFocusedApplicationLocked(displayId, nullptr);
6158 // Call focus resolver to clean up stale requests. This must be called after input windows
6159 // have been removed for the removed display.
6160 mFocusResolver.displayRemoved(displayId);
6161 } // release lock
6162
6163 // Wake up poll loop since it may need to make new input dispatching choices.
6164 mLooper->wake();
6165}
6166
chaviw15fab6f2021-06-07 14:15:52 -05006167void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6168 // The listener sends the windows as a flattened array. Separate the windows by display for
6169 // more convenient parsing.
6170 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6171
6172 for (const auto& info : windowInfos) {
6173 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6174 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6175 }
6176 setInputWindows(handlesPerDisplay);
6177}
6178
Garfield Tane84e6f92019-08-29 17:28:41 -07006179} // namespace android::inputdispatcher