blob: 297074a0b435d4816691094bfae199e348963705 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000031#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010033#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
Michael Wright44753b12020-07-08 13:48:11 +010036#include <cerrno>
37#include <cinttypes>
38#include <climits>
39#include <cstddef>
40#include <ctime>
41#include <queue>
42#include <sstream>
43
44#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070045#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010046
Michael Wrightd02c5b62014-02-10 15:10:22 -080047#define INDENT " "
48#define INDENT2 " "
49#define INDENT3 " "
50#define INDENT4 " "
51
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000053using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080054using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070055using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050056using android::gui::FocusRequest;
57using android::gui::TouchOcclusionMode;
58using android::gui::WindowInfo;
59using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100061using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::InputEventInjectionResult;
63using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Garfield Tane84e6f92019-08-29 17:28:41 -070065namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Prabir Pradhancef936d2021-07-21 16:17:52 +000067namespace {
68
Prabir Pradhan61a5d242021-07-26 16:41:09 +000069// Log detailed debug messages about each inbound event notification to the dispatcher.
70constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
71
72// Log detailed debug messages about each outbound event processed by the dispatcher.
73constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
74
75// Log debug messages about the dispatch cycle.
76constexpr bool DEBUG_DISPATCH_CYCLE = false;
77
78// Log debug messages about channel creation
79constexpr bool DEBUG_CHANNEL_CREATION = false;
80
81// Log debug messages about input event injection.
82constexpr bool DEBUG_INJECTION = false;
83
84// Log debug messages about input focus tracking.
85constexpr bool DEBUG_FOCUS = false;
86
Antonio Kantekf16f2832021-09-28 04:39:20 +000087// Log debug messages about touch mode event
88constexpr bool DEBUG_TOUCH_MODE = false;
89
Prabir Pradhan61a5d242021-07-26 16:41:09 +000090// Log debug messages about touch occlusion
Prabir Pradhan61a5d242021-07-26 16:41:09 +000091constexpr 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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110// Default input dispatching timeout if there is no focused application or paused window
111// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800112const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
113 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
114 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
116// Amount of time to allow for all pending events to be processed when an app switch
117// key is on the way. This is used to preempt input dispatch and drop input events
118// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
121// Amount of time to allow for an event to be dispatched (measured since its eventTime)
122// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000123constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125// 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 +0000126constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
127
128// Log a warning when an interception call takes longer than this to process.
129constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700131// Additional key latency in case a connection is still processing some motion events.
132// This will help with the case when a user touched a button that opens a new window,
133// and gives us the chance to dispatch the key to this new window.
134constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
135
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000137constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
138
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000139// Event log tags. See EventLogTags.logtags for reference
140constexpr int LOGTAG_INPUT_INTERACTION = 62000;
141constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000142constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000143
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000144inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 return systemTime(SYSTEM_TIME_MONOTONIC);
146}
147
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000148inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 return value ? "true" : "false";
150}
151
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000152inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000153 if (binder == nullptr) {
154 return "<null>";
155 }
156 return StringPrintf("%p", binder.get());
157}
158
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000159inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
161 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162}
163
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000164bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AKEY_EVENT_ACTION_DOWN:
167 case AKEY_EVENT_ACTION_UP:
168 return true;
169 default:
170 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 }
172}
173
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000174bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 ALOGE("Key event has invalid action code 0x%x", action);
177 return false;
178 }
179 return true;
180}
181
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000182bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 case AMOTION_EVENT_ACTION_DOWN:
185 case AMOTION_EVENT_ACTION_UP:
186 case AMOTION_EVENT_ACTION_CANCEL:
187 case AMOTION_EVENT_ACTION_MOVE:
188 case AMOTION_EVENT_ACTION_OUTSIDE:
189 case AMOTION_EVENT_ACTION_HOVER_ENTER:
190 case AMOTION_EVENT_ACTION_HOVER_MOVE:
191 case AMOTION_EVENT_ACTION_HOVER_EXIT:
192 case AMOTION_EVENT_ACTION_SCROLL:
193 return true;
194 case AMOTION_EVENT_ACTION_POINTER_DOWN:
195 case AMOTION_EVENT_ACTION_POINTER_UP: {
196 int32_t index = getMotionEventActionPointerIndex(action);
197 return index >= 0 && index < pointerCount;
198 }
199 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
200 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
201 return actionButton != 0;
202 default:
203 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500208 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
209}
210
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000211bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
212 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700213 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 ALOGE("Motion event has invalid action code 0x%x", action);
215 return false;
216 }
217 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800218 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700219 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 return false;
221 }
222 BitSet32 pointerIdBits;
223 for (size_t i = 0; i < pointerCount; i++) {
224 int32_t id = pointerProperties[i].id;
225 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700226 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
227 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 return false;
229 }
230 if (pointerIdBits.hasBit(id)) {
231 ALOGE("Motion event has duplicate pointer id %d", id);
232 return false;
233 }
234 pointerIdBits.markBit(id);
235 }
236 return true;
237}
238
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000239std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000241 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 }
243
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000244 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 bool first = true;
246 Region::const_iterator cur = region.begin();
247 Region::const_iterator const tail = region.end();
248 while (cur != tail) {
249 if (first) {
250 first = false;
251 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800252 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800254 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 cur++;
256 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000257 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258}
259
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000260std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500261 constexpr size_t maxEntries = 50; // max events to print
262 constexpr size_t skipBegin = maxEntries / 2;
263 const size_t skipEnd = queue.size() - maxEntries / 2;
264 // skip from maxEntries / 2 ... size() - maxEntries/2
265 // only print from 0 .. skipBegin and then from skipEnd .. size()
266
267 std::string dump;
268 for (size_t i = 0; i < queue.size(); i++) {
269 const DispatchEntry& entry = *queue[i];
270 if (i >= skipBegin && i < skipEnd) {
271 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
272 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
273 continue;
274 }
275 dump.append(INDENT4);
276 dump += entry.eventEntry->getDescription();
277 dump += StringPrintf(", seq=%" PRIu32
278 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
279 entry.seq, entry.targetFlags, entry.resolvedAction,
280 ns2ms(currentTime - entry.eventEntry->eventTime));
281 if (entry.deliveryTime != 0) {
282 // This entry was delivered, so add information on how long we've been waiting
283 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
284 }
285 dump.append("\n");
286 }
287 return dump;
288}
289
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700290/**
291 * Find the entry in std::unordered_map by key, and return it.
292 * If the entry is not found, return a default constructed entry.
293 *
294 * Useful when the entries are vectors, since an empty vector will be returned
295 * if the entry is not found.
296 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
297 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700298template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000299V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700300 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700301 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800302}
303
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000304bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700305 if (first == second) {
306 return true;
307 }
308
309 if (first == nullptr || second == nullptr) {
310 return false;
311 }
312
313 return first->getToken() == second->getToken();
314}
315
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000316bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000317 if (first == nullptr || second == nullptr) {
318 return false;
319 }
320 return first->applicationInfo.token != nullptr &&
321 first->applicationInfo.token == second->applicationInfo.token;
322}
323
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000324bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800325 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
326}
327
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000328std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
329 std::shared_ptr<EventEntry> eventEntry,
330 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700331 if (inputTarget.useDefaultPointerTransform()) {
332 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700333 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700334 inputTarget.displayTransform,
335 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000336 }
337
338 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
339 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700341 std::vector<PointerCoords> pointerCoords;
342 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000343
344 // Use the first pointer information to normalize all other pointers. This could be any pointer
345 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700346 // uses the transform for the normalized pointer.
347 const ui::Transform& firstPointerTransform =
348 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
349 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350
351 // Iterate through all pointers in the event to normalize against the first.
352 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
353 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
354 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356
357 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700358 // First, apply the current pointer's transform to update the coordinates into
359 // window space.
360 pointerCoords[pointerIndex].transform(currTransform);
361 // Next, apply the inverse transform of the normalized coordinates so the
362 // current coordinates are transformed into the normalized coordinate space.
363 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000364 }
365
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700366 std::unique_ptr<MotionEntry> combinedMotionEntry =
367 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
368 motionEntry.deviceId, motionEntry.source,
369 motionEntry.displayId, motionEntry.policyFlags,
370 motionEntry.action, motionEntry.actionButton,
371 motionEntry.flags, motionEntry.metaState,
372 motionEntry.buttonState, motionEntry.classification,
373 motionEntry.edgeFlags, motionEntry.xPrecision,
374 motionEntry.yPrecision, motionEntry.xCursorPosition,
375 motionEntry.yCursorPosition, motionEntry.downTime,
376 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000377 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000378
379 if (motionEntry.injectionState) {
380 combinedMotionEntry->injectionState = motionEntry.injectionState;
381 combinedMotionEntry->injectionState->refCount += 1;
382 }
383
384 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700385 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700386 firstPointerTransform, inputTarget.displayTransform,
387 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388 return dispatchEntry;
389}
390
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000391status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
392 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700393 std::unique_ptr<InputChannel> uniqueServerChannel;
394 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
395
396 serverChannel = std::move(uniqueServerChannel);
397 return result;
398}
399
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500400template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000401bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500402 if (lhs == nullptr && rhs == nullptr) {
403 return true;
404 }
405 if (lhs == nullptr || rhs == nullptr) {
406 return false;
407 }
408 return *lhs == *rhs;
409}
410
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000411KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000412 KeyEvent event;
413 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
414 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
415 entry.repeatCount, entry.downTime, entry.eventTime);
416 return event;
417}
418
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000419std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000420 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
421 const sp<IBinder>& token) {
422 for (const auto& it : monitorsByDisplay) {
423 const std::vector<Monitor>& monitors = it.second;
424 for (const Monitor& monitor : monitors) {
425 if (monitor.inputChannel->getConnectionToken() == token) {
426 return monitor.pid;
427 }
428 }
429 }
430 return std::nullopt;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000434 // Do not keep track of gesture monitors. They receive every event and would disproportionately
435 // affect the statistics.
436 if (connection.monitor) {
437 return false;
438 }
439 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
440 if (!connection.responsive) {
441 return false;
442 }
443 return true;
444}
445
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000446bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000447 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
448 const int32_t& inputEventId = eventEntry.id;
449 if (inputEventId != dispatchEntry.resolvedEventId) {
450 // Event was transmuted
451 return false;
452 }
453 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
454 return false;
455 }
456 // Only track latency for events that originated from hardware
457 if (eventEntry.isSynthesized()) {
458 return false;
459 }
460 const EventEntry::Type& inputEventEntryType = eventEntry.type;
461 if (inputEventEntryType == EventEntry::Type::KEY) {
462 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
463 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
464 return false;
465 }
466 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
467 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
468 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
469 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
470 return false;
471 }
472 } else {
473 // Not a key or a motion
474 return false;
475 }
476 if (!shouldReportMetricsForConnection(connection)) {
477 return false;
478 }
479 return true;
480}
481
Prabir Pradhancef936d2021-07-21 16:17:52 +0000482/**
483 * Connection is responsive if it has no events in the waitQueue that are older than the
484 * current time.
485 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000486bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000487 const nsecs_t currentTime = now();
488 for (const DispatchEntry* entry : connection.waitQueue) {
489 if (entry->timeoutTime < currentTime) {
490 return false;
491 }
492 }
493 return true;
494}
495
Antonio Kantekf16f2832021-09-28 04:39:20 +0000496// Returns true if the event type passed as argument represents a user activity.
497bool isUserActivityEvent(const EventEntry& eventEntry) {
498 switch (eventEntry.type) {
499 case EventEntry::Type::FOCUS:
500 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
501 case EventEntry::Type::DRAG:
502 case EventEntry::Type::TOUCH_MODE_CHANGED:
503 case EventEntry::Type::SENSOR:
504 case EventEntry::Type::CONFIGURATION_CHANGED:
505 return false;
506 case EventEntry::Type::DEVICE_RESET:
507 case EventEntry::Type::KEY:
508 case EventEntry::Type::MOTION:
509 return true;
510 }
511}
512
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800513// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700514bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
515 bool isStylus) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800516 if (windowInfo.displayId != displayId || !windowInfo.visible) {
517 return false;
518 }
519 const auto flags = windowInfo.flags;
Prabir Pradhand65552b2021-10-07 11:23:50 -0700520 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
521 if (flags.test(WindowInfo::Flag::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800522 return false;
523 }
524 const bool isModalWindow = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
525 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
526 if (!isModalWindow && !windowInfo.touchableRegionContainsPoint(x, y)) {
527 return false;
528 }
529 return true;
530}
531
Prabir Pradhand65552b2021-10-07 11:23:50 -0700532bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
533 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
534 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
535 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
536}
537
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000538} // namespace
539
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540// --- InputDispatcher ---
541
Garfield Tan00f511d2019-06-12 16:55:40 -0700542InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
543 : mPolicy(policy),
544 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700545 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800546 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700547 mAppSwitchSawKeyDown(false),
548 mAppSwitchDueTime(LONG_LONG_MAX),
549 mNextUnblockedEvent(nullptr),
550 mDispatchEnabled(false),
551 mDispatchFrozen(false),
552 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800553 // mInTouchMode will be initialized by the WindowManager to the default device config.
554 // To avoid leaking stack in case that call never comes, and for tests,
555 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000556 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100557 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000558 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800559 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000560 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800561 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800563 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700565 mWindowInfoListener = new DispatcherWindowListener(*this);
566 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
567
Yi Kong9b14ac62018-07-17 13:48:38 -0700568 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569
570 policy->getDispatcherConfiguration(&mConfig);
571}
572
573InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000574 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575
Prabir Pradhancef936d2021-07-21 16:17:52 +0000576 resetKeyRepeatLocked();
577 releasePendingEventLocked();
578 drainInboundQueueLocked();
579 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000581 while (!mConnectionsByToken.empty()) {
582 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000583 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
584 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585 }
586}
587
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700588status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700589 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700590 return ALREADY_EXISTS;
591 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700592 mThread = std::make_unique<InputThread>(
593 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
594 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595}
596
597status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700598 if (mThread && mThread->isCallingThread()) {
599 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600 return INVALID_OPERATION;
601 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700602 mThread.reset();
603 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700604}
605
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606void InputDispatcher::dispatchOnce() {
607 nsecs_t nextWakeupTime = LONG_LONG_MAX;
608 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800609 std::scoped_lock _l(mLock);
610 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611
612 // Run a dispatch loop if there are no pending commands.
613 // The dispatch loop might enqueue commands to run afterwards.
614 if (!haveCommandsLocked()) {
615 dispatchOnceInnerLocked(&nextWakeupTime);
616 }
617
618 // Run all pending commands if there are any.
619 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000620 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 nextWakeupTime = LONG_LONG_MIN;
622 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800623
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700624 // If we are still waiting for ack on some events,
625 // we might have to wake up earlier to check if an app is anr'ing.
626 const nsecs_t nextAnrCheck = processAnrsLocked();
627 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
628
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800629 // We are about to enter an infinitely long sleep, because we have no commands or
630 // pending or queued events
631 if (nextWakeupTime == LONG_LONG_MAX) {
632 mDispatcherEnteredIdle.notify_all();
633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 } // release lock
635
636 // Wait for callback or timeout or wake. (make sure we round up, not down)
637 nsecs_t currentTime = now();
638 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
639 mLooper->pollOnce(timeoutMillis);
640}
641
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700642/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500643 * Raise ANR if there is no focused window.
644 * Before the ANR is raised, do a final state check:
645 * 1. The currently focused application must be the same one we are waiting for.
646 * 2. Ensure we still don't have a focused window.
647 */
648void InputDispatcher::processNoFocusedWindowAnrLocked() {
649 // Check if the application that we are waiting for is still focused.
650 std::shared_ptr<InputApplicationHandle> focusedApplication =
651 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
652 if (focusedApplication == nullptr ||
653 focusedApplication->getApplicationToken() !=
654 mAwaitedFocusedApplication->getApplicationToken()) {
655 // Unexpected because we should have reset the ANR timer when focused application changed
656 ALOGE("Waited for a focused window, but focused application has already changed to %s",
657 focusedApplication->getName().c_str());
658 return; // The focused application has changed.
659 }
660
chaviw98318de2021-05-19 16:45:23 -0500661 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500662 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
663 if (focusedWindowHandle != nullptr) {
664 return; // We now have a focused window. No need for ANR.
665 }
666 onAnrLocked(mAwaitedFocusedApplication);
667}
668
669/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700670 * Check if any of the connections' wait queues have events that are too old.
671 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
672 * Return the time at which we should wake up next.
673 */
674nsecs_t InputDispatcher::processAnrsLocked() {
675 const nsecs_t currentTime = now();
676 nsecs_t nextAnrCheck = LONG_LONG_MAX;
677 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
678 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
679 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500680 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700681 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500682 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700683 return LONG_LONG_MIN;
684 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500685 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700686 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
687 }
688 }
689
690 // Check if any connection ANRs are due
691 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
692 if (currentTime < nextAnrCheck) { // most likely scenario
693 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
694 }
695
696 // If we reached here, we have an unresponsive connection.
697 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
698 if (connection == nullptr) {
699 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
700 return nextAnrCheck;
701 }
702 connection->responsive = false;
703 // Stop waking up for this unresponsive connection
704 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000705 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706 return LONG_LONG_MIN;
707}
708
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500709std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500710 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700711 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500712 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500714 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700715}
716
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
718 nsecs_t currentTime = now();
719
Jeff Browndc5992e2014-04-11 01:27:26 -0700720 // Reset the key repeat timer whenever normal dispatch is suspended while the
721 // device is in a non-interactive state. This is to ensure that we abort a key
722 // repeat if the device is just coming out of sleep.
723 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 resetKeyRepeatLocked();
725 }
726
727 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
728 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100729 if (DEBUG_FOCUS) {
730 ALOGD("Dispatch frozen. Waiting some more.");
731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 return;
733 }
734
735 // Optimize latency of app switches.
736 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
737 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
738 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
739 if (mAppSwitchDueTime < *nextWakeupTime) {
740 *nextWakeupTime = mAppSwitchDueTime;
741 }
742
743 // Ready to start a new event.
744 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700745 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700746 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 if (isAppSwitchDue) {
748 // The inbound queue is empty so the app switch key we were waiting
749 // for will never arrive. Stop waiting for it.
750 resetPendingAppSwitchLocked(false);
751 isAppSwitchDue = false;
752 }
753
754 // Synthesize a key repeat if appropriate.
755 if (mKeyRepeatState.lastKeyEntry) {
756 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
757 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
758 } else {
759 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
760 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
761 }
762 }
763 }
764
765 // Nothing to do if there is no pending event.
766 if (!mPendingEvent) {
767 return;
768 }
769 } else {
770 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700771 mPendingEvent = mInboundQueue.front();
772 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 traceInboundQueueLengthLocked();
774 }
775
776 // Poke user activity for this event.
777 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700778 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
781
782 // Now we have an event to dispatch.
783 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700784 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700786 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700788 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 }
792
793 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700794 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 }
796
797 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700798 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 const ConfigurationChangedEntry& typedEntry =
800 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 break;
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 const DeviceResetEntry& typedEntry =
808 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 break;
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100814 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 std::shared_ptr<FocusEntry> typedEntry =
816 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100817 dispatchFocusLocked(currentTime, typedEntry);
818 done = true;
819 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
820 break;
821 }
822
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700823 case EventEntry::Type::TOUCH_MODE_CHANGED: {
824 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
825 dispatchTouchModeChangeLocked(currentTime, typedEntry);
826 done = true;
827 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
828 break;
829 }
830
Prabir Pradhan99987712020-11-10 18:43:05 -0800831 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
832 const auto typedEntry =
833 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
834 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
835 done = true;
836 break;
837 }
838
arthurhungb89ccb02020-12-30 16:19:01 +0800839 case EventEntry::Type::DRAG: {
840 std::shared_ptr<DragEntry> typedEntry =
841 std::static_pointer_cast<DragEntry>(mPendingEvent);
842 dispatchDragLocked(currentTime, typedEntry);
843 done = true;
844 break;
845 }
846
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700847 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700848 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 resetPendingAppSwitchLocked(true);
852 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700853 } else if (dropReason == DropReason::NOT_DROPPED) {
854 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 }
856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700857 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700858 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700860 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
861 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 break;
865 }
866
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700867 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700868 std::shared_ptr<MotionEntry> motionEntry =
869 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
871 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700874 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
877 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
Chris Yef59a2f42020-10-16 12:55:26 -0700882
883 case EventEntry::Type::SENSOR: {
884 std::shared_ptr<SensorEntry> sensorEntry =
885 std::static_pointer_cast<SensorEntry>(mPendingEvent);
886 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
887 dropReason = DropReason::APP_SWITCH;
888 }
889 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
890 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
891 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
892 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
893 dropReason = DropReason::STALE;
894 }
895 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
896 done = true;
897 break;
898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
901 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Michael Wright3a981722015-06-10 15:26:13 +0100905 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906
907 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910}
911
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700912/**
913 * Return true if the events preceding this incoming motion event should be dropped
914 * Return false otherwise (the default behaviour)
915 */
916bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700917 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700918 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700919
920 // Optimize case where the current application is unresponsive and the user
921 // decides to touch a window in a different application.
922 // If the application takes too long to catch up then we drop all events preceding
923 // the touch into the other window.
924 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700925 int32_t displayId = motionEntry.displayId;
926 int32_t x = static_cast<int32_t>(
927 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
928 int32_t y = static_cast<int32_t>(
929 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700930
931 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500932 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700933 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700934 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935 touchedWindowHandle->getApplicationToken() !=
936 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 ALOGI("Pruning input queue because user touched a different application while waiting "
939 "for %s",
940 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941 return true;
942 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700943
944 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700945 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700947 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000948 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 // This monitor could take more input. Drop all events preceding this
950 // event, so that gesture monitor could get a chance to receive the stream
951 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
952 "responsive gesture monitor that may handle the event",
953 mAwaitedFocusedApplication->getName().c_str());
954 return true;
955 }
956 }
957 }
958
959 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
960 // yet been processed by some connections, the dispatcher will wait for these motion
961 // events to be processed before dispatching the key event. This is because these motion events
962 // may cause a new window to be launched, which the user might expect to receive focus.
963 // To prevent waiting forever for such events, just send the key to the currently focused window
964 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
965 ALOGD("Received a new pointer down event, stop waiting for events to process and "
966 "just send the pending key event to the focused window.");
967 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700968 }
969 return false;
970}
971
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700972bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700973 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 mInboundQueue.push_back(std::move(newEntry));
975 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 traceInboundQueueLengthLocked();
977
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700979 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 // Optimize app switch latency.
981 // If the application takes too long to catch up then we drop all events preceding
982 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700985 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700987 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000989 if (DEBUG_APP_SWITCH) {
990 ALOGD("App switch is pending!");
991 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 mAppSwitchSawKeyDown = false;
994 needWake = true;
995 }
996 }
997 }
998 break;
999 }
1000
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001001 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001002 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1003 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001004 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001008 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001009 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1010 break;
1011 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001012 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001013 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001014 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001015 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001016 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1017 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 // nothing to do
1019 break;
1020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
1022
1023 return needWake;
1024}
1025
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001027 // Do not store sensor event in recent queue to avoid flooding the queue.
1028 if (entry->type != EventEntry::Type::SENSOR) {
1029 mRecentQueue.push_back(entry);
1030 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001031 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 }
1034}
1035
chaviw98318de2021-05-19 16:45:23 -05001036sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1037 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001038 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001039 bool addOutsideTargets,
1040 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001041 if (addOutsideTargets && touchState == nullptr) {
1042 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001045 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001046 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001047 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001048 continue;
1049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001051 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001052 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001053 return windowHandle;
1054 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001055
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001056 if (addOutsideTargets && info.flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
1057 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1058 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
1060 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001061 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062}
1063
Prabir Pradhand65552b2021-10-07 11:23:50 -07001064std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1065 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001066 // Traverse windows from front to back and gather the touched spy windows.
1067 std::vector<sp<WindowInfoHandle>> spyWindows;
1068 const auto& windowHandles = getWindowHandlesLocked(displayId);
1069 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1070 const WindowInfo& info = *windowHandle->getInfo();
1071
Prabir Pradhand65552b2021-10-07 11:23:50 -07001072 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001073 continue;
1074 }
1075 if (!info.isSpy()) {
1076 // The first touched non-spy window was found, so return the spy windows touched so far.
1077 return spyWindows;
1078 }
1079 spyWindows.push_back(windowHandle);
1080 }
1081 return spyWindows;
1082}
1083
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001084void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 const char* reason;
1086 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001088 if (DEBUG_INBOUND_EVENT_DETAILS) {
1089 ALOGD("Dropped event because policy consumed it.");
1090 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 reason = "inbound event was dropped because the policy consumed it";
1092 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 case DropReason::DISABLED:
1094 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 ALOGI("Dropped event because input dispatch is disabled.");
1096 }
1097 reason = "inbound event was dropped because input dispatch is disabled";
1098 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 ALOGI("Dropped event because of pending overdue app switch.");
1101 reason = "inbound event was dropped because of pending overdue app switch";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because the current application is not responding and the user "
1105 "has started interacting with a different application.");
1106 reason = "inbound event was dropped because the current application is not responding "
1107 "and the user has started interacting with a different application";
1108 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 ALOGI("Dropped event because it is stale.");
1111 reason = "inbound event was dropped because it is stale";
1112 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001113 case DropReason::NO_POINTER_CAPTURE:
1114 ALOGI("Dropped event because there is no window with Pointer Capture.");
1115 reason = "inbound event was dropped because there is no window with Pointer Capture";
1116 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001117 case DropReason::NOT_DROPPED: {
1118 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
1122
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001123 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1126 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001129 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001130 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1131 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1133 synthesizeCancelationEventsForAllConnectionsLocked(options);
1134 } else {
1135 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1136 synthesizeCancelationEventsForAllConnectionsLocked(options);
1137 }
1138 break;
1139 }
Chris Yef59a2f42020-10-16 12:55:26 -07001140 case EventEntry::Type::SENSOR: {
1141 break;
1142 }
arthurhungb89ccb02020-12-30 16:19:01 +08001143 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1144 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001145 break;
1146 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001147 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001148 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001149 case EventEntry::Type::CONFIGURATION_CHANGED:
1150 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001151 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 break;
1153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155}
1156
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001157static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1159 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160}
1161
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001162bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1163 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1164 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1165 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166}
1167
1168bool InputDispatcher::isAppSwitchPendingLocked() {
1169 return mAppSwitchDueTime != LONG_LONG_MAX;
1170}
1171
1172void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1173 mAppSwitchDueTime = LONG_LONG_MAX;
1174
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001175 if (DEBUG_APP_SWITCH) {
1176 if (handled) {
1177 ALOGD("App switch has arrived.");
1178 } else {
1179 ALOGD("App switch was abandoned.");
1180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182}
1183
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001185 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186}
1187
Prabir Pradhancef936d2021-07-21 16:17:52 +00001188bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 return false;
1191 }
1192
1193 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001194 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001195 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001196 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1197 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001198 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 return true;
1200}
1201
Prabir Pradhancef936d2021-07-21 16:17:52 +00001202void InputDispatcher::postCommandLocked(Command&& command) {
1203 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204}
1205
1206void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001207 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001208 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001209 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 releaseInboundEventLocked(entry);
1211 }
1212 traceInboundQueueLengthLocked();
1213}
1214
1215void InputDispatcher::releasePendingEventLocked() {
1216 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001218 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 }
1220}
1221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001224 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001225 if (DEBUG_DISPATCH_CYCLE) {
1226 ALOGD("Injected inbound event was dropped.");
1227 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001231 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234}
1235
1236void InputDispatcher::resetKeyRepeatLocked() {
1237 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001238 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240}
1241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1243 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244
Michael Wright2e732952014-09-24 13:26:59 -07001245 uint32_t policyFlags = entry->policyFlags &
1246 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 std::shared_ptr<KeyEntry> newEntry =
1249 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1250 entry->source, entry->displayId, policyFlags, entry->action,
1251 entry->flags, entry->keyCode, entry->scanCode,
1252 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 newEntry->syntheticRepeat = true;
1255 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258}
1259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001262 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1263 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265
1266 // Reset key repeating in case a keyboard device was added or removed or something.
1267 resetKeyRepeatLocked();
1268
1269 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001270 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1271 scoped_unlock unlock(mLock);
1272 mPolicy->notifyConfigurationChanged(eventTime);
1273 };
1274 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 return true;
1276}
1277
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1279 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001280 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1281 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1282 entry.deviceId);
1283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
liushenxiang42232912021-05-21 20:24:09 +08001285 // Reset key repeating in case a keyboard device was disabled or enabled.
1286 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1287 resetKeyRepeatLocked();
1288 }
1289
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 synthesizeCancelationEventsForAllConnectionsLocked(options);
1293 return true;
1294}
1295
Vishnu Nairad321cd2020-08-20 16:40:21 -07001296void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001297 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001298 if (mPendingEvent != nullptr) {
1299 // Move the pending event to the front of the queue. This will give the chance
1300 // for the pending event to get dispatched to the newly focused window
1301 mInboundQueue.push_front(mPendingEvent);
1302 mPendingEvent = nullptr;
1303 }
1304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 std::unique_ptr<FocusEntry> focusEntry =
1306 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1307 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001308
1309 // This event should go to the front of the queue, but behind all other focus events
1310 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001311 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001312 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001313 [](const std::shared_ptr<EventEntry>& event) {
1314 return event->type == EventEntry::Type::FOCUS;
1315 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001316
1317 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001318 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001319}
1320
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001322 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001323 if (channel == nullptr) {
1324 return; // Window has gone away
1325 }
1326 InputTarget target;
1327 target.inputChannel = channel;
1328 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1329 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001330 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1331 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001332 std::string reason = std::string("reason=").append(entry->reason);
1333 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001334 dispatchEventLocked(currentTime, entry, {target});
1335}
1336
Prabir Pradhan99987712020-11-10 18:43:05 -08001337void InputDispatcher::dispatchPointerCaptureChangedLocked(
1338 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1339 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001340 dropReason = DropReason::NOT_DROPPED;
1341
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001343 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001344
1345 if (entry->pointerCaptureRequest.enable) {
1346 // Enable Pointer Capture.
1347 if (haveWindowWithPointerCapture &&
1348 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1349 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1350 "to the window.");
1351 }
1352 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001353 // This can happen if a window requests capture and immediately releases capture.
1354 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001355 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001356 return;
1357 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001358 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1359 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1360 return;
1361 }
1362
Vishnu Nairc519ff72021-01-21 08:23:08 -08001363 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001364 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1365 mWindowTokenWithPointerCapture = token;
1366 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001367 // Disable Pointer Capture.
1368 // We do not check if the sequence number matches for requests to disable Pointer Capture
1369 // for two reasons:
1370 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1371 // to disable capture with the same sequence number: one generated by
1372 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1373 // Capture being disabled in InputReader.
1374 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1375 // actual Pointer Capture state that affects events being generated by input devices is
1376 // in InputReader.
1377 if (!haveWindowWithPointerCapture) {
1378 // Pointer capture was already forcefully disabled because of focus change.
1379 dropReason = DropReason::NOT_DROPPED;
1380 return;
1381 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001382 token = mWindowTokenWithPointerCapture;
1383 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001384 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001385 setPointerCaptureLocked(false);
1386 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001387 }
1388
1389 auto channel = getInputChannelLocked(token);
1390 if (channel == nullptr) {
1391 // Window has gone away, clean up Pointer Capture state.
1392 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001394 setPointerCaptureLocked(false);
1395 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001396 return;
1397 }
1398 InputTarget target;
1399 target.inputChannel = channel;
1400 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1401 entry->dispatchInProgress = true;
1402 dispatchEventLocked(currentTime, entry, {target});
1403
1404 dropReason = DropReason::NOT_DROPPED;
1405}
1406
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001407void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1408 const std::shared_ptr<TouchModeEntry>& entry) {
1409 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1410 getWindowHandlesLocked(mFocusedDisplayId);
1411 if (windowHandles.empty()) {
1412 return;
1413 }
1414 const std::vector<InputTarget> inputTargets =
1415 getInputTargetsFromWindowHandlesLocked(windowHandles);
1416 if (inputTargets.empty()) {
1417 return;
1418 }
1419 entry->dispatchInProgress = true;
1420 dispatchEventLocked(currentTime, entry, inputTargets);
1421}
1422
1423std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1424 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1425 std::vector<InputTarget> inputTargets;
1426 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1427 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1428 const sp<IBinder>& token = handle->getToken();
1429 if (token == nullptr) {
1430 continue;
1431 }
1432 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1433 if (channel == nullptr) {
1434 continue; // Window has gone away
1435 }
1436 InputTarget target;
1437 target.inputChannel = channel;
1438 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1439 inputTargets.push_back(target);
1440 }
1441 return inputTargets;
1442}
1443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001447 if (!entry->dispatchInProgress) {
1448 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1449 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1450 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1451 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001452 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 // We have seen two identical key downs in a row which indicates that the device
1454 // driver is automatically generating key repeats itself. We take note of the
1455 // repeat here, but we disable our own next key repeat timer since it is clear that
1456 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001457 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1458 // Make sure we don't get key down from a different device. If a different
1459 // device Id has same key pressed down, the new device Id will replace the
1460 // current one to hold the key repeat with repeat count reset.
1461 // In the future when got a KEY_UP on the device id, drop it and do not
1462 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1464 resetKeyRepeatLocked();
1465 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1466 } else {
1467 // Not a repeat. Save key down state in case we do see a repeat later.
1468 resetKeyRepeatLocked();
1469 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1470 }
1471 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001472 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1473 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001474 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001475 if (DEBUG_INBOUND_EVENT_DETAILS) {
1476 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1477 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 resetKeyRepeatLocked();
1480 }
1481
1482 if (entry->repeatCount == 1) {
1483 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1484 } else {
1485 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1486 }
1487
1488 entry->dispatchInProgress = true;
1489
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001490 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492
1493 // Handle case where the policy asked us to try again later last time.
1494 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1495 if (currentTime < entry->interceptKeyWakeupTime) {
1496 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1497 *nextWakeupTime = entry->interceptKeyWakeupTime;
1498 }
1499 return false; // wait until next wakeup
1500 }
1501 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1502 entry->interceptKeyWakeupTime = 0;
1503 }
1504
1505 // Give the policy a chance to intercept the key.
1506 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1507 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001508 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001509 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001510
1511 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1512 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1513 };
1514 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 return false; // wait for the command to run
1516 } else {
1517 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1518 }
1519 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001520 if (*dropReason == DropReason::NOT_DROPPED) {
1521 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 }
1523 }
1524
1525 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001526 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001528 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1529 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001530 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 return true;
1532 }
1533
1534 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001535 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001536 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001537 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001538 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 return false;
1540 }
1541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001542 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001543 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 return true;
1545 }
1546
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001547 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001548 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549
1550 // Dispatch the key.
1551 dispatchEventLocked(currentTime, entry, inputTargets);
1552 return true;
1553}
1554
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001555void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001556 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1557 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1558 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1559 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1560 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1561 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1562 entry.metaState, entry.repeatCount, entry.downTime);
1563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564}
1565
Prabir Pradhancef936d2021-07-21 16:17:52 +00001566void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1567 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001568 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001569 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1570 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1571 "source=0x%x, sensorType=%s",
1572 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001573 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001574 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001575 auto command = [this, entry]() REQUIRES(mLock) {
1576 scoped_unlock unlock(mLock);
1577
1578 if (entry->accuracyChanged) {
1579 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1580 }
1581 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1582 entry->hwTimestamp, entry->values);
1583 };
1584 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001585}
1586
1587bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001588 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1589 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001590 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001591 }
Chris Yef59a2f42020-10-16 12:55:26 -07001592 { // acquire lock
1593 std::scoped_lock _l(mLock);
1594
1595 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1596 std::shared_ptr<EventEntry> entry = *it;
1597 if (entry->type == EventEntry::Type::SENSOR) {
1598 it = mInboundQueue.erase(it);
1599 releaseInboundEventLocked(entry);
1600 }
1601 }
1602 }
1603 return true;
1604}
1605
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001606bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001607 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001608 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 entry->dispatchInProgress = true;
1612
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001613 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 }
1615
1616 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001617 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001618 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001619 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1620 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 return true;
1622 }
1623
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001624 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625
1626 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001627 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628
1629 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001630 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 if (isPointerEvent) {
1632 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001633 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001634 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001635 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 } else {
1637 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001638 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001639 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001641 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 return false;
1643 }
1644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001646 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001647 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1648 return true;
1649 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001650 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001651 CancelationOptions::Mode mode(isPointerEvent
1652 ? CancelationOptions::CANCEL_POINTER_EVENTS
1653 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1654 CancelationOptions options(mode, "input event injection failed");
1655 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 return true;
1657 }
1658
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001659 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001660 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661
1662 // Dispatch the motion.
1663 if (conflictingPointerActions) {
1664 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 synthesizeCancelationEventsForAllConnectionsLocked(options);
1667 }
1668 dispatchEventLocked(currentTime, entry, inputTargets);
1669 return true;
1670}
1671
chaviw98318de2021-05-19 16:45:23 -05001672void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001673 bool isExiting, const MotionEntry& motionEntry) {
1674 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1675 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1676 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1677 PointerCoords pointerCoords;
1678 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1679 pointerCoords.transform(windowHandle->getInfo()->transform);
1680
1681 std::unique_ptr<DragEntry> dragEntry =
1682 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1683 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1684 pointerCoords.getY());
1685
1686 enqueueInboundEventLocked(std::move(dragEntry));
1687}
1688
1689void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1690 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1691 if (channel == nullptr) {
1692 return; // Window has gone away
1693 }
1694 InputTarget target;
1695 target.inputChannel = channel;
1696 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1697 entry->dispatchInProgress = true;
1698 dispatchEventLocked(currentTime, entry, {target});
1699}
1700
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001702 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1703 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1704 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001705 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001706 "metaState=0x%x, buttonState=0x%x,"
1707 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1708 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001709 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1710 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1711 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001713 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1714 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1715 "x=%f, y=%f, pressure=%f, size=%f, "
1716 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1717 "orientation=%f",
1718 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1719 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1720 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1721 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1722 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1723 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1724 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1725 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1726 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1727 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730}
1731
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001732void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1733 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001734 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001736 if (DEBUG_DISPATCH_CYCLE) {
1737 ALOGD("dispatchEventToCurrentInputTargets");
1738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001740 updateInteractionTokensLocked(*eventEntry, inputTargets);
1741
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1743
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001746 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001747 sp<Connection> connection =
1748 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001749 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001750 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001752 if (DEBUG_FOCUS) {
1753 ALOGD("Dropping event delivery to target with channel '%s' because it "
1754 "is no longer registered with the input dispatcher.",
1755 inputTarget.inputChannel->getName().c_str());
1756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 }
1758 }
1759}
1760
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001761void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1762 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1763 // If the policy decides to close the app, we will get a channel removal event via
1764 // unregisterInputChannel, and will clean up the connection that way. We are already not
1765 // sending new pointers to the connection when it blocked, but focused events will continue to
1766 // pile up.
1767 ALOGW("Canceling events for %s because it is unresponsive",
1768 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001769 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1771 "application not responding");
1772 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 }
1774}
1775
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001776void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001777 if (DEBUG_FOCUS) {
1778 ALOGD("Resetting ANR timeouts.");
1779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780
1781 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001782 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001783 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784}
1785
Tiger Huang721e26f2018-07-24 22:26:19 +08001786/**
1787 * Get the display id that the given event should go to. If this event specifies a valid display id,
1788 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1789 * Focused display is the display that the user most recently interacted with.
1790 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001792 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001794 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1796 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001797 break;
1798 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001799 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001800 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1801 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001802 break;
1803 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001804 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001805 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001806 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001807 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001808 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001809 case EventEntry::Type::SENSOR:
1810 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001811 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001812 return ADISPLAY_ID_NONE;
1813 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001814 }
1815 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1816}
1817
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1819 const char* focusedWindowName) {
1820 if (mAnrTracker.empty()) {
1821 // already processed all events that we waited for
1822 mKeyIsWaitingForEventsTimeout = std::nullopt;
1823 return false;
1824 }
1825
1826 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1827 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001828 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001829 mKeyIsWaitingForEventsTimeout = currentTime +
1830 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1831 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001832 return true;
1833 }
1834
1835 // We still have pending events, and already started the timer
1836 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1837 return true; // Still waiting
1838 }
1839
1840 // Waited too long, and some connection still hasn't processed all motions
1841 // Just send the key to the focused window
1842 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1843 focusedWindowName);
1844 mKeyIsWaitingForEventsTimeout = std::nullopt;
1845 return false;
1846}
1847
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1849 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1850 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001851 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852
Tiger Huang721e26f2018-07-24 22:26:19 +08001853 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001854 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001855 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001856 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1857
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 // If there is no currently focused window and no focused application
1859 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001860 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1861 ALOGI("Dropping %s event because there is no focused window or focused application in "
1862 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001863 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001864 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866
Vishnu Nair062a8672021-09-03 16:07:44 -07001867 // Drop key events if requested by input feature
1868 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1869 return InputEventInjectionResult::FAILED;
1870 }
1871
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001872 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1873 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1874 // start interacting with another application via touch (app switch). This code can be removed
1875 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1876 // an app is expected to have a focused window.
1877 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1878 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1879 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001880 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1881 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1882 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001883 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001884 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001885 ALOGW("Waiting because no window has focus but %s may eventually add a "
1886 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001887 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001889 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001890 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1891 // Already raised ANR. Drop the event
1892 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001893 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001895 } else {
1896 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001897 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 }
1899 }
1900
1901 // we have a valid, non-null focused window
1902 resetNoFocusedWindowTimeoutLocked();
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001905 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 }
1908
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001909 if (focusedWindowHandle->getInfo()->paused) {
1910 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001911 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001912 }
1913
1914 // If the event is a key event, then we must wait for all previous events to
1915 // complete before delivering it because previous events may have the
1916 // side-effect of transferring focus to a different window and we want to
1917 // ensure that the following keys are sent to the new window.
1918 //
1919 // Suppose the user touches a button in a window then immediately presses "A".
1920 // If the button causes a pop-up window to appear then we want to ensure that
1921 // the "A" key is delivered to the new pop-up window. This is because users
1922 // often anticipate pending UI changes when typing on a keyboard.
1923 // To obtain this behavior, we must serialize key events with respect to all
1924 // prior input events.
1925 if (entry.type == EventEntry::Type::KEY) {
1926 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1927 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001928 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 }
1931
1932 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001933 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001934 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1935 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936
1937 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939}
1940
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941/**
1942 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1943 * that are currently unresponsive.
1944 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001945std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1946 const std::vector<Monitor>& monitors) const {
1947 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001948 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001949 [this](const Monitor& monitor) REQUIRES(mLock) {
1950 sp<Connection> connection =
1951 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 if (connection == nullptr) {
1953 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001954 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 return false;
1956 }
1957 if (!connection->responsive) {
1958 ALOGW("Unresponsive monitor %s will not get the new gesture",
1959 connection->inputChannel->getName().c_str());
1960 return false;
1961 }
1962 return true;
1963 });
1964 return responsiveMonitors;
1965}
1966
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001967InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1968 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1969 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001970 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 enum InjectionPermission {
1972 INJECTION_PERMISSION_UNKNOWN,
1973 INJECTION_PERMISSION_GRANTED,
1974 INJECTION_PERMISSION_DENIED
1975 };
1976
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 // For security reasons, we defer updating the touch state until we are sure that
1978 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001979 const int32_t displayId = entry.displayId;
1980 const int32_t action = entry.action;
1981 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982
1983 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001984 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001986 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1987 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001989 // Copy current touch state into tempTouchState.
1990 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1991 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001992 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001993 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001994 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1995 oldState = &(it->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001997 }
1998
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 bool isSplit = tempTouchState.split;
2000 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2001 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2002 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002003
2004 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2005 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2006 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2007 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2008 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002009 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 bool wrongDevice = false;
2011 if (newGesture) {
2012 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002014 ALOGI("Dropping event because a pointer for a different device is already down "
2015 "in display %" PRId32,
2016 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002017 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002018 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 switchedDevice = false;
2020 wrongDevice = true;
2021 goto Failed;
2022 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 tempTouchState.reset();
2024 tempTouchState.down = down;
2025 tempTouchState.deviceId = entry.deviceId;
2026 tempTouchState.source = entry.source;
2027 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002029 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002030 ALOGI("Dropping move event because a pointer for a different device is already active "
2031 "in display %" PRId32,
2032 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002033 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002035 switchedDevice = false;
2036 wrongDevice = true;
2037 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 }
2039
2040 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2041 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2042
Garfield Tan00f511d2019-06-12 16:55:40 -07002043 int32_t x;
2044 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002045 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 // Always dispatch mouse events to cursor position.
2047 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 x = int32_t(entry.xCursorPosition);
2049 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002050 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2052 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002053 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002054 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002055 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002056 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002057 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002058
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002060 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002061 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2062 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002064 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002065 }
2066
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002067 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002069 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2070 // New window supports splitting, but we should never split mouse events.
2071 isSplit = !isFromMouse;
2072 } else if (isSplit) {
2073 // New window does not support splitting but we have already split events.
2074 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075 newTouchedWindowHandle = nullptr;
2076 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002077 } else {
2078 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002079 // be delivered to a new window which supports split touch. Pointers from a mouse device
2080 // should never be split.
2081 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002082 }
2083
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002084 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002086 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2087 newHoverWindowHandle = nullptr;
2088 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002089 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002090 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002091 }
2092
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002093 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002094 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002095 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002096 // Process the foreground window first so that it is the first to receive the event.
2097 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002098 }
2099
2100 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2101 const WindowInfo& info = *windowHandle->getInfo();
2102
2103 if (info.paused) {
2104 ALOGI("Not sending touch event to %s because it is paused",
2105 windowHandle->getName().c_str());
2106 continue;
2107 }
2108
2109 // Ensure the window has a connection and the connection is responsive
2110 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2111 if (!isResponsive) {
2112 ALOGW("Not sending touch gesture to %s because it is not responsive",
2113 windowHandle->getName().c_str());
2114 continue;
2115 }
2116
2117 // Drop events that can't be trusted due to occlusion
2118 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2119 TouchOcclusionInfo occlusionInfo =
2120 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2121 if (!isTouchTrustedLocked(occlusionInfo)) {
2122 if (DEBUG_TOUCH_OCCLUSION) {
2123 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2124 for (const auto& log : occlusionInfo.debugInfo) {
2125 ALOGD("%s", log.c_str());
2126 }
2127 }
2128 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2129 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2130 ALOGW("Dropping untrusted touch event due to %s/%d",
2131 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2132 continue;
2133 }
2134 }
2135 }
2136
2137 // Drop touch events if requested by input feature
2138 if (shouldDropInput(entry, windowHandle)) {
2139 continue;
2140 }
2141
2142 // Set target flags.
2143 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2144
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002145 if (!info.isSpy()) {
2146 // There should only be one new foreground (non-spy) window at this location.
2147 targetFlags |= InputTarget::FLAG_FOREGROUND;
2148 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002149
2150 if (isSplit) {
2151 targetFlags |= InputTarget::FLAG_SPLIT;
2152 }
2153 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2154 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2155 } else if (isWindowObscuredLocked(windowHandle)) {
2156 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2157 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002158
2159 // Update the temporary touch state.
2160 BitSet32 pointerIds;
2161 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002162 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002163 pointerIds.markBit(pointerId);
2164 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165
2166 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002168
2169 const std::vector<Monitor> newGestureMonitors = isDown
2170 ? selectResponsiveMonitorsLocked(
2171 getValueByKey(mGestureMonitorsByDisplay, displayId))
2172 : std::vector<Monitor>{};
2173
2174 if (newTouchedWindows.empty() && newGestureMonitors.empty() &&
2175 tempTouchState.gestureMonitors.empty()) {
2176 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
2177 "(%d, %d) in display %" PRId32 ".",
2178 x, y, displayId);
2179 injectionResult = InputEventInjectionResult::FAILED;
2180 goto Failed;
Arthur Hung2ea44b92021-11-23 07:42:21 +00002181 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002182
2183 tempTouchState.addGestureMonitors(newGestureMonitors);
2184
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 } else {
2186 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2187
2188 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002190 if (DEBUG_FOCUS) {
2191 ALOGD("Dropping event because the pointer is not down or we previously "
2192 "dropped the pointer down event in display %" PRId32,
2193 displayId);
2194 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002195 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 goto Failed;
2197 }
2198
arthurhung6d4bed92021-03-17 11:59:33 +08002199 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002200
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002202 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002203 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002204 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2205 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206
Prabir Pradhand65552b2021-10-07 11:23:50 -07002207 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002208 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002209 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002210 newTouchedWindowHandle =
2211 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002212
2213 // Drop touch events if requested by input feature
2214 if (newTouchedWindowHandle != nullptr &&
2215 shouldDropInput(entry, newTouchedWindowHandle)) {
2216 newTouchedWindowHandle = nullptr;
2217 }
2218
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2220 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002221 if (DEBUG_FOCUS) {
2222 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2223 oldTouchedWindowHandle->getName().c_str(),
2224 newTouchedWindowHandle->getName().c_str(), displayId);
2225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2228 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2229 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230
2231 // Make a slippery entrance into the new window.
2232 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002233 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002236 int32_t targetFlags =
2237 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 if (isSplit) {
2239 targetFlags |= InputTarget::FLAG_SPLIT;
2240 }
2241 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2242 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002243 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2244 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246
2247 BitSet32 pointerIds;
2248 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002249 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
2253 }
2254 }
2255
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002256 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002258 // Let the previous window know that the hover sequence is over, unless we already did
2259 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002260 if (mLastHoverWindowHandle != nullptr &&
2261 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2262 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002263 if (DEBUG_HOVER) {
2264 ALOGD("Sending hover exit event to window %s.",
2265 mLastHoverWindowHandle->getName().c_str());
2266 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2268 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270
Garfield Tandf26e862020-07-01 20:18:19 -07002271 // Let the new window know that the hover sequence is starting, unless we already did it
2272 // when dispatching it as is to newTouchedWindowHandle.
2273 if (newHoverWindowHandle != nullptr &&
2274 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2275 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002276 if (DEBUG_HOVER) {
2277 ALOGD("Sending hover enter event to window %s.",
2278 newHoverWindowHandle->getName().c_str());
2279 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2281 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2282 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284 }
2285
2286 // Check permission to inject into all touched foreground windows and ensure there
2287 // is at least one touched foreground window.
2288 {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002289 bool haveForegroundOrSpyWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002290 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002291 const bool isForeground =
2292 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
2293 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2294 haveForegroundOrSpyWindow = true;
2295 LOG_ALWAYS_FATAL_IF(isForeground,
2296 "Spy window cannot be dispatched as a foreground window.");
2297 }
2298 if (isForeground) {
2299 haveForegroundOrSpyWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002300 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002301 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 injectionPermission = INJECTION_PERMISSION_DENIED;
2303 goto Failed;
2304 }
2305 }
2306 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002308 if (!haveForegroundOrSpyWindow && !hasGestureMonitor) {
2309 ALOGI("Dropping event because there is no touched window in display "
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002310 "%" PRId32 " or gesture monitor to receive it.",
2311 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002312 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 goto Failed;
2314 }
2315
2316 // Permission granted to injection into all touched foreground windows.
2317 injectionPermission = INJECTION_PERMISSION_GRANTED;
2318 }
2319
2320 // Check whether windows listening for outside touches are owned by the same UID. If it is
2321 // set the policy flag that we will not reveal coordinate information to this window.
2322 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002323 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002324 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002325 if (foregroundWindowHandle) {
2326 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002327 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002328 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002329 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2330 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2331 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002332 InputTarget::FLAG_ZERO_COORDS,
2333 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
2336 }
2337 }
2338 }
2339
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 // If this is the first pointer going down and the touched window has a wallpaper
2341 // then also add the touched wallpaper windows so they are locked in for the duration
2342 // of the touch gesture.
2343 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2344 // engine only supports touch events. We would need to add a mechanism similar
2345 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2346 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002347 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002348 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002349 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002350 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002351 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002352 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2353 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002355 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002356 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 .addOrUpdateWindow(windowHandle,
2358 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2359 InputTarget::
2360 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2361 InputTarget::FLAG_DISPATCH_AS_IS,
2362 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 }
2364 }
2365 }
2366 }
2367
2368 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002369 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002371 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002376 for (const auto& monitor : tempTouchState.gestureMonitors) {
2377 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002378 }
2379
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 // Drop the outside or hover touch windows since we will not care about them
2381 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383
2384Failed:
2385 // Check injection permission once and for all.
2386 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002387 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 injectionPermission = INJECTION_PERMISSION_GRANTED;
2389 } else {
2390 injectionPermission = INJECTION_PERMISSION_DENIED;
2391 }
2392 }
2393
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2395 return injectionResult;
2396 }
2397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002399 if (!wrongDevice) {
2400 if (switchedDevice) {
2401 if (DEBUG_FOCUS) {
2402 ALOGD("Conflicting pointer actions: Switched to a different device.");
2403 }
2404 *outConflictingPointerActions = true;
2405 }
2406
2407 if (isHoverAction) {
2408 // Started hovering, therefore no longer down.
2409 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002410 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002411 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2412 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 *outConflictingPointerActions = true;
2415 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002416 tempTouchState.reset();
2417 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2418 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2419 tempTouchState.deviceId = entry.deviceId;
2420 tempTouchState.source = entry.source;
2421 tempTouchState.displayId = displayId;
2422 }
2423 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2424 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2425 // All pointers up or canceled.
2426 tempTouchState.reset();
2427 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2428 // First pointer went down.
2429 if (oldState && oldState->down) {
2430 if (DEBUG_FOCUS) {
2431 ALOGD("Conflicting pointer actions: Down received while already down.");
2432 }
2433 *outConflictingPointerActions = true;
2434 }
2435 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2436 // One pointer went up.
2437 if (isSplit) {
2438 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2439 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002441 for (size_t i = 0; i < tempTouchState.windows.size();) {
2442 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2443 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2444 touchedWindow.pointerIds.clearBit(pointerId);
2445 if (touchedWindow.pointerIds.isEmpty()) {
2446 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2447 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002450 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002452 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002453 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002454
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002455 // Save changes unless the action was scroll in which case the temporary touch
2456 // state was only valid for this one action.
2457 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2458 if (tempTouchState.displayId >= 0) {
2459 mTouchStatesByDisplay[displayId] = tempTouchState;
2460 } else {
2461 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002465 // Update hover state.
2466 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
2468
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 return injectionResult;
2470}
2471
arthurhung6d4bed92021-03-17 11:59:33 +08002472void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002473 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2474 // have an explicit reason to support it.
2475 constexpr bool isStylus = false;
2476
chaviw98318de2021-05-19 16:45:23 -05002477 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002478 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002479 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002480 if (dropWindow) {
2481 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002482 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002483 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002484 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002485 }
2486 mDragState.reset();
2487}
2488
2489void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2490 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002491 return;
2492 }
2493
arthurhung6d4bed92021-03-17 11:59:33 +08002494 if (!mDragState->isStartDrag) {
2495 mDragState->isStartDrag = true;
2496 mDragState->isStylusButtonDownAtStart =
2497 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2498 }
2499
arthurhungb89ccb02020-12-30 16:19:01 +08002500 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2501 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2502 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2503 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002504 // Handle the special case : stylus button no longer pressed.
2505 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2506 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2507 finishDragAndDrop(entry.displayId, x, y);
2508 return;
2509 }
2510
Prabir Pradhand65552b2021-10-07 11:23:50 -07002511 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2512 // we have an explicit reason to support it.
2513 constexpr bool isStylus = false;
2514
chaviw98318de2021-05-19 16:45:23 -05002515 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002516 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002517 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002518 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002519 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2520 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2521 if (mDragState->dragHoverWindowHandle != nullptr) {
2522 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2523 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002524 }
arthurhung6d4bed92021-03-17 11:59:33 +08002525 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002526 }
2527 // enqueue drag location if needed.
2528 if (hoverWindowHandle != nullptr) {
2529 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2530 }
arthurhung6d4bed92021-03-17 11:59:33 +08002531 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2532 finishDragAndDrop(entry.displayId, x, y);
2533 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002534 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002535 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002536 }
2537}
2538
chaviw98318de2021-05-19 16:45:23 -05002539void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 int32_t targetFlags, BitSet32 pointerIds,
2541 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002542 std::vector<InputTarget>::iterator it =
2543 std::find_if(inputTargets.begin(), inputTargets.end(),
2544 [&windowHandle](const InputTarget& inputTarget) {
2545 return inputTarget.inputChannel->getConnectionToken() ==
2546 windowHandle->getToken();
2547 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002548
chaviw98318de2021-05-19 16:45:23 -05002549 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002550
2551 if (it == inputTargets.end()) {
2552 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002553 std::shared_ptr<InputChannel> inputChannel =
2554 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002555 if (inputChannel == nullptr) {
2556 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2557 return;
2558 }
2559 inputTarget.inputChannel = inputChannel;
2560 inputTarget.flags = targetFlags;
2561 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002562 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2563 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002564 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002565 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002566 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002567 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002568 inputTargets.push_back(inputTarget);
2569 it = inputTargets.end() - 1;
2570 }
2571
2572 ALOG_ASSERT(it->flags == targetFlags);
2573 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2574
chaviw1ff3d1e2020-07-01 15:53:47 -07002575 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576}
2577
Michael Wright3dd60e22019-03-27 22:06:44 +00002578void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002579 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002580 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2581 mGlobalMonitorsByDisplay.find(displayId);
2582
2583 if (it != mGlobalMonitorsByDisplay.end()) {
2584 const std::vector<Monitor>& monitors = it->second;
2585 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002586 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 }
2589}
2590
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002591void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002593 InputTarget target;
2594 target.inputChannel = monitor.inputChannel;
2595 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002596 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002597 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002598 const auto& displayTransform = it->second.transform;
2599 target.displayTransform = displayTransform;
2600 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002601 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002602 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002603 inputTargets.push_back(target);
2604}
2605
chaviw98318de2021-05-19 16:45:23 -05002606bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607 const InjectionState* injectionState) {
2608 if (injectionState &&
2609 (windowHandle == nullptr ||
2610 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2611 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002612 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002614 "owned by uid %d",
2615 injectionState->injectorPid, injectionState->injectorUid,
2616 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 } else {
2618 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002619 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
2621 return false;
2622 }
2623 return true;
2624}
2625
Robert Carrc9bf1d32020-04-13 17:21:08 -07002626/**
2627 * Indicate whether one window handle should be considered as obscuring
2628 * another window handle. We only check a few preconditions. Actually
2629 * checking the bounds is left to the caller.
2630 */
chaviw98318de2021-05-19 16:45:23 -05002631static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2632 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002633 // Compare by token so cloned layers aren't counted
2634 if (haveSameToken(windowHandle, otherHandle)) {
2635 return false;
2636 }
2637 auto info = windowHandle->getInfo();
2638 auto otherInfo = otherHandle->getInfo();
2639 if (!otherInfo->visible) {
2640 return false;
chaviw98318de2021-05-19 16:45:23 -05002641 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002642 // Those act as if they were invisible, so we don't need to flag them.
2643 // We do want to potentially flag touchable windows even if they have 0
2644 // opacity, since they can consume touches and alter the effects of the
2645 // user interaction (eg. apps that rely on
2646 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2647 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2648 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002649 } else if (info->ownerUid == otherInfo->ownerUid) {
2650 // If ownerUid is the same we don't generate occlusion events as there
2651 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002652 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002653 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002654 return false;
2655 } else if (otherInfo->displayId != info->displayId) {
2656 return false;
2657 }
2658 return true;
2659}
2660
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002661/**
2662 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2663 * untrusted, one should check:
2664 *
2665 * 1. If result.hasBlockingOcclusion is true.
2666 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2667 * BLOCK_UNTRUSTED.
2668 *
2669 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2670 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2671 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2672 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2673 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2674 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2675 *
2676 * If neither of those is true, then it means the touch can be allowed.
2677 */
2678InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002679 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2680 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002681 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002682 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002683 TouchOcclusionInfo info;
2684 info.hasBlockingOcclusion = false;
2685 info.obscuringOpacity = 0;
2686 info.obscuringUid = -1;
2687 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002688 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002689 if (windowHandle == otherHandle) {
2690 break; // All future windows are below us. Exit early.
2691 }
chaviw98318de2021-05-19 16:45:23 -05002692 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002693 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2694 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002695 if (DEBUG_TOUCH_OCCLUSION) {
2696 info.debugInfo.push_back(
2697 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2698 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002699 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2700 // we perform the checks below to see if the touch can be propagated or not based on the
2701 // window's touch occlusion mode
2702 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2703 info.hasBlockingOcclusion = true;
2704 info.obscuringUid = otherInfo->ownerUid;
2705 info.obscuringPackage = otherInfo->packageName;
2706 break;
2707 }
2708 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2709 uint32_t uid = otherInfo->ownerUid;
2710 float opacity =
2711 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2712 // Given windows A and B:
2713 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2714 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2715 opacityByUid[uid] = opacity;
2716 if (opacity > info.obscuringOpacity) {
2717 info.obscuringOpacity = opacity;
2718 info.obscuringUid = uid;
2719 info.obscuringPackage = otherInfo->packageName;
2720 }
2721 }
2722 }
2723 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002724 if (DEBUG_TOUCH_OCCLUSION) {
2725 info.debugInfo.push_back(
2726 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2727 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002728 return info;
2729}
2730
chaviw98318de2021-05-19 16:45:23 -05002731std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002732 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002733 return StringPrintf(INDENT2
2734 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2735 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2736 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2737 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002738 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002739 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002740 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2741 info->frameTop, info->frameRight, info->frameBottom,
2742 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002743 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2744 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2745 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002746}
2747
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002748bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2749 if (occlusionInfo.hasBlockingOcclusion) {
2750 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2751 occlusionInfo.obscuringUid);
2752 return false;
2753 }
2754 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2755 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2756 "%.2f, maximum allowed = %.2f)",
2757 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2758 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2759 return false;
2760 }
2761 return true;
2762}
2763
chaviw98318de2021-05-19 16:45:23 -05002764bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002767 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2768 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002769 if (windowHandle == otherHandle) {
2770 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 }
chaviw98318de2021-05-19 16:45:23 -05002772 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002773 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002774 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 return true;
2776 }
2777 }
2778 return false;
2779}
2780
chaviw98318de2021-05-19 16:45:23 -05002781bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002782 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002783 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2784 const WindowInfo* windowInfo = windowHandle->getInfo();
2785 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002786 if (windowHandle == otherHandle) {
2787 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002788 }
chaviw98318de2021-05-19 16:45:23 -05002789 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002790 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002791 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002792 return true;
2793 }
2794 }
2795 return false;
2796}
2797
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002798std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002799 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002800 if (applicationHandle != nullptr) {
2801 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002802 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 } else {
2804 return applicationHandle->getName();
2805 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002806 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002807 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002809 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811}
2812
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002813void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002814 if (!isUserActivityEvent(eventEntry)) {
2815 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002816 return;
2817 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002818 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002819 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002820 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002821 const WindowInfo* info = focusedWindowHandle->getInfo();
2822 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002823 if (DEBUG_DISPATCH_CYCLE) {
2824 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 return;
2827 }
2828 }
2829
2830 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002831 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002832 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002833 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2834 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 return;
2836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002838 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 eventType = USER_ACTIVITY_EVENT_TOUCH;
2840 }
2841 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002843 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002844 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2845 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 return;
2847 }
2848 eventType = USER_ACTIVITY_EVENT_BUTTON;
2849 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002851 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002852 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002853 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002854 break;
2855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 }
2857
Prabir Pradhancef936d2021-07-21 16:17:52 +00002858 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2859 REQUIRES(mLock) {
2860 scoped_unlock unlock(mLock);
2861 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2862 };
2863 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864}
2865
2866void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002867 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002868 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002869 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002870 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002872 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002873 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002874 ATRACE_NAME(message.c_str());
2875 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002876 if (DEBUG_DISPATCH_CYCLE) {
2877 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2878 "globalScaleFactor=%f, pointerIds=0x%x %s",
2879 connection->getInputChannelName().c_str(), inputTarget.flags,
2880 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2881 inputTarget.getPointerInfoString().c_str());
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
2884 // Skip this event if the connection status is not normal.
2885 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002886 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002887 if (DEBUG_DISPATCH_CYCLE) {
2888 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002889 connection->getInputChannelName().c_str(),
2890 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 return;
2893 }
2894
2895 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002896 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2897 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2898 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002899 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002901 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002902 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002903 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002904 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 if (!splitMotionEntry) {
2906 return; // split event was dropped
2907 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002908 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2909 std::string reason = std::string("reason=pointer cancel on split window");
2910 android_log_event_list(LOGTAG_INPUT_CANCEL)
2911 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2912 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002913 if (DEBUG_FOCUS) {
2914 ALOGD("channel '%s' ~ Split motion event.",
2915 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002916 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002917 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002918 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2919 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 return;
2921 }
2922 }
2923
2924 // Not splitting. Enqueue dispatch entries for the event as is.
2925 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2926}
2927
2928void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002931 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002932 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002934 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002935 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002936 ATRACE_NAME(message.c_str());
2937 }
2938
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002939 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
2941 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002942 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002944 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002946 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002948 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002950 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002952 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954
2955 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002956 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 startDispatchCycleLocked(currentTime, connection);
2958 }
2959}
2960
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002962 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002963 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002965 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2967 connection->getInputChannelName().c_str(),
2968 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002969 ATRACE_NAME(message.c_str());
2970 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002971 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 if (!(inputTargetFlags & dispatchMode)) {
2973 return;
2974 }
2975 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2976
2977 // This is a new event.
2978 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002979 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002980 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002982 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2983 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002986 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002987 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002989 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002990 dispatchEntry->resolvedAction = keyEntry.action;
2991 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002992
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2994 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002995 if (DEBUG_DISPATCH_CYCLE) {
2996 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2997 "event",
2998 connection->getInputChannelName().c_str());
2999 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003000 return; // skip the inconsistent event
3001 }
3002 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003005 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003007 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3008 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3009 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3010 static_cast<int32_t>(IdGenerator::Source::OTHER);
3011 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3013 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3014 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3015 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3016 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3017 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3018 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3019 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3020 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3021 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3022 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003023 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003024 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003025 }
3026 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003027 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3028 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003029 if (DEBUG_DISPATCH_CYCLE) {
3030 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3031 "enter event",
3032 connection->getInputChannelName().c_str());
3033 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003034 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3035 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3041 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3042 }
3043 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3044 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3048 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003049 if (DEBUG_DISPATCH_CYCLE) {
3050 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3051 "event",
3052 connection->getInputChannelName().c_str());
3053 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 return; // skip the inconsistent event
3055 }
3056
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003057 dispatchEntry->resolvedEventId =
3058 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3059 ? mIdGenerator.nextId()
3060 : motionEntry.id;
3061 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3062 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3063 ") to MotionEvent(id=0x%" PRIx32 ").",
3064 motionEntry.id, dispatchEntry->resolvedEventId);
3065 ATRACE_NAME(message.c_str());
3066 }
3067
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003068 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3069 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3070 // Skip reporting pointer down outside focus to the policy.
3071 break;
3072 }
3073
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003074 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003075 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076
3077 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003079 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003080 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003081 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3082 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003083 break;
3084 }
Chris Yef59a2f42020-10-16 12:55:26 -07003085 case EventEntry::Type::SENSOR: {
3086 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3087 break;
3088 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003089 case EventEntry::Type::CONFIGURATION_CHANGED:
3090 case EventEntry::Type::DEVICE_RESET: {
3091 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003092 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003093 break;
3094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 }
3096
3097 // Remember that we are waiting for this dispatch to complete.
3098 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003099 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 }
3101
3102 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003103 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003104 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003105}
3106
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003107/**
3108 * This function is purely for debugging. It helps us understand where the user interaction
3109 * was taking place. For example, if user is touching launcher, we will see a log that user
3110 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3111 * We will see both launcher and wallpaper in that list.
3112 * Once the interaction with a particular set of connections starts, no new logs will be printed
3113 * until the set of interacted connections changes.
3114 *
3115 * The following items are skipped, to reduce the logspam:
3116 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3117 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3118 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3119 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3120 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003121 */
3122void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3123 const std::vector<InputTarget>& targets) {
3124 // Skip ACTION_UP events, and all events other than keys and motions
3125 if (entry.type == EventEntry::Type::KEY) {
3126 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3127 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3128 return;
3129 }
3130 } else if (entry.type == EventEntry::Type::MOTION) {
3131 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3132 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3133 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3134 return;
3135 }
3136 } else {
3137 return; // Not a key or a motion
3138 }
3139
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003140 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003141 std::vector<sp<Connection>> newConnections;
3142 for (const InputTarget& target : targets) {
3143 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3144 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3145 continue; // Skip windows that receive ACTION_OUTSIDE
3146 }
3147
3148 sp<IBinder> token = target.inputChannel->getConnectionToken();
3149 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003150 if (connection == nullptr) {
3151 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003152 }
3153 newConnectionTokens.insert(std::move(token));
3154 newConnections.emplace_back(connection);
3155 }
3156 if (newConnectionTokens == mInteractionConnectionTokens) {
3157 return; // no change
3158 }
3159 mInteractionConnectionTokens = newConnectionTokens;
3160
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003161 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003162 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003163 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003164 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003165 std::string message = "Interaction with: " + targetList;
3166 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003167 message += "<none>";
3168 }
3169 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3170}
3171
chaviwfd6d3512019-03-25 13:23:49 -07003172void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003173 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003174 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003175 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3176 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003177 return;
3178 }
3179
Vishnu Nairc519ff72021-01-21 08:23:08 -08003180 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003181 if (focusedToken == token) {
3182 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003183 return;
3184 }
3185
Prabir Pradhancef936d2021-07-21 16:17:52 +00003186 auto command = [this, token]() REQUIRES(mLock) {
3187 scoped_unlock unlock(mLock);
3188 mPolicy->onPointerDownOutsideFocus(token);
3189 };
3190 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191}
3192
3193void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003195 if (ATRACE_ENABLED()) {
3196 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003198 ATRACE_NAME(message.c_str());
3199 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 if (DEBUG_DISPATCH_CYCLE) {
3201 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003204 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003205 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003207 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003208 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003209 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210
3211 // Publish the event.
3212 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003213 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3214 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003215 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003216 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3217 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 status = connection->inputPublisher
3221 .publishKeyEvent(dispatchEntry->seq,
3222 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3223 keyEntry.source, keyEntry.displayId,
3224 std::move(hmac), dispatchEntry->resolvedAction,
3225 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3226 keyEntry.scanCode, keyEntry.metaState,
3227 keyEntry.repeatCount, keyEntry.downTime,
3228 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
3231
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003232 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003233 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003237
chaviw82357092020-01-28 13:13:06 -08003238 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3241 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003242 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003243 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3244 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003245 // Don't apply window scale here since we don't want scale to affect raw
3246 // coordinates. The scale will be sent back to the client and applied
3247 // later when requesting relative coordinates.
3248 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3249 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 }
3251 usingCoords = scaledCoords;
3252 }
3253 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 // We don't want the dispatch target to know.
3255 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 scaledCoords[i].clear();
3258 }
3259 usingCoords = scaledCoords;
3260 }
3261 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003263 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264
3265 // Publish the motion event.
3266 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003267 .publishMotionEvent(dispatchEntry->seq,
3268 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003269 motionEntry.deviceId, motionEntry.source,
3270 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003271 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003272 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 motionEntry.edgeFlags, motionEntry.metaState,
3275 motionEntry.buttonState,
3276 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003277 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003278 motionEntry.xPrecision, motionEntry.yPrecision,
3279 motionEntry.xCursorPosition,
3280 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003281 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003282 motionEntry.downTime, motionEntry.eventTime,
3283 motionEntry.pointerCount,
3284 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003285 break;
3286 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003287
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003288 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003289 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003290 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003292 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003293 break;
3294 }
3295
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003296 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3297 const TouchModeEntry& touchModeEntry =
3298 static_cast<const TouchModeEntry&>(eventEntry);
3299 status = connection->inputPublisher
3300 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3301 touchModeEntry.inTouchMode);
3302
3303 break;
3304 }
3305
Prabir Pradhan99987712020-11-10 18:43:05 -08003306 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3307 const auto& captureEntry =
3308 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3309 status = connection->inputPublisher
3310 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003311 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003312 break;
3313 }
3314
arthurhungb89ccb02020-12-30 16:19:01 +08003315 case EventEntry::Type::DRAG: {
3316 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3317 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3318 dragEntry.id, dragEntry.x,
3319 dragEntry.y,
3320 dragEntry.isExiting);
3321 break;
3322 }
3323
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003324 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003325 case EventEntry::Type::DEVICE_RESET:
3326 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003327 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003328 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
3332
3333 // Check the result.
3334 if (status) {
3335 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003336 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 "This is unexpected because the wait queue is empty, so the pipe "
3339 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003340 "event to it, status=%s(%d)",
3341 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3342 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3344 } else {
3345 // Pipe is full and we are waiting for the app to finish process some events
3346 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003347 if (DEBUG_DISPATCH_CYCLE) {
3348 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3349 "waiting for the application to catch up",
3350 connection->getInputChannelName().c_str());
3351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
3353 } else {
3354 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003355 "status=%s(%d)",
3356 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3357 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3359 }
3360 return;
3361 }
3362
3363 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003364 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3365 connection->outboundQueue.end(),
3366 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003367 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003368 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003369 if (connection->responsive) {
3370 mAnrTracker.insert(dispatchEntry->timeoutTime,
3371 connection->inputChannel->getConnectionToken());
3372 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003373 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375}
3376
chaviw09c8d2d2020-08-24 15:48:26 -07003377std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3378 size_t size;
3379 switch (event.type) {
3380 case VerifiedInputEvent::Type::KEY: {
3381 size = sizeof(VerifiedKeyEvent);
3382 break;
3383 }
3384 case VerifiedInputEvent::Type::MOTION: {
3385 size = sizeof(VerifiedMotionEvent);
3386 break;
3387 }
3388 }
3389 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3390 return mHmacKeyManager.sign(start, size);
3391}
3392
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003393const std::array<uint8_t, 32> InputDispatcher::getSignature(
3394 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003395 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3396 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003397 // Only sign events up and down events as the purely move events
3398 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003399 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003400 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003401
3402 VerifiedMotionEvent verifiedEvent =
3403 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3404 verifiedEvent.actionMasked = actionMasked;
3405 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3406 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003407}
3408
3409const std::array<uint8_t, 32> InputDispatcher::getSignature(
3410 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3411 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3412 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3413 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003414 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003415}
3416
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003418 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003419 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003420 if (DEBUG_DISPATCH_CYCLE) {
3421 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3422 connection->getInputChannelName().c_str(), seq, toString(handled));
3423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003425 if (connection->status == Connection::Status::BROKEN ||
3426 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 return;
3428 }
3429
3430 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003431 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3432 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3433 };
3434 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435}
3436
3437void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 const sp<Connection>& connection,
3439 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003440 if (DEBUG_DISPATCH_CYCLE) {
3441 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3442 connection->getInputChannelName().c_str(), toString(notify));
3443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444
3445 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003446 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003447 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003448 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003449 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450
3451 // The connection appears to be unrecoverably broken.
3452 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003453 if (connection->status == Connection::Status::NORMAL) {
3454 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455
3456 if (notify) {
3457 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003458 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3459 connection->getInputChannelName().c_str());
3460
3461 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003462 scoped_unlock unlock(mLock);
3463 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3464 };
3465 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 }
3467 }
3468}
3469
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003470void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3471 while (!queue.empty()) {
3472 DispatchEntry* dispatchEntry = queue.front();
3473 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003474 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
3476}
3477
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003478void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003480 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481 }
3482 delete dispatchEntry;
3483}
3484
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003485int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3486 std::scoped_lock _l(mLock);
3487 sp<Connection> connection = getConnectionLocked(connectionToken);
3488 if (connection == nullptr) {
3489 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3490 connectionToken.get(), events);
3491 return 0; // remove the callback
3492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003494 bool notify;
3495 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3496 if (!(events & ALOOPER_EVENT_INPUT)) {
3497 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3498 "events=0x%x",
3499 connection->getInputChannelName().c_str(), events);
3500 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 }
3502
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003503 nsecs_t currentTime = now();
3504 bool gotOne = false;
3505 status_t status = OK;
3506 for (;;) {
3507 Result<InputPublisher::ConsumerResponse> result =
3508 connection->inputPublisher.receiveConsumerResponse();
3509 if (!result.ok()) {
3510 status = result.error().code();
3511 break;
3512 }
3513
3514 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3515 const InputPublisher::Finished& finish =
3516 std::get<InputPublisher::Finished>(*result);
3517 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3518 finish.consumeTime);
3519 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003520 if (shouldReportMetricsForConnection(*connection)) {
3521 const InputPublisher::Timeline& timeline =
3522 std::get<InputPublisher::Timeline>(*result);
3523 mLatencyTracker
3524 .trackGraphicsLatency(timeline.inputEventId,
3525 connection->inputChannel->getConnectionToken(),
3526 std::move(timeline.graphicsTimeline));
3527 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003528 }
3529 gotOne = true;
3530 }
3531 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003532 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003533 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 return 1;
3535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
3537
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003538 notify = status != DEAD_OBJECT || !connection->monitor;
3539 if (notify) {
3540 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3541 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3542 status);
3543 }
3544 } else {
3545 // Monitor channels are never explicitly unregistered.
3546 // We do it automatically when the remote endpoint is closed so don't warn about them.
3547 const bool stillHaveWindowHandle =
3548 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3549 notify = !connection->monitor && stillHaveWindowHandle;
3550 if (notify) {
3551 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3552 connection->getInputChannelName().c_str(), events);
3553 }
3554 }
3555
3556 // Remove the channel.
3557 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3558 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559}
3560
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003561void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003563 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003564 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 }
3566}
3567
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003568void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003569 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003570 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3571 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3572}
3573
3574void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3575 const CancelationOptions& options,
3576 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3577 for (const auto& it : monitorsByDisplay) {
3578 const std::vector<Monitor>& monitors = it.second;
3579 for (const Monitor& monitor : monitors) {
3580 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003581 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003582 }
3583}
3584
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003586 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003587 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003588 if (connection == nullptr) {
3589 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003591
3592 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593}
3594
3595void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3596 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003597 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 return;
3599 }
3600
3601 nsecs_t currentTime = now();
3602
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003603 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003604 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003606 if (cancelationEvents.empty()) {
3607 return;
3608 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003609 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3610 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3611 "with reality: %s, mode=%d.",
3612 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3613 options.mode);
3614 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003615
Arthur Hungb3307ee2021-10-14 10:57:37 +00003616 std::string reason = std::string("reason=").append(options.reason);
3617 android_log_event_list(LOGTAG_INPUT_CANCEL)
3618 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3619
Svet Ganov5d3bc372020-01-26 23:11:07 -08003620 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003621 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003622 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3623 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003624 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003625 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003626 target.globalScaleFactor = windowInfo->globalScaleFactor;
3627 }
3628 target.inputChannel = connection->inputChannel;
3629 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3630
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003631 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003633 switch (cancelationEventEntry->type) {
3634 case EventEntry::Type::KEY: {
3635 logOutboundKeyDetails("cancel - ",
3636 static_cast<const KeyEntry&>(*cancelationEventEntry));
3637 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003639 case EventEntry::Type::MOTION: {
3640 logOutboundMotionDetails("cancel - ",
3641 static_cast<const MotionEntry&>(*cancelationEventEntry));
3642 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003644 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003645 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003646 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3647 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003648 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003649 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003650 break;
3651 }
3652 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003653 case EventEntry::Type::DEVICE_RESET:
3654 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003655 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003656 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003657 break;
3658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
3660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003661 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3662 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003664
3665 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666}
3667
Svet Ganov5d3bc372020-01-26 23:11:07 -08003668void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3669 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003670 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003671 return;
3672 }
3673
3674 nsecs_t currentTime = now();
3675
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003677 connection->inputState.synthesizePointerDownEvents(currentTime);
3678
3679 if (downEvents.empty()) {
3680 return;
3681 }
3682
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003683 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003684 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3685 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003686 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003687
3688 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003689 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003690 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3691 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003692 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003693 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003694 target.globalScaleFactor = windowInfo->globalScaleFactor;
3695 }
3696 target.inputChannel = connection->inputChannel;
3697 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3698
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003699 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003700 switch (downEventEntry->type) {
3701 case EventEntry::Type::MOTION: {
3702 logOutboundMotionDetails("down - ",
3703 static_cast<const MotionEntry&>(*downEventEntry));
3704 break;
3705 }
3706
3707 case EventEntry::Type::KEY:
3708 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003709 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003710 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003711 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003712 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003713 case EventEntry::Type::SENSOR:
3714 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003715 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003716 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003717 break;
3718 }
3719 }
3720
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003721 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3722 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723 }
3724
3725 startDispatchCycleLocked(currentTime, connection);
3726}
3727
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003728std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3729 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 ALOG_ASSERT(pointerIds.value != 0);
3731
3732 uint32_t splitPointerIndexMap[MAX_POINTERS];
3733 PointerProperties splitPointerProperties[MAX_POINTERS];
3734 PointerCoords splitPointerCoords[MAX_POINTERS];
3735
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003736 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 uint32_t splitPointerCount = 0;
3738
3739 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003740 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003742 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 uint32_t pointerId = uint32_t(pointerProperties.id);
3744 if (pointerIds.hasBit(pointerId)) {
3745 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3746 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3747 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003748 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 splitPointerCount += 1;
3750 }
3751 }
3752
3753 if (splitPointerCount != pointerIds.count()) {
3754 // This is bad. We are missing some of the pointers that we expected to deliver.
3755 // Most likely this indicates that we received an ACTION_MOVE events that has
3756 // different pointer ids than we expected based on the previous ACTION_DOWN
3757 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3758 // in this way.
3759 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 "we expected there to be %d pointers. This probably means we received "
3761 "a broken sequence of pointer ids from the input device.",
3762 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003763 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
3765
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003766 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003768 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3769 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3771 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003772 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 uint32_t pointerId = uint32_t(pointerProperties.id);
3774 if (pointerIds.hasBit(pointerId)) {
3775 if (pointerIds.count() == 1) {
3776 // The first/last pointer went down/up.
3777 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003778 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003779 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3780 ? AMOTION_EVENT_ACTION_CANCEL
3781 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 } else {
3783 // A secondary pointer went down/up.
3784 uint32_t splitPointerIndex = 0;
3785 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3786 splitPointerIndex += 1;
3787 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 action = maskedAction |
3789 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 }
3791 } else {
3792 // An unrelated pointer changed.
3793 action = AMOTION_EVENT_ACTION_MOVE;
3794 }
3795 }
3796
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003797 int32_t newId = mIdGenerator.nextId();
3798 if (ATRACE_ENABLED()) {
3799 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3800 ") to MotionEvent(id=0x%" PRIx32 ").",
3801 originalMotionEntry.id, newId);
3802 ATRACE_NAME(message.c_str());
3803 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003804 std::unique_ptr<MotionEntry> splitMotionEntry =
3805 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3806 originalMotionEntry.deviceId, originalMotionEntry.source,
3807 originalMotionEntry.displayId,
3808 originalMotionEntry.policyFlags, action,
3809 originalMotionEntry.actionButton,
3810 originalMotionEntry.flags, originalMotionEntry.metaState,
3811 originalMotionEntry.buttonState,
3812 originalMotionEntry.classification,
3813 originalMotionEntry.edgeFlags,
3814 originalMotionEntry.xPrecision,
3815 originalMotionEntry.yPrecision,
3816 originalMotionEntry.xCursorPosition,
3817 originalMotionEntry.yCursorPosition,
3818 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003819 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003821 if (originalMotionEntry.injectionState) {
3822 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 splitMotionEntry->injectionState->refCount += 1;
3824 }
3825
3826 return splitMotionEntry;
3827}
3828
3829void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003830 if (DEBUG_INBOUND_EVENT_DETAILS) {
3831 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833
Antonio Kantekf16f2832021-09-28 04:39:20 +00003834 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003836 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003838 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3839 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3840 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 } // release lock
3842
3843 if (needWake) {
3844 mLooper->wake();
3845 }
3846}
3847
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003848/**
3849 * If one of the meta shortcuts is detected, process them here:
3850 * Meta + Backspace -> generate BACK
3851 * Meta + Enter -> generate HOME
3852 * This will potentially overwrite keyCode and metaState.
3853 */
3854void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003855 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003856 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3857 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3858 if (keyCode == AKEYCODE_DEL) {
3859 newKeyCode = AKEYCODE_BACK;
3860 } else if (keyCode == AKEYCODE_ENTER) {
3861 newKeyCode = AKEYCODE_HOME;
3862 }
3863 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003864 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003865 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003866 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003867 keyCode = newKeyCode;
3868 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3869 }
3870 } else if (action == AKEY_EVENT_ACTION_UP) {
3871 // In order to maintain a consistent stream of up and down events, check to see if the key
3872 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3873 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003874 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003875 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003876 auto replacementIt = mReplacedKeys.find(replacement);
3877 if (replacementIt != mReplacedKeys.end()) {
3878 keyCode = replacementIt->second;
3879 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003880 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3881 }
3882 }
3883}
3884
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003886 if (DEBUG_INBOUND_EVENT_DETAILS) {
3887 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3888 "policyFlags=0x%x, action=0x%x, "
3889 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3890 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3891 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3892 args->downTime);
3893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 if (!validateKeyEvent(args->action)) {
3895 return;
3896 }
3897
3898 uint32_t policyFlags = args->policyFlags;
3899 int32_t flags = args->flags;
3900 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003901 // InputDispatcher tracks and generates key repeats on behalf of
3902 // whatever notifies it, so repeatCount should always be set to 0
3903 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3905 policyFlags |= POLICY_FLAG_VIRTUAL;
3906 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 if (policyFlags & POLICY_FLAG_FUNCTION) {
3909 metaState |= AMETA_FUNCTION_ON;
3910 }
3911
3912 policyFlags |= POLICY_FLAG_TRUSTED;
3913
Michael Wright78f24442014-08-06 15:55:28 -07003914 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003915 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003916
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003918 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003919 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3920 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
Michael Wright2b3c3302018-03-02 17:19:13 +00003922 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003924 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3925 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003926 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928
Antonio Kantekf16f2832021-09-28 04:39:20 +00003929 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 { // acquire lock
3931 mLock.lock();
3932
3933 if (shouldSendKeyToInputFilterLocked(args)) {
3934 mLock.unlock();
3935
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003936 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3938 return; // event was consumed by the filter
3939 }
3940
3941 mLock.lock();
3942 }
3943
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003944 std::unique_ptr<KeyEntry> newEntry =
3945 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3946 args->displayId, policyFlags, args->action, flags,
3947 keyCode, args->scanCode, metaState, repeatCount,
3948 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003950 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 mLock.unlock();
3952 } // release lock
3953
3954 if (needWake) {
3955 mLooper->wake();
3956 }
3957}
3958
3959bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3960 return mInputFilterEnabled;
3961}
3962
3963void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003964 if (DEBUG_INBOUND_EVENT_DETAILS) {
3965 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3966 "displayId=%" PRId32 ", policyFlags=0x%x, "
3967 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3968 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3969 "yCursorPosition=%f, downTime=%" PRId64,
3970 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3971 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3972 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3973 args->xCursorPosition, args->yCursorPosition, args->downTime);
3974 for (uint32_t i = 0; i < args->pointerCount; i++) {
3975 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3976 "x=%f, y=%f, pressure=%f, size=%f, "
3977 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3978 "orientation=%f",
3979 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3980 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3981 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3982 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3983 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3984 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3985 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3986 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3987 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3988 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003991 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3992 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 return;
3994 }
3995
3996 uint32_t policyFlags = args->policyFlags;
3997 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003998
3999 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004000 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004001 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4002 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Antonio Kantekf16f2832021-09-28 04:39:20 +00004006 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 { // acquire lock
4008 mLock.lock();
4009
4010 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004011 ui::Transform displayTransform;
4012 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4013 displayTransform = it->second.transform;
4014 }
4015
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 mLock.unlock();
4017
4018 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004019 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4020 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004021 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004022 displayTransform, args->xPrecision, args->yPrecision,
4023 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004024 args->downTime, args->eventTime, args->pointerCount,
4025 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026
4027 policyFlags |= POLICY_FLAG_FILTERED;
4028 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4029 return; // event was consumed by the filter
4030 }
4031
4032 mLock.lock();
4033 }
4034
4035 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 std::unique_ptr<MotionEntry> newEntry =
4037 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4038 args->source, args->displayId, policyFlags,
4039 args->action, args->actionButton, args->flags,
4040 args->metaState, args->buttonState,
4041 args->classification, args->edgeFlags,
4042 args->xPrecision, args->yPrecision,
4043 args->xCursorPosition, args->yCursorPosition,
4044 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004045 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004047 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4048 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4049 !mInputFilterEnabled) {
4050 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4051 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4052 }
4053
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004054 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 mLock.unlock();
4056 } // release lock
4057
4058 if (needWake) {
4059 mLooper->wake();
4060 }
4061}
4062
Chris Yef59a2f42020-10-16 12:55:26 -07004063void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004064 if (DEBUG_INBOUND_EVENT_DETAILS) {
4065 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4066 " sensorType=%s",
4067 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004068 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004069 }
Chris Yef59a2f42020-10-16 12:55:26 -07004070
Antonio Kantekf16f2832021-09-28 04:39:20 +00004071 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004072 { // acquire lock
4073 mLock.lock();
4074
4075 // Just enqueue a new sensor event.
4076 std::unique_ptr<SensorEntry> newEntry =
4077 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4078 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4079 args->sensorType, args->accuracy,
4080 args->accuracyChanged, args->values);
4081
4082 needWake = enqueueInboundEventLocked(std::move(newEntry));
4083 mLock.unlock();
4084 } // release lock
4085
4086 if (needWake) {
4087 mLooper->wake();
4088 }
4089}
4090
Chris Yefb552902021-02-03 17:18:37 -08004091void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004092 if (DEBUG_INBOUND_EVENT_DETAILS) {
4093 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4094 args->deviceId, args->isOn);
4095 }
Chris Yefb552902021-02-03 17:18:37 -08004096 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4097}
4098
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004100 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101}
4102
4103void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004104 if (DEBUG_INBOUND_EVENT_DETAILS) {
4105 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4106 "switchMask=0x%08x",
4107 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
4110 uint32_t policyFlags = args->policyFlags;
4111 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113}
4114
4115void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004116 if (DEBUG_INBOUND_EVENT_DETAILS) {
4117 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4118 args->deviceId);
4119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
Antonio Kantekf16f2832021-09-28 04:39:20 +00004121 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004123 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004125 std::unique_ptr<DeviceResetEntry> newEntry =
4126 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4127 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 } // release lock
4129
4130 if (needWake) {
4131 mLooper->wake();
4132 }
4133}
4134
Prabir Pradhan7e186182020-11-10 13:56:45 -08004135void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004136 if (DEBUG_INBOUND_EVENT_DETAILS) {
4137 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004138 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004139 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004140
Antonio Kantekf16f2832021-09-28 04:39:20 +00004141 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004142 { // acquire lock
4143 std::scoped_lock _l(mLock);
4144 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004145 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004146 needWake = enqueueInboundEventLocked(std::move(entry));
4147 } // release lock
4148
4149 if (needWake) {
4150 mLooper->wake();
4151 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004152}
4153
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004154InputEventInjectionResult InputDispatcher::injectInputEvent(
4155 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4156 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 if (DEBUG_INBOUND_EVENT_DETAILS) {
4158 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4159 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4160 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4161 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004162 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163
4164 policyFlags |= POLICY_FLAG_INJECTED;
4165 if (hasInjectionPermission(injectorPid, injectorUid)) {
4166 policyFlags |= POLICY_FLAG_TRUSTED;
4167 }
4168
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004169 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004170 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4171 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4172 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4173 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4174 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004175 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004176 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004177 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 }
4179
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004180 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004182 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004183 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4184 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004186 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004189 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004190 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4191 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4192 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004193 int32_t keyCode = incomingKey.getKeyCode();
4194 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004195 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004197 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004198 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004199 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4200 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4201 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004203 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4204 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004205 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206
4207 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4208 android::base::Timer t;
4209 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4210 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4211 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4212 std::to_string(t.duration().count()).c_str());
4213 }
4214 }
4215
4216 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004217 std::unique_ptr<KeyEntry> injectedEntry =
4218 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004219 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004220 incomingKey.getDisplayId(), policyFlags, action,
4221 flags, keyCode, incomingKey.getScanCode(), metaState,
4222 incomingKey.getRepeatCount(),
4223 incomingKey.getDownTime());
4224 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
4227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004229 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004230 const int32_t action = motionEvent.getAction();
4231 const bool isPointerEvent =
4232 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4233 // If a pointer event has no displayId specified, inject it to the default display.
4234 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4235 ? ADISPLAY_ID_DEFAULT
4236 : event->getDisplayId();
4237 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004238 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004239 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004240 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004242 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 }
4244
4245 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 android::base::Timer t;
4248 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4249 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4250 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4251 std::to_string(t.duration().count()).c_str());
4252 }
4253 }
4254
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004255 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4256 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4257 }
4258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004260 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4261 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004262 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004263 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4264 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004265 displayId, policyFlags, action, actionButton,
4266 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004267 motionEvent.getButtonState(),
4268 motionEvent.getClassification(),
4269 motionEvent.getEdgeFlags(),
4270 motionEvent.getXPrecision(),
4271 motionEvent.getYPrecision(),
4272 motionEvent.getRawXCursorPosition(),
4273 motionEvent.getRawYCursorPosition(),
4274 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004275 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004276 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004278 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004279 sampleEventTimes += 1;
4280 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004282 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4283 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004284 displayId, policyFlags, action, actionButton,
4285 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286 motionEvent.getButtonState(),
4287 motionEvent.getClassification(),
4288 motionEvent.getEdgeFlags(),
4289 motionEvent.getXPrecision(),
4290 motionEvent.getYPrecision(),
4291 motionEvent.getRawXCursorPosition(),
4292 motionEvent.getRawYCursorPosition(),
4293 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004294 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004295 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004296 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4297 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004298 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 }
4300 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004304 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 }
4307
4308 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 injectionState->injectionIsAsync = true;
4311 }
4312
4313 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004314 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315
4316 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004317 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004318 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004319 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
4321
4322 mLock.unlock();
4323
4324 if (needWake) {
4325 mLooper->wake();
4326 }
4327
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004328 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004330 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004332 if (syncMode == InputEventInjectionSync::NONE) {
4333 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 } else {
4335 for (;;) {
4336 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 break;
4339 }
4340
4341 nsecs_t remainingTimeout = endTime - now();
4342 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004343 if (DEBUG_INJECTION) {
4344 ALOGD("injectInputEvent - Timed out waiting for injection result "
4345 "to become available.");
4346 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004347 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 break;
4349 }
4350
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004351 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
4353
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004354 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4355 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004357 if (DEBUG_INJECTION) {
4358 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4359 injectionState->pendingForegroundDispatches);
4360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 nsecs_t remainingTimeout = endTime - now();
4362 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004363 if (DEBUG_INJECTION) {
4364 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4365 "dispatches to finish.");
4366 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004367 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 break;
4369 }
4370
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004371 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 }
4373 }
4374 }
4375
4376 injectionState->release();
4377 } // release lock
4378
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004379 if (DEBUG_INJECTION) {
4380 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4381 injectionResult, injectorPid, injectorUid);
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
4384 return injectionResult;
4385}
4386
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004387std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004388 std::array<uint8_t, 32> calculatedHmac;
4389 std::unique_ptr<VerifiedInputEvent> result;
4390 switch (event.getType()) {
4391 case AINPUT_EVENT_TYPE_KEY: {
4392 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4393 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4394 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004395 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004396 break;
4397 }
4398 case AINPUT_EVENT_TYPE_MOTION: {
4399 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4400 VerifiedMotionEvent verifiedMotionEvent =
4401 verifiedMotionEventFromMotionEvent(motionEvent);
4402 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004403 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004404 break;
4405 }
4406 default: {
4407 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4408 return nullptr;
4409 }
4410 }
4411 if (calculatedHmac == INVALID_HMAC) {
4412 return nullptr;
4413 }
4414 if (calculatedHmac != event.getHmac()) {
4415 return nullptr;
4416 }
4417 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004418}
4419
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004421 return injectorUid == 0 ||
4422 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423}
4424
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004425void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004426 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004427 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004429 if (DEBUG_INJECTION) {
4430 ALOGD("Setting input event injection result to %d. "
4431 "injectorPid=%d, injectorUid=%d",
4432 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004435 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 // Log the outcome since the injector did not wait for the injection result.
4437 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004438 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 ALOGV("Asynchronous input event injection succeeded.");
4440 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 ALOGW("Asynchronous input event injection failed.");
4443 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004444 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 ALOGW("Asynchronous input event injection permission denied.");
4446 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 ALOGW("Asynchronous input event injection timed out.");
4449 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 case InputEventInjectionResult::PENDING:
4451 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4452 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454 }
4455
4456 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004457 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 }
4459}
4460
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004461void InputDispatcher::transformMotionEntryForInjectionLocked(
4462 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004463 // Input injection works in the logical display coordinate space, but the input pipeline works
4464 // display space, so we need to transform the injected events accordingly.
4465 const auto it = mDisplayInfos.find(entry.displayId);
4466 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004467 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004468
4469 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4470 PointerCoords& pc = entry.pointerCoords[i];
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004471 // Make a copy of the injected coords. We cannot change them in place because some of them
4472 // are interdependent (for example, X coordinate might depend on the Y coordinate).
4473 PointerCoords injectedCoords = entry.pointerCoords[i];
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004474
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004475 BitSet64 bits(injectedCoords.bits);
4476 while (!bits.isEmpty()) {
4477 const auto axis = static_cast<int32_t>(bits.clearFirstMarkedBit());
4478 const float value =
4479 MotionEvent::calculateTransformedAxisValue(axis, entry.source,
4480 transformToDisplay, injectedCoords);
4481 pc.setAxisValue(axis, value);
4482 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004483 }
4484}
4485
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4487 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 if (injectionState) {
4489 injectionState->pendingForegroundDispatches += 1;
4490 }
4491}
4492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4494 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 if (injectionState) {
4496 injectionState->pendingForegroundDispatches -= 1;
4497
4498 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004499 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
4501 }
4502}
4503
chaviw98318de2021-05-19 16:45:23 -05004504const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004505 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004506 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004507 auto it = mWindowHandlesByDisplay.find(displayId);
4508 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004509}
4510
chaviw98318de2021-05-19 16:45:23 -05004511sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004512 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004513 if (windowHandleToken == nullptr) {
4514 return nullptr;
4515 }
4516
Arthur Hungb92218b2018-08-14 12:00:21 +08004517 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004518 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4519 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004520 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004521 return windowHandle;
4522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004525 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526}
4527
chaviw98318de2021-05-19 16:45:23 -05004528sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4529 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004530 if (windowHandleToken == nullptr) {
4531 return nullptr;
4532 }
4533
chaviw98318de2021-05-19 16:45:23 -05004534 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004535 if (windowHandle->getToken() == windowHandleToken) {
4536 return windowHandle;
4537 }
4538 }
4539 return nullptr;
4540}
4541
chaviw98318de2021-05-19 16:45:23 -05004542sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4543 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004544 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004545 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4546 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004547 if (handle->getId() == windowHandle->getId() &&
4548 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004549 if (windowHandle->getInfo()->displayId != it.first) {
4550 ALOGE("Found window %s in display %" PRId32
4551 ", but it should belong to display %" PRId32,
4552 windowHandle->getName().c_str(), it.first,
4553 windowHandle->getInfo()->displayId);
4554 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004555 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004559 return nullptr;
4560}
4561
chaviw98318de2021-05-19 16:45:23 -05004562sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004563 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4564 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565}
4566
chaviw98318de2021-05-19 16:45:23 -05004567bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004568 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4569 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004570 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004571 if (connection != nullptr && noInputChannel) {
4572 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4573 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4574 return false;
4575 }
4576
4577 if (connection == nullptr) {
4578 if (!noInputChannel) {
4579 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4580 }
4581 return false;
4582 }
4583 if (!connection->responsive) {
4584 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4585 return false;
4586 }
4587 return true;
4588}
4589
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004590std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4591 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004592 auto connectionIt = mConnectionsByToken.find(token);
4593 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004594 return nullptr;
4595 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004596 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004597}
4598
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004599void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004600 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4601 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004602 // Remove all handles on a display if there are no windows left.
4603 mWindowHandlesByDisplay.erase(displayId);
4604 return;
4605 }
4606
4607 // Since we compare the pointer of input window handles across window updates, we need
4608 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004609 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4610 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4611 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004612 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004613 }
4614
chaviw98318de2021-05-19 16:45:23 -05004615 std::vector<sp<WindowInfoHandle>> newHandles;
4616 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004617 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004618 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004619 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004620 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4621 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4622 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004623 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004624 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004625 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004626 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004627 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004628 }
4629
4630 if (info->displayId != displayId) {
4631 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4632 handle->getName().c_str(), displayId, info->displayId);
4633 continue;
4634 }
4635
Robert Carredd13602020-04-13 17:24:34 -07004636 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4637 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004638 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004639 oldHandle->updateFrom(handle);
4640 newHandles.push_back(oldHandle);
4641 } else {
4642 newHandles.push_back(handle);
4643 }
4644 }
4645
4646 // Insert or replace
4647 mWindowHandlesByDisplay[displayId] = newHandles;
4648}
4649
Arthur Hung72d8dc32020-03-28 00:48:39 +00004650void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004651 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004652 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004653 { // acquire lock
4654 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004655 for (const auto& [displayId, handles] : handlesPerDisplay) {
4656 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004657 }
4658 }
4659 // Wake up poll loop since it may need to make new input dispatching choices.
4660 mLooper->wake();
4661}
4662
Arthur Hungb92218b2018-08-14 12:00:21 +08004663/**
4664 * Called from InputManagerService, update window handle list by displayId that can receive input.
4665 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4666 * If set an empty list, remove all handles from the specific display.
4667 * For focused handle, check if need to change and send a cancel event to previous one.
4668 * For removed handle, check if need to send a cancel event if already in touch.
4669 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004670void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004671 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004672 if (DEBUG_FOCUS) {
4673 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004674 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004675 windowList += iwh->getName() + " ";
4676 }
4677 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
Prabir Pradhand65552b2021-10-07 11:23:50 -07004680 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004681 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004682 const WindowInfo& info = *window->getInfo();
4683
4684 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4685 const bool noInputWindow = info.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004686 if (noInputWindow && window->getToken() != nullptr) {
4687 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4688 window->getName().c_str());
4689 window->releaseChannel();
4690 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004691
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004692 // Ensure all spy windows are trusted overlays
4693 LOG_ALWAYS_FATAL_IF(info.isSpy() && !info.trustedOverlay,
4694 "%s has feature SPY, but is not a trusted overlay.",
4695 window->getName().c_str());
4696
Prabir Pradhand65552b2021-10-07 11:23:50 -07004697 // Ensure all stylus interceptors are trusted overlays
4698 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() && !info.trustedOverlay,
4699 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4700 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004701 }
4702
Arthur Hung72d8dc32020-03-28 00:48:39 +00004703 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004704 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004706 // Save the old windows' orientation by ID before it gets updated.
4707 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004708 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004709 oldWindowOrientations.emplace(handle->getId(),
4710 handle->getInfo()->transform.getOrientation());
4711 }
4712
chaviw98318de2021-05-19 16:45:23 -05004713 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004714
chaviw98318de2021-05-19 16:45:23 -05004715 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004716 if (mLastHoverWindowHandle &&
4717 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4718 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004719 mLastHoverWindowHandle = nullptr;
4720 }
4721
Vishnu Nairc519ff72021-01-21 08:23:08 -08004722 std::optional<FocusResolver::FocusChanges> changes =
4723 mFocusResolver.setInputWindows(displayId, windowHandles);
4724 if (changes) {
4725 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004728 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4729 mTouchStatesByDisplay.find(displayId);
4730 if (stateIt != mTouchStatesByDisplay.end()) {
4731 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004732 for (size_t i = 0; i < state.windows.size();) {
4733 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004734 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004735 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 ALOGD("Touched window was removed: %s in display %" PRId32,
4737 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004738 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004739 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004740 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4741 if (touchedInputChannel != nullptr) {
4742 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4743 "touched window was removed");
4744 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004745 // Since we are about to drop the touch, cancel the events for the wallpaper as
4746 // well.
4747 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4748 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4749 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4750 if (wallpaper != nullptr) {
4751 sp<Connection> wallpaperConnection =
4752 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004753 if (wallpaperConnection != nullptr) {
4754 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4755 options);
4756 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004757 }
4758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004760 state.windows.erase(state.windows.begin() + i);
4761 } else {
4762 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 }
4764 }
arthurhungb89ccb02020-12-30 16:19:01 +08004765
arthurhung6d4bed92021-03-17 11:59:33 +08004766 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004767 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004768 if (mDragState &&
4769 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004770 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004771 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004772 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004773 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004774
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004775 // Determine if the orientation of any of the input windows have changed, and cancel all
4776 // pointer events if necessary.
4777 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4778 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4779 if (newWindowHandle != nullptr &&
4780 newWindowHandle->getInfo()->transform.getOrientation() !=
4781 oldWindowOrientations[oldWindowHandle->getId()]) {
4782 std::shared_ptr<InputChannel> inputChannel =
4783 getInputChannelLocked(newWindowHandle->getToken());
4784 if (inputChannel != nullptr) {
4785 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4786 "touched window's orientation changed");
4787 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004788 }
4789 }
4790 }
4791
Arthur Hung72d8dc32020-03-28 00:48:39 +00004792 // Release information for windows that are no longer present.
4793 // This ensures that unused input channels are released promptly.
4794 // Otherwise, they might stick around until the window handle is destroyed
4795 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004796 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004797 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004798 if (DEBUG_FOCUS) {
4799 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004800 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004801 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004802 }
chaviw291d88a2019-02-14 10:33:58 -08004803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804}
4805
4806void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004807 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004808 if (DEBUG_FOCUS) {
4809 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4810 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4811 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004812 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004813 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004814 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 } // release lock
4816
4817 // Wake up poll loop since it may need to make new input dispatching choices.
4818 mLooper->wake();
4819}
4820
Vishnu Nair599f1412021-06-21 10:39:58 -07004821void InputDispatcher::setFocusedApplicationLocked(
4822 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4823 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4824 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4825
4826 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4827 return; // This application is already focused. No need to wake up or change anything.
4828 }
4829
4830 // Set the new application handle.
4831 if (inputApplicationHandle != nullptr) {
4832 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4833 } else {
4834 mFocusedApplicationHandlesByDisplay.erase(displayId);
4835 }
4836
4837 // No matter what the old focused application was, stop waiting on it because it is
4838 // no longer focused.
4839 resetNoFocusedWindowTimeoutLocked();
4840}
4841
Tiger Huang721e26f2018-07-24 22:26:19 +08004842/**
4843 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4844 * the display not specified.
4845 *
4846 * We track any unreleased events for each window. If a window loses the ability to receive the
4847 * released event, we will send a cancel event to it. So when the focused display is changed, we
4848 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4849 * display. The display-specified events won't be affected.
4850 */
4851void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004852 if (DEBUG_FOCUS) {
4853 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4854 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004855 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004856 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004857
4858 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004859 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004860 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004861 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004862 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004863 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004864 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004865 CancelationOptions
4866 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4867 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004868 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004869 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4870 }
4871 }
4872 mFocusedDisplayId = displayId;
4873
Chris Ye3c2d6f52020-08-09 10:39:48 -07004874 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004875 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004876 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004877
Vishnu Nairad321cd2020-08-20 16:40:21 -07004878 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004879 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004880 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004881 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004882 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004883 }
4884 }
4885 }
4886
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004887 if (DEBUG_FOCUS) {
4888 logDispatchStateLocked();
4889 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004890 } // release lock
4891
4892 // Wake up poll loop since it may need to make new input dispatching choices.
4893 mLooper->wake();
4894}
4895
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004897 if (DEBUG_FOCUS) {
4898 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900
4901 bool changed;
4902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004903 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904
4905 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4906 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004907 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 }
4909
4910 if (mDispatchEnabled && !enabled) {
4911 resetAndDropEverythingLocked("dispatcher is being disabled");
4912 }
4913
4914 mDispatchEnabled = enabled;
4915 mDispatchFrozen = frozen;
4916 changed = true;
4917 } else {
4918 changed = false;
4919 }
4920
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004921 if (DEBUG_FOCUS) {
4922 logDispatchStateLocked();
4923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 } // release lock
4925
4926 if (changed) {
4927 // Wake up poll loop since it may need to make new input dispatching choices.
4928 mLooper->wake();
4929 }
4930}
4931
4932void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004933 if (DEBUG_FOCUS) {
4934 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936
4937 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004938 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939
4940 if (mInputFilterEnabled == enabled) {
4941 return;
4942 }
4943
4944 mInputFilterEnabled = enabled;
4945 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4946 } // release lock
4947
4948 // Wake up poll loop since there might be work to do to drop everything.
4949 mLooper->wake();
4950}
4951
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004952void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004953 bool needWake = false;
4954 {
4955 std::scoped_lock lock(mLock);
4956 if (mInTouchMode == inTouchMode) {
4957 return;
4958 }
4959 if (DEBUG_TOUCH_MODE) {
4960 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4961 toString(inTouchMode));
4962 // TODO(b/198487159): Also print the current last interacted apps.
4963 }
4964
4965 // TODO(b/198499018): Store touch mode per display.
4966 mInTouchMode = inTouchMode;
4967
4968 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4969 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4970 needWake = enqueueInboundEventLocked(std::move(entry));
4971 } // release lock
4972
4973 if (needWake) {
4974 mLooper->wake();
4975 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004976}
4977
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004978void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4979 if (opacity < 0 || opacity > 1) {
4980 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4981 return;
4982 }
4983
4984 std::scoped_lock lock(mLock);
4985 mMaximumObscuringOpacityForTouch = opacity;
4986}
4987
4988void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4989 std::scoped_lock lock(mLock);
4990 mBlockUntrustedTouchesMode = mode;
4991}
4992
Arthur Hungabbb9d82021-09-01 14:52:30 +00004993std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4994 const sp<IBinder>& token) {
4995 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4996 for (TouchedWindow& w : state.windows) {
4997 if (w.windowHandle->getToken() == token) {
4998 return std::make_pair(&state, &w);
4999 }
5000 }
5001 }
5002 return std::make_pair(nullptr, nullptr);
5003}
5004
arthurhungb89ccb02020-12-30 16:19:01 +08005005bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5006 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005007 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005008 if (DEBUG_FOCUS) {
5009 ALOGD("Trivial transfer to same window.");
5010 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005011 return true;
5012 }
5013
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005015 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016
Arthur Hungabbb9d82021-09-01 14:52:30 +00005017 // Find the target touch state and touched window by fromToken.
5018 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5019 if (state == nullptr || touchedWindow == nullptr) {
5020 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 return false;
5022 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005023
5024 const int32_t displayId = state->displayId;
5025 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5026 if (toWindowHandle == nullptr) {
5027 ALOGW("Cannot transfer focus because to window not found.");
5028 return false;
5029 }
5030
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005031 if (DEBUG_FOCUS) {
5032 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005033 touchedWindow->windowHandle->getName().c_str(),
5034 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 }
5036
Arthur Hungabbb9d82021-09-01 14:52:30 +00005037 // Erase old window.
5038 int32_t oldTargetFlags = touchedWindow->targetFlags;
5039 BitSet32 pointerIds = touchedWindow->pointerIds;
5040 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041
Arthur Hungabbb9d82021-09-01 14:52:30 +00005042 // Add new window.
5043 int32_t newTargetFlags = oldTargetFlags &
5044 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5045 InputTarget::FLAG_DISPATCH_AS_IS);
5046 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047
Arthur Hungabbb9d82021-09-01 14:52:30 +00005048 // Store the dragging window.
5049 if (isDragDrop) {
5050 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 }
5052
Arthur Hungabbb9d82021-09-01 14:52:30 +00005053 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005054 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5055 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005056 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005057 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 CancelationOptions
5059 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5060 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005062 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 }
5064
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005065 if (DEBUG_FOCUS) {
5066 logDispatchStateLocked();
5067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 } // release lock
5069
5070 // Wake up poll loop since it may need to make new input dispatching choices.
5071 mLooper->wake();
5072 return true;
5073}
5074
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005075// Binder call
5076bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5077 sp<IBinder> fromToken;
5078 { // acquire lock
5079 std::scoped_lock _l(mLock);
5080
Arthur Hungabbb9d82021-09-01 14:52:30 +00005081 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5082 [](const auto& pair) { return pair.second.windows.size() == 1; });
5083 if (it == mTouchStatesByDisplay.end()) {
5084 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5085 return false;
5086 }
5087 const int32_t displayId = it->first;
5088 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005089 if (toWindowHandle == nullptr) {
5090 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5091 return false;
5092 }
5093
Arthur Hungabbb9d82021-09-01 14:52:30 +00005094 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005095 const TouchedWindow& touchedWindow = state.windows[0];
5096 fromToken = touchedWindow.windowHandle->getToken();
5097 } // release lock
5098
5099 return transferTouchFocus(fromToken, destChannelToken);
5100}
5101
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005103 if (DEBUG_FOCUS) {
5104 ALOGD("Resetting and dropping all events (%s).", reason);
5105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106
5107 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5108 synthesizeCancelationEventsForAllConnectionsLocked(options);
5109
5110 resetKeyRepeatLocked();
5111 releasePendingEventLocked();
5112 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005115 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005116 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005118 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119}
5120
5121void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005122 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 dumpDispatchStateLocked(dump);
5124
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005125 std::istringstream stream(dump);
5126 std::string line;
5127
5128 while (std::getline(stream, line, '\n')) {
5129 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131}
5132
Prabir Pradhan99987712020-11-10 18:43:05 -08005133std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5134 std::string dump;
5135
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005136 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5137 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005138
5139 std::string windowName = "None";
5140 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005141 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005142 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5143 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5144 : "token has capture without window";
5145 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005146 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005147
5148 return dump;
5149}
5150
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005151void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005152 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5153 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5154 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005155 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156
Tiger Huang721e26f2018-07-24 22:26:19 +08005157 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5158 dump += StringPrintf(INDENT "FocusedApplications:\n");
5159 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5160 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005161 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005162 const std::chrono::duration timeout =
5163 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005164 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005165 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005166 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005169 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005171
Vishnu Nairc519ff72021-01-21 08:23:08 -08005172 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005173 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005175 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005176 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005177 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5178 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005179 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005180 state.displayId, toString(state.down), toString(state.split),
5181 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005182 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005183 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005184 for (size_t i = 0; i < state.windows.size(); i++) {
5185 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005186 dump += StringPrintf(INDENT4
5187 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5188 i, touchedWindow.windowHandle->getName().c_str(),
5189 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005190 }
5191 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005192 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194 }
5195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005196 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 }
5198
arthurhung6d4bed92021-03-17 11:59:33 +08005199 if (mDragState) {
5200 dump += StringPrintf(INDENT "DragState:\n");
5201 mDragState->dump(dump, INDENT2);
5202 }
5203
Arthur Hungb92218b2018-08-14 12:00:21 +08005204 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005205 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5206 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5207 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5208 const auto& displayInfo = it->second;
5209 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5210 displayInfo.logicalHeight);
5211 displayInfo.transform.dump(dump, "transform", INDENT4);
5212 } else {
5213 dump += INDENT2 "No DisplayInfo found!\n";
5214 }
5215
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005216 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005217 dump += INDENT2 "Windows:\n";
5218 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005219 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5220 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005222 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005223 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005224 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005225 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005226 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005227 "applicationInfo.name=%s, "
5228 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005229 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005230 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005231 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005232 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005233 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005234 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005235 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005236 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005237 windowInfo->frameLeft, windowInfo->frameTop,
5238 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005239 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005240 windowInfo->applicationInfo.name.c_str(),
5241 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005242 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005243 dump += StringPrintf(", inputFeatures=%s",
5244 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005245 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005246 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005247 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005248 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005249 millis(windowInfo->dispatchingTimeout),
5250 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005251 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005252 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005253 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005254 }
5255 } else {
5256 dump += INDENT2 "Windows: <none>\n";
5257 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 }
5259 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005260 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 }
5262
Michael Wright3dd60e22019-03-27 22:06:44 +00005263 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005264 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005265 const std::vector<Monitor>& monitors = it.second;
5266 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5267 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 }
5269 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005270 const std::vector<Monitor>& monitors = it.second;
5271 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5272 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005275 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277
5278 nsecs_t currentTime = now();
5279
5280 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005281 if (!mRecentQueue.empty()) {
5282 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005283 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005284 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005285 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005286 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 }
5288 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291
5292 // Dump event currently being dispatched.
5293 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005294 dump += INDENT "PendingEvent:\n";
5295 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005296 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005297 dump += StringPrintf(", age=%" PRId64 "ms\n",
5298 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005300 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 }
5302
5303 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005304 if (!mInboundQueue.empty()) {
5305 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005306 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005307 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005308 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005309 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005312 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 }
5314
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005315 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005316 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005317 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5318 const KeyReplacement& replacement = pair.first;
5319 int32_t newKeyCode = pair.second;
5320 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005321 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005322 }
5323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005324 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005325 }
5326
Prabir Pradhancef936d2021-07-21 16:17:52 +00005327 if (!mCommandQueue.empty()) {
5328 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5329 } else {
5330 dump += INDENT "CommandQueue: <empty>\n";
5331 }
5332
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005333 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005335 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005336 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005337 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005338 connection->inputChannel->getFd().get(),
5339 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005340 connection->getWindowName().c_str(),
5341 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005342 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005344 if (!connection->outboundQueue.empty()) {
5345 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5346 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005347 dump += dumpQueue(connection->outboundQueue, currentTime);
5348
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005350 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 }
5352
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005353 if (!connection->waitQueue.empty()) {
5354 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5355 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005356 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005358 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 }
5360 }
5361 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005362 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 }
5364
5365 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005366 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5367 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005369 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 }
5371
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005372 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005373 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5374 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5375 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005376 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005377 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378}
5379
Michael Wright3dd60e22019-03-27 22:06:44 +00005380void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5381 const size_t numMonitors = monitors.size();
5382 for (size_t i = 0; i < numMonitors; i++) {
5383 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005384 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5386 dump += "\n";
5387 }
5388}
5389
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005390class LooperEventCallback : public LooperCallback {
5391public:
5392 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5393 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5394
5395private:
5396 std::function<int(int events)> mCallback;
5397};
5398
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005399Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005400 if (DEBUG_CHANNEL_CREATION) {
5401 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005404 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005405 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005406 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005407
5408 if (result) {
5409 return base::Error(result) << "Failed to open input channel pair with name " << name;
5410 }
5411
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005413 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005414 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005415 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005416 sp<Connection> connection =
5417 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005419 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5420 ALOGE("Created a new connection, but the token %p is already known", token.get());
5421 }
5422 mConnectionsByToken.emplace(token, connection);
5423
5424 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5425 this, std::placeholders::_1, token);
5426
5427 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 } // release lock
5429
5430 // Wake the looper because some connections have changed.
5431 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005432 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433}
5434
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005435Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5436 bool isGestureMonitor,
5437 const std::string& name,
5438 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005439 std::shared_ptr<InputChannel> serverChannel;
5440 std::unique_ptr<InputChannel> clientChannel;
5441 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5442 if (result) {
5443 return base::Error(result) << "Failed to open input channel pair with name " << name;
5444 }
5445
Michael Wright3dd60e22019-03-27 22:06:44 +00005446 { // acquire lock
5447 std::scoped_lock _l(mLock);
5448
5449 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005450 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5451 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005452 }
5453
Garfield Tan15601662020-09-22 15:32:38 -07005454 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005455 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005456 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005457
5458 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5459 ALOGE("Created a new connection, but the token %p is already known", token.get());
5460 }
5461 mConnectionsByToken.emplace(token, connection);
5462 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5463 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005464
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005465 auto& monitorsByDisplay =
5466 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005467 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005468
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005469 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005470 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5471 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005472 }
Garfield Tan15601662020-09-22 15:32:38 -07005473
Michael Wright3dd60e22019-03-27 22:06:44 +00005474 // Wake the looper because some connections have changed.
5475 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005476 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005477}
5478
Garfield Tan15601662020-09-22 15:32:38 -07005479status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005481 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482
Garfield Tan15601662020-09-22 15:32:38 -07005483 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 if (status) {
5485 return status;
5486 }
5487 } // release lock
5488
5489 // Wake the poll loop because removing the connection may have changed the current
5490 // synchronization state.
5491 mLooper->wake();
5492 return OK;
5493}
5494
Garfield Tan15601662020-09-22 15:32:38 -07005495status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5496 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005497 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005498 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005499 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500 return BAD_VALUE;
5501 }
5502
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005503 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005504
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005506 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 }
5508
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005509 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510
5511 nsecs_t currentTime = now();
5512 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5513
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005514 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 return OK;
5516}
5517
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005518void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5519 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5520 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005521}
5522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005523void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005524 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005525 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005526 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005527 std::vector<Monitor>& monitors = it->second;
5528 const size_t numMonitors = monitors.size();
5529 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005530 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005531 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5532 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005533 monitors.erase(monitors.begin() + i);
5534 break;
5535 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005536 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005537 if (monitors.empty()) {
5538 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005539 } else {
5540 ++it;
5541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 }
5543}
5544
Michael Wright3dd60e22019-03-27 22:06:44 +00005545status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5546 { // acquire lock
5547 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005548
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005549 TouchState* statePtr = nullptr;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005550 std::shared_ptr<InputChannel> requestingChannel;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005551 int32_t displayId;
5552 int32_t deviceId;
5553 const std::optional<int32_t> foundGestureMonitorDisplayId =
5554 findGestureMonitorDisplayByTokenLocked(token);
5555
5556 // TODO: Optimize this function for pilfering from windows when removing gesture monitors.
5557 if (foundGestureMonitorDisplayId) {
5558 // A gesture monitor has requested to pilfer pointers.
5559 displayId = *foundGestureMonitorDisplayId;
5560 auto stateIt = mTouchStatesByDisplay.find(displayId);
5561 if (stateIt == mTouchStatesByDisplay.end()) {
5562 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5563 return BAD_VALUE;
5564 }
5565 statePtr = &stateIt->second;
5566
5567 for (const auto& monitor : statePtr->gestureMonitors) {
5568 if (monitor.inputChannel->getConnectionToken() == token) {
5569 requestingChannel = monitor.inputChannel;
5570 deviceId = statePtr->deviceId;
5571 }
5572 }
5573 } else {
5574 // Check if a window has requested to pilfer pointers.
5575 for (auto& [curDisplayId, state] : mTouchStatesByDisplay) {
5576 const sp<WindowInfoHandle>& windowHandle = state.getWindow(token);
5577 if (windowHandle != nullptr) {
5578 displayId = curDisplayId;
5579 requestingChannel = getInputChannelLocked(token);
5580 deviceId = state.deviceId;
5581 statePtr = &state;
5582 break;
5583 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005584 }
5585 }
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005586
5587 if (requestingChannel == nullptr) {
5588 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5589 return BAD_VALUE;
5590 }
5591 TouchState& state = *statePtr;
5592 if (!state.down) {
5593 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005594 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005595 return BAD_VALUE;
5596 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005597
5598 // Send cancel events to all the input channels we're stealing from.
5599 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005600 "input channel stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005601 options.deviceId = deviceId;
5602 options.displayId = displayId;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005603 std::string canceledWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005604 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005605 std::shared_ptr<InputChannel> channel =
5606 getInputChannelLocked(window.windowHandle->getToken());
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005607 if (channel != nullptr && channel->getConnectionToken() != token) {
Michael Wright3a240c42019-12-10 20:53:41 +00005608 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005609 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5610 canceledWindows += channel->getName();
Michael Wright3a240c42019-12-10 20:53:41 +00005611 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005612 }
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005613 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5614 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005615 canceledWindows.c_str());
5616
Michael Wright3dd60e22019-03-27 22:06:44 +00005617 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hungfbfa5722021-11-16 02:45:54 +00005618 state.split = false;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005619 state.filterWindowsExcept(token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005620 }
5621 return OK;
5622}
5623
Prabir Pradhan99987712020-11-10 18:43:05 -08005624void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5625 { // acquire lock
5626 std::scoped_lock _l(mLock);
5627 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005628 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005629 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5630 windowHandle != nullptr ? windowHandle->getName().c_str()
5631 : "token without window");
5632 }
5633
Vishnu Nairc519ff72021-01-21 08:23:08 -08005634 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005635 if (focusedToken != windowToken) {
5636 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5637 enabled ? "enable" : "disable");
5638 return;
5639 }
5640
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005641 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005642 ALOGW("Ignoring request to %s Pointer Capture: "
5643 "window has %s requested pointer capture.",
5644 enabled ? "enable" : "disable", enabled ? "already" : "not");
5645 return;
5646 }
5647
Prabir Pradhan99987712020-11-10 18:43:05 -08005648 setPointerCaptureLocked(enabled);
5649 } // release lock
5650
5651 // Wake the thread to process command entries.
5652 mLooper->wake();
5653}
5654
Michael Wright3dd60e22019-03-27 22:06:44 +00005655std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5656 const sp<IBinder>& token) {
5657 for (const auto& it : mGestureMonitorsByDisplay) {
5658 const std::vector<Monitor>& monitors = it.second;
5659 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005660 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005661 return it.first;
5662 }
5663 }
5664 }
5665 return std::nullopt;
5666}
5667
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005668std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5669 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5670 if (gesturePid.has_value()) {
5671 return gesturePid;
5672 }
5673 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5674}
5675
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005676sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005677 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005678 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005679 }
5680
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005681 for (const auto& [token, connection] : mConnectionsByToken) {
5682 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005683 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685 }
Robert Carr4e670e52018-08-15 13:26:12 -07005686
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005687 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688}
5689
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005690std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5691 sp<Connection> connection = getConnectionLocked(connectionToken);
5692 if (connection == nullptr) {
5693 return "<nullptr>";
5694 }
5695 return connection->getInputChannelName();
5696}
5697
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005698void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005699 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005700 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005701}
5702
Prabir Pradhancef936d2021-07-21 16:17:52 +00005703void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5704 const sp<Connection>& connection, uint32_t seq,
5705 bool handled, nsecs_t consumeTime) {
5706 // Handle post-event policy actions.
5707 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5708 if (dispatchEntryIt == connection->waitQueue.end()) {
5709 return;
5710 }
5711 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5712 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5713 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5714 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5715 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5716 }
5717 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5718 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5719 connection->inputChannel->getConnectionToken(),
5720 dispatchEntry->deliveryTime, consumeTime, finishTime);
5721 }
5722
5723 bool restartEvent;
5724 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5725 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5726 restartEvent =
5727 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5728 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5729 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5730 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5731 handled);
5732 } else {
5733 restartEvent = false;
5734 }
5735
5736 // Dequeue the event and start the next cycle.
5737 // Because the lock might have been released, it is possible that the
5738 // contents of the wait queue to have been drained, so we need to double-check
5739 // a few things.
5740 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5741 if (dispatchEntryIt != connection->waitQueue.end()) {
5742 dispatchEntry = *dispatchEntryIt;
5743 connection->waitQueue.erase(dispatchEntryIt);
5744 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5745 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5746 if (!connection->responsive) {
5747 connection->responsive = isConnectionResponsive(*connection);
5748 if (connection->responsive) {
5749 // The connection was unresponsive, and now it's responsive.
5750 processConnectionResponsiveLocked(*connection);
5751 }
5752 }
5753 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005754 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005755 connection->outboundQueue.push_front(dispatchEntry);
5756 traceOutboundQueueLength(*connection);
5757 } else {
5758 releaseDispatchEntry(dispatchEntry);
5759 }
5760 }
5761
5762 // Start the next dispatch cycle for this connection.
5763 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764}
5765
Prabir Pradhancef936d2021-07-21 16:17:52 +00005766void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5767 const sp<IBinder>& newToken) {
5768 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5769 scoped_unlock unlock(mLock);
5770 mPolicy->notifyFocusChanged(oldToken, newToken);
5771 };
5772 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773}
5774
Prabir Pradhancef936d2021-07-21 16:17:52 +00005775void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5776 auto command = [this, token, x, y]() REQUIRES(mLock) {
5777 scoped_unlock unlock(mLock);
5778 mPolicy->notifyDropWindow(token, x, y);
5779 };
5780 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005781}
5782
Prabir Pradhancef936d2021-07-21 16:17:52 +00005783void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5784 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5785 scoped_unlock unlock(mLock);
5786 mPolicy->notifyUntrustedTouch(obscuringPackage);
5787 };
5788 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005789}
5790
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005791void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5792 if (connection == nullptr) {
5793 LOG_ALWAYS_FATAL("Caller must check for nullness");
5794 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005795 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5796 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005797 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005798 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005799 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005800 return;
5801 }
5802 /**
5803 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5804 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5805 * has changed. This could cause newer entries to time out before the already dispatched
5806 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5807 * processes the events linearly. So providing information about the oldest entry seems to be
5808 * most useful.
5809 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005810 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005811 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5812 std::string reason =
5813 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005814 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005815 ns2ms(currentWait),
5816 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005817 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005818 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005819
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005820 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5821
5822 // Stop waking up for events on this connection, it is already unresponsive
5823 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005824}
5825
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005826void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5827 std::string reason =
5828 StringPrintf("%s does not have a focused window", application->getName().c_str());
5829 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005830
Prabir Pradhancef936d2021-07-21 16:17:52 +00005831 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5832 scoped_unlock unlock(mLock);
5833 mPolicy->notifyNoFocusedWindowAnr(application);
5834 };
5835 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005836}
5837
chaviw98318de2021-05-19 16:45:23 -05005838void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005839 const std::string& reason) {
5840 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5841 updateLastAnrStateLocked(windowLabel, reason);
5842}
5843
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005844void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5845 const std::string& reason) {
5846 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005847 updateLastAnrStateLocked(windowLabel, reason);
5848}
5849
5850void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5851 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005853 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854 struct tm tm;
5855 localtime_r(&t, &tm);
5856 char timestr[64];
5857 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005858 mLastAnrState.clear();
5859 mLastAnrState += INDENT "ANR:\n";
5860 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005861 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5862 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005863 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864}
5865
Prabir Pradhancef936d2021-07-21 16:17:52 +00005866void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5867 KeyEntry& entry) {
5868 const KeyEvent event = createKeyEvent(entry);
5869 nsecs_t delay = 0;
5870 { // release lock
5871 scoped_unlock unlock(mLock);
5872 android::base::Timer t;
5873 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5874 entry.policyFlags);
5875 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5876 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5877 std::to_string(t.duration().count()).c_str());
5878 }
5879 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880
5881 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005882 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005883 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005884 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005885 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5887 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889}
5890
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005891void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005892 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5893 scoped_unlock unlock(mLock);
5894 mPolicy->notifyMonitorUnresponsive(pid, reason);
5895 };
5896 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005897}
5898
Prabir Pradhancef936d2021-07-21 16:17:52 +00005899void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005900 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005901 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5902 scoped_unlock unlock(mLock);
5903 mPolicy->notifyWindowUnresponsive(token, reason);
5904 };
5905 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906}
5907
5908void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005909 auto command = [this, pid]() REQUIRES(mLock) {
5910 scoped_unlock unlock(mLock);
5911 mPolicy->notifyMonitorResponsive(pid);
5912 };
5913 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005914}
5915
Prabir Pradhancef936d2021-07-21 16:17:52 +00005916void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5917 auto command = [this, connectionToken]() REQUIRES(mLock) {
5918 scoped_unlock unlock(mLock);
5919 mPolicy->notifyWindowResponsive(connectionToken);
5920 };
5921 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005922}
5923
5924/**
5925 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5926 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5927 * command entry to the command queue.
5928 */
5929void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5930 std::string reason) {
5931 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5932 if (connection.monitor) {
5933 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5934 reason.c_str());
5935 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5936 if (!pid.has_value()) {
5937 ALOGE("Could not find unresponsive monitor for connection %s",
5938 connection.inputChannel->getName().c_str());
5939 return;
5940 }
5941 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5942 return;
5943 }
5944 // If not a monitor, must be a window
5945 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5946 reason.c_str());
5947 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5948}
5949
5950/**
5951 * Tell the policy that a connection has become responsive so that it can stop ANR.
5952 */
5953void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5954 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5955 if (connection.monitor) {
5956 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5957 if (!pid.has_value()) {
5958 ALOGE("Could not find responsive monitor for connection %s",
5959 connection.inputChannel->getName().c_str());
5960 return;
5961 }
5962 sendMonitorResponsiveCommandLocked(pid.value());
5963 return;
5964 }
5965 // If not a monitor, must be a window
5966 sendWindowResponsiveCommandLocked(connectionToken);
5967}
5968
Prabir Pradhancef936d2021-07-21 16:17:52 +00005969bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005970 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 KeyEntry& keyEntry, bool handled) {
5972 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005973 if (!handled) {
5974 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005976 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005977 return false;
5978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005980 // Get the fallback key state.
5981 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005982 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005984 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985 connection->inputState.removeFallbackKey(originalKeyCode);
5986 }
5987
5988 if (handled || !dispatchEntry->hasForegroundTarget()) {
5989 // If the application handles the original key for which we previously
5990 // generated a fallback or if the window is not a foreground window,
5991 // then cancel the associated fallback key, if any.
5992 if (fallbackKeyCode != -1) {
5993 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005994 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5995 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5996 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5997 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5998 keyEntry.policyFlags);
5999 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006000 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006001 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002
6003 mLock.unlock();
6004
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006005 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006006 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007
6008 mLock.lock();
6009
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 // Cancel the fallback key.
6011 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006013 "application handled the original non-fallback key "
6014 "or is no longer a foreground target, "
6015 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 options.keyCode = fallbackKeyCode;
6017 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006019 connection->inputState.removeFallbackKey(originalKeyCode);
6020 }
6021 } else {
6022 // If the application did not handle a non-fallback key, first check
6023 // that we are in a good state to perform unhandled key event processing
6024 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006025 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006026 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006027 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6028 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6029 "since this is not an initial down. "
6030 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6031 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6032 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006033 return false;
6034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006036 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006037 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6038 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6039 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6040 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6041 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006042 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043
6044 mLock.unlock();
6045
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006046 bool fallback =
6047 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006048 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006049
6050 mLock.lock();
6051
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006052 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 connection->inputState.removeFallbackKey(originalKeyCode);
6054 return false;
6055 }
6056
6057 // Latch the fallback keycode for this key on an initial down.
6058 // The fallback keycode cannot change at any other point in the lifecycle.
6059 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061 fallbackKeyCode = event.getKeyCode();
6062 } else {
6063 fallbackKeyCode = AKEYCODE_UNKNOWN;
6064 }
6065 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6066 }
6067
6068 ALOG_ASSERT(fallbackKeyCode != -1);
6069
6070 // Cancel the fallback key if the policy decides not to send it anymore.
6071 // We will continue to dispatch the key to the policy but we will no
6072 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006073 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6074 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006075 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6076 if (fallback) {
6077 ALOGD("Unhandled key event: Policy requested to send key %d"
6078 "as a fallback for %d, but on the DOWN it had requested "
6079 "to send %d instead. Fallback canceled.",
6080 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6081 } else {
6082 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6083 "but on the DOWN it had requested to send %d. "
6084 "Fallback canceled.",
6085 originalKeyCode, fallbackKeyCode);
6086 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006087 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088
6089 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6090 "canceling fallback, policy no longer desires it");
6091 options.keyCode = fallbackKeyCode;
6092 synthesizeCancelationEventsForConnectionLocked(connection, options);
6093
6094 fallback = false;
6095 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006096 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006097 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006098 }
6099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006101 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6102 {
6103 std::string msg;
6104 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6105 connection->inputState.getFallbackKeys();
6106 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6107 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6108 }
6109 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6110 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006113
6114 if (fallback) {
6115 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 keyEntry.eventTime = event.getEventTime();
6117 keyEntry.deviceId = event.getDeviceId();
6118 keyEntry.source = event.getSource();
6119 keyEntry.displayId = event.getDisplayId();
6120 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6121 keyEntry.keyCode = fallbackKeyCode;
6122 keyEntry.scanCode = event.getScanCode();
6123 keyEntry.metaState = event.getMetaState();
6124 keyEntry.repeatCount = event.getRepeatCount();
6125 keyEntry.downTime = event.getDownTime();
6126 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006127
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006128 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6129 ALOGD("Unhandled key event: Dispatching fallback key. "
6130 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6131 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6132 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133 return true; // restart the event
6134 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006135 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6136 ALOGD("Unhandled key event: No fallback key.");
6137 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006138
6139 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006140 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 }
6142 }
6143 return false;
6144}
6145
Prabir Pradhancef936d2021-07-21 16:17:52 +00006146bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006147 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006148 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149 return false;
6150}
6151
Michael Wrightd02c5b62014-02-10 15:10:22 -08006152void InputDispatcher::traceInboundQueueLengthLocked() {
6153 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006154 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006155 }
6156}
6157
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006158void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159 if (ATRACE_ENABLED()) {
6160 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006161 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6162 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163 }
6164}
6165
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006166void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 if (ATRACE_ENABLED()) {
6168 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006169 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6170 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171 }
6172}
6173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006174void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006175 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006177 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178 dumpDispatchStateLocked(dump);
6179
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006180 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006181 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006182 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183 }
6184}
6185
6186void InputDispatcher::monitor() {
6187 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006188 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006190 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191}
6192
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006193/**
6194 * Wake up the dispatcher and wait until it processes all events and commands.
6195 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6196 * this method can be safely called from any thread, as long as you've ensured that
6197 * the work you are interested in completing has already been queued.
6198 */
6199bool InputDispatcher::waitForIdle() {
6200 /**
6201 * Timeout should represent the longest possible time that a device might spend processing
6202 * events and commands.
6203 */
6204 constexpr std::chrono::duration TIMEOUT = 100ms;
6205 std::unique_lock lock(mLock);
6206 mLooper->wake();
6207 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6208 return result == std::cv_status::no_timeout;
6209}
6210
Vishnu Naire798b472020-07-23 13:52:21 -07006211/**
6212 * Sets focus to the window identified by the token. This must be called
6213 * after updating any input window handles.
6214 *
6215 * Params:
6216 * request.token - input channel token used to identify the window that should gain focus.
6217 * request.focusedToken - the token that the caller expects currently to be focused. If the
6218 * specified token does not match the currently focused window, this request will be dropped.
6219 * If the specified focused token matches the currently focused window, the call will succeed.
6220 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6221 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6222 * when requesting the focus change. This determines which request gets
6223 * precedence if there is a focus change request from another source such as pointer down.
6224 */
Vishnu Nair958da932020-08-21 17:12:37 -07006225void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6226 { // acquire lock
6227 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006228 std::optional<FocusResolver::FocusChanges> changes =
6229 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6230 if (changes) {
6231 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006232 }
6233 } // release lock
6234 // Wake up poll loop since it may need to make new input dispatching choices.
6235 mLooper->wake();
6236}
6237
Vishnu Nairc519ff72021-01-21 08:23:08 -08006238void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6239 if (changes.oldFocus) {
6240 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006241 if (focusedInputChannel) {
6242 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6243 "focus left window");
6244 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006245 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006246 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006247 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006248 if (changes.newFocus) {
6249 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006250 }
6251
Prabir Pradhan99987712020-11-10 18:43:05 -08006252 // If a window has pointer capture, then it must have focus. We need to ensure that this
6253 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6254 // If the window loses focus before it loses pointer capture, then the window can be in a state
6255 // where it has pointer capture but not focus, violating the contract. Therefore we must
6256 // dispatch the pointer capture event before the focus event. Since focus events are added to
6257 // the front of the queue (above), we add the pointer capture event to the front of the queue
6258 // after the focus events are added. This ensures the pointer capture event ends up at the
6259 // front.
6260 disablePointerCaptureForcedLocked();
6261
Vishnu Nairc519ff72021-01-21 08:23:08 -08006262 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006263 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006264 }
6265}
Vishnu Nair958da932020-08-21 17:12:37 -07006266
Prabir Pradhan99987712020-11-10 18:43:05 -08006267void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006268 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006269 return;
6270 }
6271
6272 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6273
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006274 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006275 setPointerCaptureLocked(false);
6276 }
6277
6278 if (!mWindowTokenWithPointerCapture) {
6279 // No need to send capture changes because no window has capture.
6280 return;
6281 }
6282
6283 if (mPendingEvent != nullptr) {
6284 // Move the pending event to the front of the queue. This will give the chance
6285 // for the pending event to be dropped if it is a captured event.
6286 mInboundQueue.push_front(mPendingEvent);
6287 mPendingEvent = nullptr;
6288 }
6289
6290 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006291 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006292 mInboundQueue.push_front(std::move(entry));
6293}
6294
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006295void InputDispatcher::setPointerCaptureLocked(bool enable) {
6296 mCurrentPointerCaptureRequest.enable = enable;
6297 mCurrentPointerCaptureRequest.seq++;
6298 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006299 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006300 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006301 };
6302 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006303}
6304
Vishnu Nair599f1412021-06-21 10:39:58 -07006305void InputDispatcher::displayRemoved(int32_t displayId) {
6306 { // acquire lock
6307 std::scoped_lock _l(mLock);
6308 // Set an empty list to remove all handles from the specific display.
6309 setInputWindowsLocked(/* window handles */ {}, displayId);
6310 setFocusedApplicationLocked(displayId, nullptr);
6311 // Call focus resolver to clean up stale requests. This must be called after input windows
6312 // have been removed for the removed display.
6313 mFocusResolver.displayRemoved(displayId);
6314 } // release lock
6315
6316 // Wake up poll loop since it may need to make new input dispatching choices.
6317 mLooper->wake();
6318}
6319
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006320void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6321 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006322 // The listener sends the windows as a flattened array. Separate the windows by display for
6323 // more convenient parsing.
6324 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006325 for (const auto& info : windowInfos) {
6326 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6327 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6328 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006329
6330 { // acquire lock
6331 std::scoped_lock _l(mLock);
6332 mDisplayInfos.clear();
6333 for (const auto& displayInfo : displayInfos) {
6334 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6335 }
6336
6337 for (const auto& [displayId, handles] : handlesPerDisplay) {
6338 setInputWindowsLocked(handles, displayId);
6339 }
6340 }
6341 // Wake up poll loop since it may need to make new input dispatching choices.
6342 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006343}
6344
Vishnu Nair062a8672021-09-03 16:07:44 -07006345bool InputDispatcher::shouldDropInput(
6346 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6347 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6348 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6349 isWindowObscuredLocked(windowHandle))) {
6350 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6351 "%" PRId32 ".",
6352 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6353 windowHandle->getInfo()->inputFeatures.string().c_str(),
6354 windowHandle->getInfo()->displayId);
6355 return true;
6356 }
6357 return false;
6358}
6359
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006360void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6361 const std::vector<gui::WindowInfo>& windowInfos,
6362 const std::vector<DisplayInfo>& displayInfos) {
6363 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6364}
6365
Arthur Hungdfd528e2021-12-08 13:23:04 +00006366void InputDispatcher::cancelCurrentTouch() {
6367 {
6368 std::scoped_lock _l(mLock);
6369 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6370 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6371 "cancel current touch");
6372 synthesizeCancelationEventsForAllConnectionsLocked(options);
6373
6374 mTouchStatesByDisplay.clear();
6375 mLastHoverWindowHandle.clear();
6376 }
6377 // Wake up poll loop since there might be work to do.
6378 mLooper->wake();
6379}
6380
Garfield Tane84e6f92019-08-29 17:28:41 -07006381} // namespace android::inputdispatcher