blob: d1982fc53c1cd9aaa483b484c7c41a16112fd39b [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.
Vadim Tryshev78548252022-01-27 19:32:46 +0000123const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL // 10sec
124 * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126// 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 +0000127constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
128
129// Log a warning when an interception call takes longer than this to process.
130constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700132// Additional key latency in case a connection is still processing some motion events.
133// This will help with the case when a user touched a button that opens a new window,
134// and gives us the chance to dispatch the key to this new window.
135constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000138constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
139
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000140// Event log tags. See EventLogTags.logtags for reference
141constexpr int LOGTAG_INPUT_INTERACTION = 62000;
142constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000143constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000144
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000145inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146 return systemTime(SYSTEM_TIME_MONOTONIC);
147}
148
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000149inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 return value ? "true" : "false";
151}
152
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000153inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000154 if (binder == nullptr) {
155 return "<null>";
156 }
157 return StringPrintf("%p", binder.get());
158}
159
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000160inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
162 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163}
164
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000165bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AKEY_EVENT_ACTION_DOWN:
168 case AKEY_EVENT_ACTION_UP:
169 return true;
170 default:
171 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 }
173}
174
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000175bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 ALOGE("Key event has invalid action code 0x%x", action);
178 return false;
179 }
180 return true;
181}
182
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000183bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 case AMOTION_EVENT_ACTION_DOWN:
186 case AMOTION_EVENT_ACTION_UP:
187 case AMOTION_EVENT_ACTION_CANCEL:
188 case AMOTION_EVENT_ACTION_MOVE:
189 case AMOTION_EVENT_ACTION_OUTSIDE:
190 case AMOTION_EVENT_ACTION_HOVER_ENTER:
191 case AMOTION_EVENT_ACTION_HOVER_MOVE:
192 case AMOTION_EVENT_ACTION_HOVER_EXIT:
193 case AMOTION_EVENT_ACTION_SCROLL:
194 return true;
195 case AMOTION_EVENT_ACTION_POINTER_DOWN:
196 case AMOTION_EVENT_ACTION_POINTER_UP: {
197 int32_t index = getMotionEventActionPointerIndex(action);
198 return index >= 0 && index < pointerCount;
199 }
200 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
201 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
202 return actionButton != 0;
203 default:
204 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
206}
207
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000208int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500209 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
210}
211
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000212bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
213 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700214 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 ALOGE("Motion event has invalid action code 0x%x", action);
216 return false;
217 }
218 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800219 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700220 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return false;
222 }
223 BitSet32 pointerIdBits;
224 for (size_t i = 0; i < pointerCount; i++) {
225 int32_t id = pointerProperties[i].id;
226 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700227 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
228 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 return false;
230 }
231 if (pointerIdBits.hasBit(id)) {
232 ALOGE("Motion event has duplicate pointer id %d", id);
233 return false;
234 }
235 pointerIdBits.markBit(id);
236 }
237 return true;
238}
239
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000240std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000242 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243 }
244
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000245 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 bool first = true;
247 Region::const_iterator cur = region.begin();
248 Region::const_iterator const tail = region.end();
249 while (cur != tail) {
250 if (first) {
251 first = false;
252 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800253 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800255 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 cur++;
257 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259}
260
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000261std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500262 constexpr size_t maxEntries = 50; // max events to print
263 constexpr size_t skipBegin = maxEntries / 2;
264 const size_t skipEnd = queue.size() - maxEntries / 2;
265 // skip from maxEntries / 2 ... size() - maxEntries/2
266 // only print from 0 .. skipBegin and then from skipEnd .. size()
267
268 std::string dump;
269 for (size_t i = 0; i < queue.size(); i++) {
270 const DispatchEntry& entry = *queue[i];
271 if (i >= skipBegin && i < skipEnd) {
272 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
273 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
274 continue;
275 }
276 dump.append(INDENT4);
277 dump += entry.eventEntry->getDescription();
278 dump += StringPrintf(", seq=%" PRIu32
279 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
280 entry.seq, entry.targetFlags, entry.resolvedAction,
281 ns2ms(currentTime - entry.eventEntry->eventTime));
282 if (entry.deliveryTime != 0) {
283 // This entry was delivered, so add information on how long we've been waiting
284 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
285 }
286 dump.append("\n");
287 }
288 return dump;
289}
290
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700291/**
292 * Find the entry in std::unordered_map by key, and return it.
293 * If the entry is not found, return a default constructed entry.
294 *
295 * Useful when the entries are vectors, since an empty vector will be returned
296 * if the entry is not found.
297 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
298 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700299template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000300V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700301 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700302 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800303}
304
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000305bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000317bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321 return first->applicationInfo.token != nullptr &&
322 first->applicationInfo.token == second->applicationInfo.token;
323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800326 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
327}
328
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000329std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
330 std::shared_ptr<EventEntry> eventEntry,
331 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700332 if (inputTarget.useDefaultPointerTransform()) {
333 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700334 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700335 inputTarget.displayTransform,
336 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000337 }
338
339 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
340 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700342 std::vector<PointerCoords> pointerCoords;
343 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344
345 // Use the first pointer information to normalize all other pointers. This could be any pointer
346 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 // uses the transform for the normalized pointer.
348 const ui::Transform& firstPointerTransform =
349 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
350 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000351
352 // Iterate through all pointers in the event to normalize against the first.
353 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
354 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
355 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700356 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700359 // First, apply the current pointer's transform to update the coordinates into
360 // window space.
361 pointerCoords[pointerIndex].transform(currTransform);
362 // Next, apply the inverse transform of the normalized coordinates so the
363 // current coordinates are transformed into the normalized coordinate space.
364 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365 }
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::unique_ptr<MotionEntry> combinedMotionEntry =
368 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
369 motionEntry.deviceId, motionEntry.source,
370 motionEntry.displayId, motionEntry.policyFlags,
371 motionEntry.action, motionEntry.actionButton,
372 motionEntry.flags, motionEntry.metaState,
373 motionEntry.buttonState, motionEntry.classification,
374 motionEntry.edgeFlags, motionEntry.xPrecision,
375 motionEntry.yPrecision, motionEntry.xCursorPosition,
376 motionEntry.yCursorPosition, motionEntry.downTime,
377 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000378 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379
380 if (motionEntry.injectionState) {
381 combinedMotionEntry->injectionState = motionEntry.injectionState;
382 combinedMotionEntry->injectionState->refCount += 1;
383 }
384
385 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700386 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700387 firstPointerTransform, inputTarget.displayTransform,
388 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 return dispatchEntry;
390}
391
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000392status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
393 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700394 std::unique_ptr<InputChannel> uniqueServerChannel;
395 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
396
397 serverChannel = std::move(uniqueServerChannel);
398 return result;
399}
400
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500401template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000402bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500403 if (lhs == nullptr && rhs == nullptr) {
404 return true;
405 }
406 if (lhs == nullptr || rhs == nullptr) {
407 return false;
408 }
409 return *lhs == *rhs;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000413 KeyEvent event;
414 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
415 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
416 entry.repeatCount, entry.downTime, entry.eventTime);
417 return event;
418}
419
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000420std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000421 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
422 const sp<IBinder>& token) {
423 for (const auto& it : monitorsByDisplay) {
424 const std::vector<Monitor>& monitors = it.second;
425 for (const Monitor& monitor : monitors) {
426 if (monitor.inputChannel->getConnectionToken() == token) {
427 return monitor.pid;
428 }
429 }
430 }
431 return std::nullopt;
432}
433
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000434bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000435 // Do not keep track of gesture monitors. They receive every event and would disproportionately
436 // affect the statistics.
437 if (connection.monitor) {
438 return false;
439 }
440 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
441 if (!connection.responsive) {
442 return false;
443 }
444 return true;
445}
446
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000447bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000448 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
449 const int32_t& inputEventId = eventEntry.id;
450 if (inputEventId != dispatchEntry.resolvedEventId) {
451 // Event was transmuted
452 return false;
453 }
454 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
455 return false;
456 }
457 // Only track latency for events that originated from hardware
458 if (eventEntry.isSynthesized()) {
459 return false;
460 }
461 const EventEntry::Type& inputEventEntryType = eventEntry.type;
462 if (inputEventEntryType == EventEntry::Type::KEY) {
463 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
464 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
465 return false;
466 }
467 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
468 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
469 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
470 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
471 return false;
472 }
473 } else {
474 // Not a key or a motion
475 return false;
476 }
477 if (!shouldReportMetricsForConnection(connection)) {
478 return false;
479 }
480 return true;
481}
482
Prabir Pradhancef936d2021-07-21 16:17:52 +0000483/**
484 * Connection is responsive if it has no events in the waitQueue that are older than the
485 * current time.
486 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000487bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000488 const nsecs_t currentTime = now();
489 for (const DispatchEntry* entry : connection.waitQueue) {
490 if (entry->timeoutTime < currentTime) {
491 return false;
492 }
493 }
494 return true;
495}
496
Antonio Kantekf16f2832021-09-28 04:39:20 +0000497// Returns true if the event type passed as argument represents a user activity.
498bool isUserActivityEvent(const EventEntry& eventEntry) {
499 switch (eventEntry.type) {
500 case EventEntry::Type::FOCUS:
501 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
502 case EventEntry::Type::DRAG:
503 case EventEntry::Type::TOUCH_MODE_CHANGED:
504 case EventEntry::Type::SENSOR:
505 case EventEntry::Type::CONFIGURATION_CHANGED:
506 return false;
507 case EventEntry::Type::DEVICE_RESET:
508 case EventEntry::Type::KEY:
509 case EventEntry::Type::MOTION:
510 return true;
511 }
512}
513
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800514// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700515bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
516 bool isStylus) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800517 if (windowInfo.displayId != displayId || !windowInfo.visible) {
518 return false;
519 }
520 const auto flags = windowInfo.flags;
Prabir Pradhand65552b2021-10-07 11:23:50 -0700521 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
522 if (flags.test(WindowInfo::Flag::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800523 return false;
524 }
525 const bool isModalWindow = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
526 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
527 if (!isModalWindow && !windowInfo.touchableRegionContainsPoint(x, y)) {
528 return false;
529 }
530 return true;
531}
532
Prabir Pradhand65552b2021-10-07 11:23:50 -0700533bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
534 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
535 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
536 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
537}
538
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000539} // namespace
540
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541// --- InputDispatcher ---
542
Garfield Tan00f511d2019-06-12 16:55:40 -0700543InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
544 : mPolicy(policy),
545 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700546 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800547 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700548 mAppSwitchSawKeyDown(false),
549 mAppSwitchDueTime(LONG_LONG_MAX),
550 mNextUnblockedEvent(nullptr),
551 mDispatchEnabled(false),
552 mDispatchFrozen(false),
553 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800554 // mInTouchMode will be initialized by the WindowManager to the default device config.
555 // To avoid leaking stack in case that call never comes, and for tests,
556 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000557 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100558 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000559 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800560 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000561 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800562 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800564 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700566 mWindowInfoListener = new DispatcherWindowListener(*this);
567 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
568
Yi Kong9b14ac62018-07-17 13:48:38 -0700569 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
571 policy->getDispatcherConfiguration(&mConfig);
572}
573
574InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000575 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Prabir Pradhancef936d2021-07-21 16:17:52 +0000577 resetKeyRepeatLocked();
578 releasePendingEventLocked();
579 drainInboundQueueLocked();
580 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000582 while (!mConnectionsByToken.empty()) {
583 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000584 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
585 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 }
587}
588
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700589status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700590 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591 return ALREADY_EXISTS;
592 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700593 mThread = std::make_unique<InputThread>(
594 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
595 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596}
597
598status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700599 if (mThread && mThread->isCallingThread()) {
600 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700601 return INVALID_OPERATION;
602 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700603 mThread.reset();
604 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700605}
606
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607void InputDispatcher::dispatchOnce() {
608 nsecs_t nextWakeupTime = LONG_LONG_MAX;
609 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800610 std::scoped_lock _l(mLock);
611 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612
613 // Run a dispatch loop if there are no pending commands.
614 // The dispatch loop might enqueue commands to run afterwards.
615 if (!haveCommandsLocked()) {
616 dispatchOnceInnerLocked(&nextWakeupTime);
617 }
618
619 // Run all pending commands if there are any.
620 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000621 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 nextWakeupTime = LONG_LONG_MIN;
623 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800624
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700625 // If we are still waiting for ack on some events,
626 // we might have to wake up earlier to check if an app is anr'ing.
627 const nsecs_t nextAnrCheck = processAnrsLocked();
628 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
629
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800630 // We are about to enter an infinitely long sleep, because we have no commands or
631 // pending or queued events
632 if (nextWakeupTime == LONG_LONG_MAX) {
633 mDispatcherEnteredIdle.notify_all();
634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 } // release lock
636
637 // Wait for callback or timeout or wake. (make sure we round up, not down)
638 nsecs_t currentTime = now();
639 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
640 mLooper->pollOnce(timeoutMillis);
641}
642
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500644 * Raise ANR if there is no focused window.
645 * Before the ANR is raised, do a final state check:
646 * 1. The currently focused application must be the same one we are waiting for.
647 * 2. Ensure we still don't have a focused window.
648 */
649void InputDispatcher::processNoFocusedWindowAnrLocked() {
650 // Check if the application that we are waiting for is still focused.
651 std::shared_ptr<InputApplicationHandle> focusedApplication =
652 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
653 if (focusedApplication == nullptr ||
654 focusedApplication->getApplicationToken() !=
655 mAwaitedFocusedApplication->getApplicationToken()) {
656 // Unexpected because we should have reset the ANR timer when focused application changed
657 ALOGE("Waited for a focused window, but focused application has already changed to %s",
658 focusedApplication->getName().c_str());
659 return; // The focused application has changed.
660 }
661
chaviw98318de2021-05-19 16:45:23 -0500662 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500663 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
664 if (focusedWindowHandle != nullptr) {
665 return; // We now have a focused window. No need for ANR.
666 }
667 onAnrLocked(mAwaitedFocusedApplication);
668}
669
670/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 * Check if any of the connections' wait queues have events that are too old.
672 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
673 * Return the time at which we should wake up next.
674 */
675nsecs_t InputDispatcher::processAnrsLocked() {
676 const nsecs_t currentTime = now();
677 nsecs_t nextAnrCheck = LONG_LONG_MAX;
678 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
679 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
680 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500681 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700682 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700684 return LONG_LONG_MIN;
685 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500686 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700687 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
688 }
689 }
690
691 // Check if any connection ANRs are due
692 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
693 if (currentTime < nextAnrCheck) { // most likely scenario
694 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
695 }
696
697 // If we reached here, we have an unresponsive connection.
698 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
699 if (connection == nullptr) {
700 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
701 return nextAnrCheck;
702 }
703 connection->responsive = false;
704 // Stop waking up for this unresponsive connection
705 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000706 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 return LONG_LONG_MIN;
708}
709
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500710std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500711 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500713 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500715 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716}
717
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
719 nsecs_t currentTime = now();
720
Jeff Browndc5992e2014-04-11 01:27:26 -0700721 // Reset the key repeat timer whenever normal dispatch is suspended while the
722 // device is in a non-interactive state. This is to ensure that we abort a key
723 // repeat if the device is just coming out of sleep.
724 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 resetKeyRepeatLocked();
726 }
727
728 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
729 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100730 if (DEBUG_FOCUS) {
731 ALOGD("Dispatch frozen. Waiting some more.");
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 return;
734 }
735
736 // Optimize latency of app switches.
737 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
738 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
739 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
740 if (mAppSwitchDueTime < *nextWakeupTime) {
741 *nextWakeupTime = mAppSwitchDueTime;
742 }
743
744 // Ready to start a new event.
745 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700747 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 if (isAppSwitchDue) {
749 // The inbound queue is empty so the app switch key we were waiting
750 // for will never arrive. Stop waiting for it.
751 resetPendingAppSwitchLocked(false);
752 isAppSwitchDue = false;
753 }
754
755 // Synthesize a key repeat if appropriate.
756 if (mKeyRepeatState.lastKeyEntry) {
757 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
758 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
759 } else {
760 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
761 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
762 }
763 }
764 }
765
766 // Nothing to do if there is no pending event.
767 if (!mPendingEvent) {
768 return;
769 }
770 } else {
771 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 mPendingEvent = mInboundQueue.front();
773 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 traceInboundQueueLengthLocked();
775 }
776
777 // Poke user activity for this event.
778 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700779 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
782
783 // Now we have an event to dispatch.
784 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700787 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700791 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700795 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700799 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700800 const ConfigurationChangedEntry& typedEntry =
801 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700807 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 const DeviceResetEntry& typedEntry =
809 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700810 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 break;
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100815 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 std::shared_ptr<FocusEntry> typedEntry =
817 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100818 dispatchFocusLocked(currentTime, typedEntry);
819 done = true;
820 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
821 break;
822 }
823
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700824 case EventEntry::Type::TOUCH_MODE_CHANGED: {
825 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
826 dispatchTouchModeChangeLocked(currentTime, typedEntry);
827 done = true;
828 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
829 break;
830 }
831
Prabir Pradhan99987712020-11-10 18:43:05 -0800832 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
833 const auto typedEntry =
834 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
835 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
836 done = true;
837 break;
838 }
839
arthurhungb89ccb02020-12-30 16:19:01 +0800840 case EventEntry::Type::DRAG: {
841 std::shared_ptr<DragEntry> typedEntry =
842 std::static_pointer_cast<DragEntry>(mPendingEvent);
843 dispatchDragLocked(currentTime, typedEntry);
844 done = true;
845 break;
846 }
847
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700848 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700851 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 resetPendingAppSwitchLocked(true);
853 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700854 } else if (dropReason == DropReason::NOT_DROPPED) {
855 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 }
857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
862 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700864 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 break;
866 }
867
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700868 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 std::shared_ptr<MotionEntry> motionEntry =
870 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
872 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
878 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 }
Chris Yef59a2f42020-10-16 12:55:26 -0700883
884 case EventEntry::Type::SENSOR: {
885 std::shared_ptr<SensorEntry> sensorEntry =
886 std::static_pointer_cast<SensorEntry>(mPendingEvent);
887 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
888 dropReason = DropReason::APP_SWITCH;
889 }
890 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
891 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
892 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
893 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
894 dropReason = DropReason::STALE;
895 }
896 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
897 done = true;
898 break;
899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901
902 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Michael Wright3a981722015-06-10 15:26:13 +0100906 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
908 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
911}
912
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700913/**
914 * Return true if the events preceding this incoming motion event should be dropped
915 * Return false otherwise (the default behaviour)
916 */
917bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700918 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700919 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700920
921 // Optimize case where the current application is unresponsive and the user
922 // decides to touch a window in a different application.
923 // If the application takes too long to catch up then we drop all events preceding
924 // the touch into the other window.
925 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 int32_t displayId = motionEntry.displayId;
927 int32_t x = static_cast<int32_t>(
928 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
929 int32_t y = static_cast<int32_t>(
930 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700931
932 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500933 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700934 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700935 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936 touchedWindowHandle->getApplicationToken() !=
937 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700938 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 ALOGI("Pruning input queue because user touched a different application while waiting "
940 "for %s",
941 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700942 return true;
943 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944
945 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700946 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700948 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000949 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 // This monitor could take more input. Drop all events preceding this
951 // event, so that gesture monitor could get a chance to receive the stream
952 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
953 "responsive gesture monitor that may handle the event",
954 mAwaitedFocusedApplication->getName().c_str());
955 return true;
956 }
957 }
958 }
959
960 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
961 // yet been processed by some connections, the dispatcher will wait for these motion
962 // events to be processed before dispatching the key event. This is because these motion events
963 // may cause a new window to be launched, which the user might expect to receive focus.
964 // To prevent waiting forever for such events, just send the key to the currently focused window
965 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
966 ALOGD("Received a new pointer down event, stop waiting for events to process and "
967 "just send the pending key event to the focused window.");
968 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700969 }
970 return false;
971}
972
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700973bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700974 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 mInboundQueue.push_back(std::move(newEntry));
976 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 traceInboundQueueLengthLocked();
978
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700980 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 // Optimize app switch latency.
982 // If the application takes too long to catch up then we drop all events preceding
983 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700986 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700988 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000990 if (DEBUG_APP_SWITCH) {
991 ALOGD("App switch is pending!");
992 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700993 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 mAppSwitchSawKeyDown = false;
995 needWake = true;
996 }
997 }
998 }
999 break;
1000 }
1001
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001002 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001003 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1004 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001005 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001009 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001010 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1011 break;
1012 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001013 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001014 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001015 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001016 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001017 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1018 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001019 // nothing to do
1020 break;
1021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
1023
1024 return needWake;
1025}
1026
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001027void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001028 // Do not store sensor event in recent queue to avoid flooding the queue.
1029 if (entry->type != EventEntry::Type::SENSOR) {
1030 mRecentQueue.push_back(entry);
1031 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001033 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034 }
1035}
1036
chaviw98318de2021-05-19 16:45:23 -05001037sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1038 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001039 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001040 bool addOutsideTargets,
1041 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001042 if (addOutsideTargets && touchState == nullptr) {
1043 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001046 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001047 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001048 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001049 continue;
1050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001052 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001053 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001054 return windowHandle;
1055 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001056
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001057 if (addOutsideTargets && info.flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
1058 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1059 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
1061 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001062 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063}
1064
Prabir Pradhand65552b2021-10-07 11:23:50 -07001065std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1066 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001067 // Traverse windows from front to back and gather the touched spy windows.
1068 std::vector<sp<WindowInfoHandle>> spyWindows;
1069 const auto& windowHandles = getWindowHandlesLocked(displayId);
1070 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1071 const WindowInfo& info = *windowHandle->getInfo();
1072
Prabir Pradhand65552b2021-10-07 11:23:50 -07001073 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001074 continue;
1075 }
1076 if (!info.isSpy()) {
1077 // The first touched non-spy window was found, so return the spy windows touched so far.
1078 return spyWindows;
1079 }
1080 spyWindows.push_back(windowHandle);
1081 }
1082 return spyWindows;
1083}
1084
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 const char* reason;
1087 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001089 if (DEBUG_INBOUND_EVENT_DETAILS) {
1090 ALOGD("Dropped event because policy consumed it.");
1091 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 reason = "inbound event was dropped because the policy consumed it";
1093 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001094 case DropReason::DISABLED:
1095 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 ALOGI("Dropped event because input dispatch is disabled.");
1097 }
1098 reason = "inbound event was dropped because input dispatch is disabled";
1099 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001100 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 ALOGI("Dropped event because of pending overdue app switch.");
1102 reason = "inbound event was dropped because of pending overdue app switch";
1103 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001104 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 ALOGI("Dropped event because the current application is not responding and the user "
1106 "has started interacting with a different application.");
1107 reason = "inbound event was dropped because the current application is not responding "
1108 "and the user has started interacting with a different application";
1109 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001110 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 ALOGI("Dropped event because it is stale.");
1112 reason = "inbound event was dropped because it is stale";
1113 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001114 case DropReason::NO_POINTER_CAPTURE:
1115 ALOGI("Dropped event because there is no window with Pointer Capture.");
1116 reason = "inbound event was dropped because there is no window with Pointer Capture";
1117 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 case DropReason::NOT_DROPPED: {
1119 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
1123
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001125 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1127 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001130 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001131 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1132 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1134 synthesizeCancelationEventsForAllConnectionsLocked(options);
1135 } else {
1136 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1137 synthesizeCancelationEventsForAllConnectionsLocked(options);
1138 }
1139 break;
1140 }
Chris Yef59a2f42020-10-16 12:55:26 -07001141 case EventEntry::Type::SENSOR: {
1142 break;
1143 }
arthurhungb89ccb02020-12-30 16:19:01 +08001144 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1145 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001146 break;
1147 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001148 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001149 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001150 case EventEntry::Type::CONFIGURATION_CHANGED:
1151 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001152 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001153 break;
1154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156}
1157
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001158static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1160 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161}
1162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001163bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1164 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1165 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1166 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167}
1168
1169bool InputDispatcher::isAppSwitchPendingLocked() {
1170 return mAppSwitchDueTime != LONG_LONG_MAX;
1171}
1172
1173void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1174 mAppSwitchDueTime = LONG_LONG_MAX;
1175
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001176 if (DEBUG_APP_SWITCH) {
1177 if (handled) {
1178 ALOGD("App switch has arrived.");
1179 } else {
1180 ALOGD("App switch was abandoned.");
1181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183}
1184
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001186 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187}
1188
Prabir Pradhancef936d2021-07-21 16:17:52 +00001189bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001190 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 return false;
1192 }
1193
1194 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001195 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001196 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001197 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1198 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001199 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 return true;
1201}
1202
Prabir Pradhancef936d2021-07-21 16:17:52 +00001203void InputDispatcher::postCommandLocked(Command&& command) {
1204 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205}
1206
1207void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001208 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001210 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 releaseInboundEventLocked(entry);
1212 }
1213 traceInboundQueueLengthLocked();
1214}
1215
1216void InputDispatcher::releasePendingEventLocked() {
1217 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001219 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 }
1221}
1222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001225 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001226 if (DEBUG_DISPATCH_CYCLE) {
1227 ALOGD("Injected inbound event was dropped.");
1228 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001229 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 }
1231 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001232 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
1237void InputDispatcher::resetKeyRepeatLocked() {
1238 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001239 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241}
1242
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1244 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245
Michael Wright2e732952014-09-24 13:26:59 -07001246 uint32_t policyFlags = entry->policyFlags &
1247 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249 std::shared_ptr<KeyEntry> newEntry =
1250 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1251 entry->source, entry->displayId, policyFlags, entry->action,
1252 entry->flags, entry->keyCode, entry->scanCode,
1253 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 newEntry->syntheticRepeat = true;
1256 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001258 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259}
1260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001263 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1264 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266
1267 // Reset key repeating in case a keyboard device was added or removed or something.
1268 resetKeyRepeatLocked();
1269
1270 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001271 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1272 scoped_unlock unlock(mLock);
1273 mPolicy->notifyConfigurationChanged(eventTime);
1274 };
1275 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 return true;
1277}
1278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1280 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001281 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1282 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1283 entry.deviceId);
1284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
liushenxiang42232912021-05-21 20:24:09 +08001286 // Reset key repeating in case a keyboard device was disabled or enabled.
1287 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1288 resetKeyRepeatLocked();
1289 }
1290
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 synthesizeCancelationEventsForAllConnectionsLocked(options);
1294 return true;
1295}
1296
Vishnu Nairad321cd2020-08-20 16:40:21 -07001297void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001298 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001299 if (mPendingEvent != nullptr) {
1300 // Move the pending event to the front of the queue. This will give the chance
1301 // for the pending event to get dispatched to the newly focused window
1302 mInboundQueue.push_front(mPendingEvent);
1303 mPendingEvent = nullptr;
1304 }
1305
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001306 std::unique_ptr<FocusEntry> focusEntry =
1307 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1308 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001309
1310 // This event should go to the front of the queue, but behind all other focus events
1311 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001312 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001313 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314 [](const std::shared_ptr<EventEntry>& event) {
1315 return event->type == EventEntry::Type::FOCUS;
1316 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001317
1318 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001319 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001320}
1321
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001322void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001323 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001324 if (channel == nullptr) {
1325 return; // Window has gone away
1326 }
1327 InputTarget target;
1328 target.inputChannel = channel;
1329 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1330 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001331 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1332 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001333 std::string reason = std::string("reason=").append(entry->reason);
1334 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001335 dispatchEventLocked(currentTime, entry, {target});
1336}
1337
Prabir Pradhan99987712020-11-10 18:43:05 -08001338void InputDispatcher::dispatchPointerCaptureChangedLocked(
1339 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1340 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001341 dropReason = DropReason::NOT_DROPPED;
1342
Prabir Pradhan99987712020-11-10 18:43:05 -08001343 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001344 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001345
1346 if (entry->pointerCaptureRequest.enable) {
1347 // Enable Pointer Capture.
1348 if (haveWindowWithPointerCapture &&
1349 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1350 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1351 "to the window.");
1352 }
1353 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001354 // This can happen if a window requests capture and immediately releases capture.
1355 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001356 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001357 return;
1358 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001359 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1360 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1361 return;
1362 }
1363
Vishnu Nairc519ff72021-01-21 08:23:08 -08001364 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001365 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1366 mWindowTokenWithPointerCapture = token;
1367 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001368 // Disable Pointer Capture.
1369 // We do not check if the sequence number matches for requests to disable Pointer Capture
1370 // for two reasons:
1371 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1372 // to disable capture with the same sequence number: one generated by
1373 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1374 // Capture being disabled in InputReader.
1375 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1376 // actual Pointer Capture state that affects events being generated by input devices is
1377 // in InputReader.
1378 if (!haveWindowWithPointerCapture) {
1379 // Pointer capture was already forcefully disabled because of focus change.
1380 dropReason = DropReason::NOT_DROPPED;
1381 return;
1382 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001383 token = mWindowTokenWithPointerCapture;
1384 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001385 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001386 setPointerCaptureLocked(false);
1387 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001388 }
1389
1390 auto channel = getInputChannelLocked(token);
1391 if (channel == nullptr) {
1392 // Window has gone away, clean up Pointer Capture state.
1393 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001394 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001395 setPointerCaptureLocked(false);
1396 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001397 return;
1398 }
1399 InputTarget target;
1400 target.inputChannel = channel;
1401 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1402 entry->dispatchInProgress = true;
1403 dispatchEventLocked(currentTime, entry, {target});
1404
1405 dropReason = DropReason::NOT_DROPPED;
1406}
1407
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001408void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1409 const std::shared_ptr<TouchModeEntry>& entry) {
1410 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1411 getWindowHandlesLocked(mFocusedDisplayId);
1412 if (windowHandles.empty()) {
1413 return;
1414 }
1415 const std::vector<InputTarget> inputTargets =
1416 getInputTargetsFromWindowHandlesLocked(windowHandles);
1417 if (inputTargets.empty()) {
1418 return;
1419 }
1420 entry->dispatchInProgress = true;
1421 dispatchEventLocked(currentTime, entry, inputTargets);
1422}
1423
1424std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1425 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1426 std::vector<InputTarget> inputTargets;
1427 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1428 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1429 const sp<IBinder>& token = handle->getToken();
1430 if (token == nullptr) {
1431 continue;
1432 }
1433 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1434 if (channel == nullptr) {
1435 continue; // Window has gone away
1436 }
1437 InputTarget target;
1438 target.inputChannel = channel;
1439 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1440 inputTargets.push_back(target);
1441 }
1442 return inputTargets;
1443}
1444
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001445bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001448 if (!entry->dispatchInProgress) {
1449 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1450 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1451 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1452 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001453 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 // We have seen two identical key downs in a row which indicates that the device
1455 // driver is automatically generating key repeats itself. We take note of the
1456 // repeat here, but we disable our own next key repeat timer since it is clear that
1457 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001458 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1459 // Make sure we don't get key down from a different device. If a different
1460 // device Id has same key pressed down, the new device Id will replace the
1461 // current one to hold the key repeat with repeat count reset.
1462 // In the future when got a KEY_UP on the device id, drop it and do not
1463 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1465 resetKeyRepeatLocked();
1466 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1467 } else {
1468 // Not a repeat. Save key down state in case we do see a repeat later.
1469 resetKeyRepeatLocked();
1470 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1471 }
1472 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001473 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1474 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001475 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001476 if (DEBUG_INBOUND_EVENT_DETAILS) {
1477 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1478 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001479 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 resetKeyRepeatLocked();
1481 }
1482
1483 if (entry->repeatCount == 1) {
1484 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1485 } else {
1486 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1487 }
1488
1489 entry->dispatchInProgress = true;
1490
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001491 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 }
1493
1494 // Handle case where the policy asked us to try again later last time.
1495 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1496 if (currentTime < entry->interceptKeyWakeupTime) {
1497 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1498 *nextWakeupTime = entry->interceptKeyWakeupTime;
1499 }
1500 return false; // wait until next wakeup
1501 }
1502 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1503 entry->interceptKeyWakeupTime = 0;
1504 }
1505
1506 // Give the policy a chance to intercept the key.
1507 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1508 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001509 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001510 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001511
1512 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1513 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1514 };
1515 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 return false; // wait for the command to run
1517 } else {
1518 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1519 }
1520 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001521 if (*dropReason == DropReason::NOT_DROPPED) {
1522 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 }
1524 }
1525
1526 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001527 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001528 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001529 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1530 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001531 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533 }
1534
1535 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001536 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001537 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 return false;
1541 }
1542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001543 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001544 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 return true;
1546 }
1547
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001548 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550
1551 // Dispatch the key.
1552 dispatchEventLocked(currentTime, entry, inputTargets);
1553 return true;
1554}
1555
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001556void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001557 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1558 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1559 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1560 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1561 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1562 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1563 entry.metaState, entry.repeatCount, entry.downTime);
1564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565}
1566
Prabir Pradhancef936d2021-07-21 16:17:52 +00001567void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1568 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001569 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001570 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1571 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1572 "source=0x%x, sensorType=%s",
1573 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001574 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001575 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001576 auto command = [this, entry]() REQUIRES(mLock) {
1577 scoped_unlock unlock(mLock);
1578
1579 if (entry->accuracyChanged) {
1580 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1581 }
1582 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1583 entry->hwTimestamp, entry->values);
1584 };
1585 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001586}
1587
1588bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001589 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1590 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001591 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001592 }
Chris Yef59a2f42020-10-16 12:55:26 -07001593 { // acquire lock
1594 std::scoped_lock _l(mLock);
1595
1596 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1597 std::shared_ptr<EventEntry> entry = *it;
1598 if (entry->type == EventEntry::Type::SENSOR) {
1599 it = mInboundQueue.erase(it);
1600 releaseInboundEventLocked(entry);
1601 }
1602 }
1603 }
1604 return true;
1605}
1606
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001607bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001609 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 entry->dispatchInProgress = true;
1613
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616
1617 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001618 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001619 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1621 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 return true;
1623 }
1624
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001625 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626
1627 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001628 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629
1630 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001631 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 if (isPointerEvent) {
1633 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001634 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001635 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001636 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 } else {
1638 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001639 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001642 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 return false;
1644 }
1645
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001646 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001647 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001648 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1649 return true;
1650 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001651 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001652 CancelationOptions::Mode mode(isPointerEvent
1653 ? CancelationOptions::CANCEL_POINTER_EVENTS
1654 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1655 CancelationOptions options(mode, "input event injection failed");
1656 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return true;
1658 }
1659
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001660 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662
1663 // Dispatch the motion.
1664 if (conflictingPointerActions) {
1665 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 synthesizeCancelationEventsForAllConnectionsLocked(options);
1668 }
1669 dispatchEventLocked(currentTime, entry, inputTargets);
1670 return true;
1671}
1672
chaviw98318de2021-05-19 16:45:23 -05001673void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001674 bool isExiting, const MotionEntry& motionEntry) {
1675 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1676 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1677 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1678 PointerCoords pointerCoords;
1679 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1680 pointerCoords.transform(windowHandle->getInfo()->transform);
1681
1682 std::unique_ptr<DragEntry> dragEntry =
1683 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1684 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1685 pointerCoords.getY());
1686
1687 enqueueInboundEventLocked(std::move(dragEntry));
1688}
1689
1690void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1691 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1692 if (channel == nullptr) {
1693 return; // Window has gone away
1694 }
1695 InputTarget target;
1696 target.inputChannel = channel;
1697 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1698 entry->dispatchInProgress = true;
1699 dispatchEventLocked(currentTime, entry, {target});
1700}
1701
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001702void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001703 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1704 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1705 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001706 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001707 "metaState=0x%x, buttonState=0x%x,"
1708 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1709 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001710 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1711 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1712 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001714 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1715 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1716 "x=%f, y=%f, pressure=%f, size=%f, "
1717 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1718 "orientation=%f",
1719 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1720 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1721 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1722 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1723 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1724 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1725 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1726 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1727 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1728 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731}
1732
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001733void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1734 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001735 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001737 if (DEBUG_DISPATCH_CYCLE) {
1738 ALOGD("dispatchEventToCurrentInputTargets");
1739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001741 updateInteractionTokensLocked(*eventEntry, inputTargets);
1742
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1744
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001745 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001747 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001748 sp<Connection> connection =
1749 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001750 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001751 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001753 if (DEBUG_FOCUS) {
1754 ALOGD("Dropping event delivery to target with channel '%s' because it "
1755 "is no longer registered with the input dispatcher.",
1756 inputTarget.inputChannel->getName().c_str());
1757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759 }
1760}
1761
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001762void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1763 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1764 // If the policy decides to close the app, we will get a channel removal event via
1765 // unregisterInputChannel, and will clean up the connection that way. We are already not
1766 // sending new pointers to the connection when it blocked, but focused events will continue to
1767 // pile up.
1768 ALOGW("Canceling events for %s because it is unresponsive",
1769 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001770 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001771 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1772 "application not responding");
1773 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 }
1775}
1776
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001777void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001778 if (DEBUG_FOCUS) {
1779 ALOGD("Resetting ANR timeouts.");
1780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
1782 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001783 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001784 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785}
1786
Tiger Huang721e26f2018-07-24 22:26:19 +08001787/**
1788 * Get the display id that the given event should go to. If this event specifies a valid display id,
1789 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1790 * Focused display is the display that the user most recently interacted with.
1791 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001792int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001793 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001794 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001795 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1797 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001798 break;
1799 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001800 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001801 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1802 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001803 break;
1804 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001805 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001806 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001807 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001808 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001809 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001810 case EventEntry::Type::SENSOR:
1811 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001812 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001813 return ADISPLAY_ID_NONE;
1814 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001815 }
1816 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1817}
1818
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001819bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1820 const char* focusedWindowName) {
1821 if (mAnrTracker.empty()) {
1822 // already processed all events that we waited for
1823 mKeyIsWaitingForEventsTimeout = std::nullopt;
1824 return false;
1825 }
1826
1827 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1828 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001829 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001830 mKeyIsWaitingForEventsTimeout = currentTime +
1831 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1832 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 return true;
1834 }
1835
1836 // We still have pending events, and already started the timer
1837 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1838 return true; // Still waiting
1839 }
1840
1841 // Waited too long, and some connection still hasn't processed all motions
1842 // Just send the key to the focused window
1843 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1844 focusedWindowName);
1845 mKeyIsWaitingForEventsTimeout = std::nullopt;
1846 return false;
1847}
1848
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001849InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1850 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1851 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001852 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
Tiger Huang721e26f2018-07-24 22:26:19 +08001854 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001855 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001856 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001857 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1858
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 // If there is no currently focused window and no focused application
1860 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001861 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1862 ALOGI("Dropping %s event because there is no focused window or focused application in "
1863 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001864 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001865 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 }
1867
Vishnu Nair062a8672021-09-03 16:07:44 -07001868 // Drop key events if requested by input feature
1869 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1870 return InputEventInjectionResult::FAILED;
1871 }
1872
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001873 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1874 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1875 // start interacting with another application via touch (app switch). This code can be removed
1876 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1877 // an app is expected to have a focused window.
1878 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1879 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1880 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001881 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1882 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1883 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001885 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001886 ALOGW("Waiting because no window has focus but %s may eventually add a "
1887 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001888 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001890 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001891 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1892 // Already raised ANR. Drop the event
1893 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001894 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001896 } else {
1897 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001898 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899 }
1900 }
1901
1902 // we have a valid, non-null focused window
1903 resetNoFocusedWindowTimeoutLocked();
1904
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001906 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 }
1909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910 if (focusedWindowHandle->getInfo()->paused) {
1911 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001912 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 }
1914
1915 // If the event is a key event, then we must wait for all previous events to
1916 // complete before delivering it because previous events may have the
1917 // side-effect of transferring focus to a different window and we want to
1918 // ensure that the following keys are sent to the new window.
1919 //
1920 // Suppose the user touches a button in a window then immediately presses "A".
1921 // If the button causes a pop-up window to appear then we want to ensure that
1922 // the "A" key is delivered to the new pop-up window. This is because users
1923 // often anticipate pending UI changes when typing on a keyboard.
1924 // To obtain this behavior, we must serialize key events with respect to all
1925 // prior input events.
1926 if (entry.type == EventEntry::Type::KEY) {
1927 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1928 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932
1933 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001934 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1936 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937
1938 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940}
1941
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001942/**
1943 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1944 * that are currently unresponsive.
1945 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001946std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1947 const std::vector<Monitor>& monitors) const {
1948 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001950 [this](const Monitor& monitor) REQUIRES(mLock) {
1951 sp<Connection> connection =
1952 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001953 if (connection == nullptr) {
1954 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001955 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 return false;
1957 }
1958 if (!connection->responsive) {
1959 ALOGW("Unresponsive monitor %s will not get the new gesture",
1960 connection->inputChannel->getName().c_str());
1961 return false;
1962 }
1963 return true;
1964 });
1965 return responsiveMonitors;
1966}
1967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1969 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1970 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001971 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 enum InjectionPermission {
1973 INJECTION_PERMISSION_UNKNOWN,
1974 INJECTION_PERMISSION_GRANTED,
1975 INJECTION_PERMISSION_DENIED
1976 };
1977
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 // For security reasons, we defer updating the touch state until we are sure that
1979 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001980 const int32_t displayId = entry.displayId;
1981 const int32_t action = entry.action;
1982 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983
1984 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001985 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001987 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1988 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001990 // Copy current touch state into tempTouchState.
1991 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1992 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001993 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001994 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001995 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1996 oldState = &(it->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001998 }
1999
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002000 bool isSplit = tempTouchState.split;
2001 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2002 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2003 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002004
2005 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2006 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2007 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2008 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2009 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002010 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 bool wrongDevice = false;
2012 if (newGesture) {
2013 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002014 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002015 ALOGI("Dropping event because a pointer for a different device is already down "
2016 "in display %" PRId32,
2017 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002018 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002019 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 switchedDevice = false;
2021 wrongDevice = true;
2022 goto Failed;
2023 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002024 tempTouchState.reset();
2025 tempTouchState.down = down;
2026 tempTouchState.deviceId = entry.deviceId;
2027 tempTouchState.source = entry.source;
2028 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002030 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002031 ALOGI("Dropping move event because a pointer for a different device is already active "
2032 "in display %" PRId32,
2033 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002034 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002036 switchedDevice = false;
2037 wrongDevice = true;
2038 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
2040
2041 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2042 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2043
Garfield Tan00f511d2019-06-12 16:55:40 -07002044 int32_t x;
2045 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002046 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002047 // Always dispatch mouse events to cursor position.
2048 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002049 x = int32_t(entry.xCursorPosition);
2050 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002051 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002052 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2053 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002054 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002055 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002056 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002057 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002058 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002061 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002062 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2063 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002066 }
2067
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002068 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002070 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2071 // New window supports splitting, but we should never split mouse events.
2072 isSplit = !isFromMouse;
2073 } else if (isSplit) {
2074 // New window does not support splitting but we have already split events.
2075 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002076 newTouchedWindowHandle = nullptr;
2077 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002078 } else {
2079 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002080 // be delivered to a new window which supports split touch. Pointers from a mouse device
2081 // should never be split.
2082 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002083 }
2084
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002085 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002087 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2088 newHoverWindowHandle = nullptr;
2089 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002090 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002091 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002092 }
2093
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002094 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002095 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002096 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002097 // Process the foreground window first so that it is the first to receive the event.
2098 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002099 }
2100
2101 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2102 const WindowInfo& info = *windowHandle->getInfo();
2103
2104 if (info.paused) {
2105 ALOGI("Not sending touch event to %s because it is paused",
2106 windowHandle->getName().c_str());
2107 continue;
2108 }
2109
2110 // Ensure the window has a connection and the connection is responsive
2111 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2112 if (!isResponsive) {
2113 ALOGW("Not sending touch gesture to %s because it is not responsive",
2114 windowHandle->getName().c_str());
2115 continue;
2116 }
2117
2118 // Drop events that can't be trusted due to occlusion
2119 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2120 TouchOcclusionInfo occlusionInfo =
2121 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2122 if (!isTouchTrustedLocked(occlusionInfo)) {
2123 if (DEBUG_TOUCH_OCCLUSION) {
2124 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2125 for (const auto& log : occlusionInfo.debugInfo) {
2126 ALOGD("%s", log.c_str());
2127 }
2128 }
2129 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2130 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2131 ALOGW("Dropping untrusted touch event due to %s/%d",
2132 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2133 continue;
2134 }
2135 }
2136 }
2137
2138 // Drop touch events if requested by input feature
2139 if (shouldDropInput(entry, windowHandle)) {
2140 continue;
2141 }
2142
2143 // Set target flags.
2144 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2145
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002146 if (!info.isSpy()) {
2147 // There should only be one new foreground (non-spy) window at this location.
2148 targetFlags |= InputTarget::FLAG_FOREGROUND;
2149 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002150
2151 if (isSplit) {
2152 targetFlags |= InputTarget::FLAG_SPLIT;
2153 }
2154 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2155 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2156 } else if (isWindowObscuredLocked(windowHandle)) {
2157 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2158 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002159
2160 // Update the temporary touch state.
2161 BitSet32 pointerIds;
2162 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002164 pointerIds.markBit(pointerId);
2165 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166
2167 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002169
2170 const std::vector<Monitor> newGestureMonitors = isDown
2171 ? selectResponsiveMonitorsLocked(
2172 getValueByKey(mGestureMonitorsByDisplay, displayId))
2173 : std::vector<Monitor>{};
2174
2175 if (newTouchedWindows.empty() && newGestureMonitors.empty() &&
2176 tempTouchState.gestureMonitors.empty()) {
2177 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
2178 "(%d, %d) in display %" PRId32 ".",
2179 x, y, displayId);
2180 injectionResult = InputEventInjectionResult::FAILED;
2181 goto Failed;
Arthur Hung2ea44b92021-11-23 07:42:21 +00002182 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183
2184 tempTouchState.addGestureMonitors(newGestureMonitors);
2185
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 } else {
2187 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2188
2189 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002190 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002191 if (DEBUG_FOCUS) {
2192 ALOGD("Dropping event because the pointer is not down or we previously "
2193 "dropped the pointer down event in display %" PRId32,
2194 displayId);
2195 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002196 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 goto Failed;
2198 }
2199
arthurhung6d4bed92021-03-17 11:59:33 +08002200 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002201
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002203 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002205 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2206 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207
Prabir Pradhand65552b2021-10-07 11:23:50 -07002208 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002209 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002210 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002211 newTouchedWindowHandle =
2212 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002213
2214 // Drop touch events if requested by input feature
2215 if (newTouchedWindowHandle != nullptr &&
2216 shouldDropInput(entry, newTouchedWindowHandle)) {
2217 newTouchedWindowHandle = nullptr;
2218 }
2219
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002220 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2221 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002222 if (DEBUG_FOCUS) {
2223 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2224 oldTouchedWindowHandle->getName().c_str(),
2225 newTouchedWindowHandle->getName().c_str(), displayId);
2226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002228 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2229 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2230 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
2232 // Make a slippery entrance into the new window.
2233 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002234 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
2236
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002237 int32_t targetFlags =
2238 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 if (isSplit) {
2240 targetFlags |= InputTarget::FLAG_SPLIT;
2241 }
2242 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2243 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002244 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2245 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 }
2247
2248 BitSet32 pointerIds;
2249 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002250 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 }
2254 }
2255 }
2256
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002257 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002259 // Let the previous window know that the hover sequence is over, unless we already did
2260 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002261 if (mLastHoverWindowHandle != nullptr &&
2262 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2263 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002264 if (DEBUG_HOVER) {
2265 ALOGD("Sending hover exit event to window %s.",
2266 mLastHoverWindowHandle->getName().c_str());
2267 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002268 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2269 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271
Garfield Tandf26e862020-07-01 20:18:19 -07002272 // Let the new window know that the hover sequence is starting, unless we already did it
2273 // when dispatching it as is to newTouchedWindowHandle.
2274 if (newHoverWindowHandle != nullptr &&
2275 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2276 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002277 if (DEBUG_HOVER) {
2278 ALOGD("Sending hover enter event to window %s.",
2279 newHoverWindowHandle->getName().c_str());
2280 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2282 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2283 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
2285 }
2286
2287 // Check permission to inject into all touched foreground windows and ensure there
2288 // is at least one touched foreground window.
2289 {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002290 bool haveForegroundOrSpyWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002291 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002292 const bool isForeground =
2293 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
2294 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2295 haveForegroundOrSpyWindow = true;
2296 LOG_ALWAYS_FATAL_IF(isForeground,
2297 "Spy window cannot be dispatched as a foreground window.");
2298 }
2299 if (isForeground) {
2300 haveForegroundOrSpyWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002301 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002302 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 injectionPermission = INJECTION_PERMISSION_DENIED;
2304 goto Failed;
2305 }
2306 }
2307 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002308 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002309 if (!haveForegroundOrSpyWindow && !hasGestureMonitor) {
2310 ALOGI("Dropping event because there is no touched window in display "
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002311 "%" PRId32 " or gesture monitor to receive it.",
2312 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002313 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 goto Failed;
2315 }
2316
2317 // Permission granted to injection into all touched foreground windows.
2318 injectionPermission = INJECTION_PERMISSION_GRANTED;
2319 }
2320
2321 // Check whether windows listening for outside touches are owned by the same UID. If it is
2322 // set the policy flag that we will not reveal coordinate information to this window.
2323 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002324 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002325 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002326 if (foregroundWindowHandle) {
2327 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002328 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002329 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002330 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2331 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2332 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002333 InputTarget::FLAG_ZERO_COORDS,
2334 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
2337 }
2338 }
2339 }
2340
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 // If this is the first pointer going down and the touched window has a wallpaper
2342 // then also add the touched wallpaper windows so they are locked in for the duration
2343 // of the touch gesture.
2344 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2345 // engine only supports touch events. We would need to add a mechanism similar
2346 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2347 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002348 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002349 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002350 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002351 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002352 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002353 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2354 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002356 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002357 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 .addOrUpdateWindow(windowHandle,
2359 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2360 InputTarget::
2361 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2362 InputTarget::FLAG_DISPATCH_AS_IS,
2363 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 }
2365 }
2366 }
2367 }
2368
2369 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002370 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002372 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002377 for (const auto& monitor : tempTouchState.gestureMonitors) {
2378 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002379 }
2380
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 // Drop the outside or hover touch windows since we will not care about them
2382 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002383 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384
2385Failed:
2386 // Check injection permission once and for all.
2387 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002388 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 injectionPermission = INJECTION_PERMISSION_GRANTED;
2390 } else {
2391 injectionPermission = INJECTION_PERMISSION_DENIED;
2392 }
2393 }
2394
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002395 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2396 return injectionResult;
2397 }
2398
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002400 if (!wrongDevice) {
2401 if (switchedDevice) {
2402 if (DEBUG_FOCUS) {
2403 ALOGD("Conflicting pointer actions: Switched to a different device.");
2404 }
2405 *outConflictingPointerActions = true;
2406 }
2407
2408 if (isHoverAction) {
2409 // Started hovering, therefore no longer down.
2410 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002411 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002412 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2413 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 *outConflictingPointerActions = true;
2416 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002417 tempTouchState.reset();
2418 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2419 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2420 tempTouchState.deviceId = entry.deviceId;
2421 tempTouchState.source = entry.source;
2422 tempTouchState.displayId = displayId;
2423 }
2424 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2425 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2426 // All pointers up or canceled.
2427 tempTouchState.reset();
2428 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2429 // First pointer went down.
2430 if (oldState && oldState->down) {
2431 if (DEBUG_FOCUS) {
2432 ALOGD("Conflicting pointer actions: Down received while already down.");
2433 }
2434 *outConflictingPointerActions = true;
2435 }
2436 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2437 // One pointer went up.
2438 if (isSplit) {
2439 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2440 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002442 for (size_t i = 0; i < tempTouchState.windows.size();) {
2443 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2444 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2445 touchedWindow.pointerIds.clearBit(pointerId);
2446 if (touchedWindow.pointerIds.isEmpty()) {
2447 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2448 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002451 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002453 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002454 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002455
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002456 // Save changes unless the action was scroll in which case the temporary touch
2457 // state was only valid for this one action.
2458 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2459 if (tempTouchState.displayId >= 0) {
2460 mTouchStatesByDisplay[displayId] = tempTouchState;
2461 } else {
2462 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002466 // Update hover state.
2467 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 }
2469
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 return injectionResult;
2471}
2472
arthurhung6d4bed92021-03-17 11:59:33 +08002473void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002474 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2475 // have an explicit reason to support it.
2476 constexpr bool isStylus = false;
2477
chaviw98318de2021-05-19 16:45:23 -05002478 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002479 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002480 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002481 if (dropWindow) {
2482 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002483 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002484 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002485 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002486 }
2487 mDragState.reset();
2488}
2489
2490void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2491 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002492 return;
2493 }
2494
arthurhung6d4bed92021-03-17 11:59:33 +08002495 if (!mDragState->isStartDrag) {
2496 mDragState->isStartDrag = true;
2497 mDragState->isStylusButtonDownAtStart =
2498 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2499 }
2500
arthurhungb89ccb02020-12-30 16:19:01 +08002501 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2502 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2503 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2504 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002505 // Handle the special case : stylus button no longer pressed.
2506 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2507 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2508 finishDragAndDrop(entry.displayId, x, y);
2509 return;
2510 }
2511
Prabir Pradhand65552b2021-10-07 11:23:50 -07002512 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2513 // we have an explicit reason to support it.
2514 constexpr bool isStylus = false;
2515
chaviw98318de2021-05-19 16:45:23 -05002516 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002517 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002518 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002519 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002520 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2521 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2522 if (mDragState->dragHoverWindowHandle != nullptr) {
2523 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2524 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002525 }
arthurhung6d4bed92021-03-17 11:59:33 +08002526 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002527 }
2528 // enqueue drag location if needed.
2529 if (hoverWindowHandle != nullptr) {
2530 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2531 }
arthurhung6d4bed92021-03-17 11:59:33 +08002532 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2533 finishDragAndDrop(entry.displayId, x, y);
2534 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002535 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002536 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002537 }
2538}
2539
chaviw98318de2021-05-19 16:45:23 -05002540void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 int32_t targetFlags, BitSet32 pointerIds,
2542 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002543 std::vector<InputTarget>::iterator it =
2544 std::find_if(inputTargets.begin(), inputTargets.end(),
2545 [&windowHandle](const InputTarget& inputTarget) {
2546 return inputTarget.inputChannel->getConnectionToken() ==
2547 windowHandle->getToken();
2548 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002549
chaviw98318de2021-05-19 16:45:23 -05002550 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002551
2552 if (it == inputTargets.end()) {
2553 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002554 std::shared_ptr<InputChannel> inputChannel =
2555 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002556 if (inputChannel == nullptr) {
2557 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2558 return;
2559 }
2560 inputTarget.inputChannel = inputChannel;
2561 inputTarget.flags = targetFlags;
2562 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002563 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2564 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002565 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002566 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002567 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002568 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002569 inputTargets.push_back(inputTarget);
2570 it = inputTargets.end() - 1;
2571 }
2572
2573 ALOG_ASSERT(it->flags == targetFlags);
2574 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2575
chaviw1ff3d1e2020-07-01 15:53:47 -07002576 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577}
2578
Michael Wright3dd60e22019-03-27 22:06:44 +00002579void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002580 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002581 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2582 mGlobalMonitorsByDisplay.find(displayId);
2583
2584 if (it != mGlobalMonitorsByDisplay.end()) {
2585 const std::vector<Monitor>& monitors = it->second;
2586 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002587 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590}
2591
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002592void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002593 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002594 InputTarget target;
2595 target.inputChannel = monitor.inputChannel;
2596 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002597 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002598 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002599 const auto& displayTransform = it->second.transform;
2600 target.displayTransform = displayTransform;
2601 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002602 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002603 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002604 inputTargets.push_back(target);
2605}
2606
chaviw98318de2021-05-19 16:45:23 -05002607bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 const InjectionState* injectionState) {
2609 if (injectionState &&
2610 (windowHandle == nullptr ||
2611 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2612 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002613 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002615 "owned by uid %d",
2616 injectionState->injectorPid, injectionState->injectorUid,
2617 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 } else {
2619 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002620 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
2622 return false;
2623 }
2624 return true;
2625}
2626
Robert Carrc9bf1d32020-04-13 17:21:08 -07002627/**
2628 * Indicate whether one window handle should be considered as obscuring
2629 * another window handle. We only check a few preconditions. Actually
2630 * checking the bounds is left to the caller.
2631 */
chaviw98318de2021-05-19 16:45:23 -05002632static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2633 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002634 // Compare by token so cloned layers aren't counted
2635 if (haveSameToken(windowHandle, otherHandle)) {
2636 return false;
2637 }
2638 auto info = windowHandle->getInfo();
2639 auto otherInfo = otherHandle->getInfo();
2640 if (!otherInfo->visible) {
2641 return false;
chaviw98318de2021-05-19 16:45:23 -05002642 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002643 // Those act as if they were invisible, so we don't need to flag them.
2644 // We do want to potentially flag touchable windows even if they have 0
2645 // opacity, since they can consume touches and alter the effects of the
2646 // user interaction (eg. apps that rely on
2647 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2648 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2649 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002650 } else if (info->ownerUid == otherInfo->ownerUid) {
2651 // If ownerUid is the same we don't generate occlusion events as there
2652 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002653 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002654 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002655 return false;
2656 } else if (otherInfo->displayId != info->displayId) {
2657 return false;
2658 }
2659 return true;
2660}
2661
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002662/**
2663 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2664 * untrusted, one should check:
2665 *
2666 * 1. If result.hasBlockingOcclusion is true.
2667 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2668 * BLOCK_UNTRUSTED.
2669 *
2670 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2671 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2672 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2673 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2674 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2675 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2676 *
2677 * If neither of those is true, then it means the touch can be allowed.
2678 */
2679InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002680 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2681 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002682 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002683 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002684 TouchOcclusionInfo info;
2685 info.hasBlockingOcclusion = false;
2686 info.obscuringOpacity = 0;
2687 info.obscuringUid = -1;
2688 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002689 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002690 if (windowHandle == otherHandle) {
2691 break; // All future windows are below us. Exit early.
2692 }
chaviw98318de2021-05-19 16:45:23 -05002693 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002694 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2695 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002696 if (DEBUG_TOUCH_OCCLUSION) {
2697 info.debugInfo.push_back(
2698 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2699 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002700 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2701 // we perform the checks below to see if the touch can be propagated or not based on the
2702 // window's touch occlusion mode
2703 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2704 info.hasBlockingOcclusion = true;
2705 info.obscuringUid = otherInfo->ownerUid;
2706 info.obscuringPackage = otherInfo->packageName;
2707 break;
2708 }
2709 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2710 uint32_t uid = otherInfo->ownerUid;
2711 float opacity =
2712 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2713 // Given windows A and B:
2714 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2715 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2716 opacityByUid[uid] = opacity;
2717 if (opacity > info.obscuringOpacity) {
2718 info.obscuringOpacity = opacity;
2719 info.obscuringUid = uid;
2720 info.obscuringPackage = otherInfo->packageName;
2721 }
2722 }
2723 }
2724 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002725 if (DEBUG_TOUCH_OCCLUSION) {
2726 info.debugInfo.push_back(
2727 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2728 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002729 return info;
2730}
2731
chaviw98318de2021-05-19 16:45:23 -05002732std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002733 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002734 return StringPrintf(INDENT2
2735 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2736 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2737 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2738 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002739 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002740 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002741 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2742 info->frameTop, info->frameRight, info->frameBottom,
2743 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002744 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2745 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2746 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002747}
2748
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002749bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2750 if (occlusionInfo.hasBlockingOcclusion) {
2751 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2752 occlusionInfo.obscuringUid);
2753 return false;
2754 }
2755 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2756 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2757 "%.2f, maximum allowed = %.2f)",
2758 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2759 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2760 return false;
2761 }
2762 return true;
2763}
2764
chaviw98318de2021-05-19 16:45:23 -05002765bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002766 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002768 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2769 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002770 if (windowHandle == otherHandle) {
2771 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 }
chaviw98318de2021-05-19 16:45:23 -05002773 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002774 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002775 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 return true;
2777 }
2778 }
2779 return false;
2780}
2781
chaviw98318de2021-05-19 16:45:23 -05002782bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002783 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002784 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2785 const WindowInfo* windowInfo = windowHandle->getInfo();
2786 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002787 if (windowHandle == otherHandle) {
2788 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002789 }
chaviw98318de2021-05-19 16:45:23 -05002790 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002792 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002793 return true;
2794 }
2795 }
2796 return false;
2797}
2798
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002799std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002800 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002801 if (applicationHandle != nullptr) {
2802 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002803 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 } else {
2805 return applicationHandle->getName();
2806 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002807 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002808 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002810 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 }
2812}
2813
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002814void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002815 if (!isUserActivityEvent(eventEntry)) {
2816 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002817 return;
2818 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002819 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002820 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002821 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002822 const WindowInfo* info = focusedWindowHandle->getInfo();
2823 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002824 if (DEBUG_DISPATCH_CYCLE) {
2825 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 return;
2828 }
2829 }
2830
2831 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002832 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002833 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002834 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2835 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 return;
2837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002839 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 eventType = USER_ACTIVITY_EVENT_TOUCH;
2841 }
2842 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002844 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002845 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2846 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 return;
2848 }
2849 eventType = USER_ACTIVITY_EVENT_BUTTON;
2850 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002852 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002853 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002854 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002855 break;
2856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 }
2858
Prabir Pradhancef936d2021-07-21 16:17:52 +00002859 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2860 REQUIRES(mLock) {
2861 scoped_unlock unlock(mLock);
2862 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2863 };
2864 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865}
2866
2867void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002868 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002869 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002870 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002871 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002872 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002873 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002874 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002875 ATRACE_NAME(message.c_str());
2876 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002877 if (DEBUG_DISPATCH_CYCLE) {
2878 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2879 "globalScaleFactor=%f, pointerIds=0x%x %s",
2880 connection->getInputChannelName().c_str(), inputTarget.flags,
2881 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2882 inputTarget.getPointerInfoString().c_str());
2883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884
2885 // Skip this event if the connection status is not normal.
2886 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002887 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002888 if (DEBUG_DISPATCH_CYCLE) {
2889 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002890 connection->getInputChannelName().c_str(),
2891 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 return;
2894 }
2895
2896 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002897 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2898 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2899 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002900 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002902 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002903 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002904 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002905 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 if (!splitMotionEntry) {
2907 return; // split event was dropped
2908 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002909 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2910 std::string reason = std::string("reason=pointer cancel on split window");
2911 android_log_event_list(LOGTAG_INPUT_CANCEL)
2912 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2913 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002914 if (DEBUG_FOCUS) {
2915 ALOGD("channel '%s' ~ Split motion event.",
2916 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002917 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002918 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002919 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2920 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 return;
2922 }
2923 }
2924
2925 // Not splitting. Enqueue dispatch entries for the event as is.
2926 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2927}
2928
2929void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002931 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002932 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002933 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002935 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002936 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002937 ATRACE_NAME(message.c_str());
2938 }
2939
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002940 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941
2942 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002943 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002945 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002947 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002949 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002951 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002953 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955
2956 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002957 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 startDispatchCycleLocked(currentTime, connection);
2959 }
2960}
2961
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002963 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002964 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002966 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2968 connection->getInputChannelName().c_str(),
2969 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002970 ATRACE_NAME(message.c_str());
2971 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002972 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 if (!(inputTargetFlags & dispatchMode)) {
2974 return;
2975 }
2976 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2977
2978 // This is a new event.
2979 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002980 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002981 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002983 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2984 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002985 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002987 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002988 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002989 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002990 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002991 dispatchEntry->resolvedAction = keyEntry.action;
2992 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2995 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002996 if (DEBUG_DISPATCH_CYCLE) {
2997 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2998 "event",
2999 connection->getInputChannelName().c_str());
3000 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 return; // skip the inconsistent event
3002 }
3003 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003006 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003007 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003008 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3009 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3010 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3011 static_cast<int32_t>(IdGenerator::Source::OTHER);
3012 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3014 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3015 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3016 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3017 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3018 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3019 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3020 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3021 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3022 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3023 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003024 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003025 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 }
3027 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003028 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3029 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003030 if (DEBUG_DISPATCH_CYCLE) {
3031 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3032 "enter event",
3033 connection->getInputChannelName().c_str());
3034 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003035 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3036 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3042 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3043 }
3044 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3045 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3049 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003050 if (DEBUG_DISPATCH_CYCLE) {
3051 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3052 "event",
3053 connection->getInputChannelName().c_str());
3054 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 return; // skip the inconsistent event
3056 }
3057
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003058 dispatchEntry->resolvedEventId =
3059 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3060 ? mIdGenerator.nextId()
3061 : motionEntry.id;
3062 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3063 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3064 ") to MotionEvent(id=0x%" PRIx32 ").",
3065 motionEntry.id, dispatchEntry->resolvedEventId);
3066 ATRACE_NAME(message.c_str());
3067 }
3068
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003069 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3070 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3071 // Skip reporting pointer down outside focus to the policy.
3072 break;
3073 }
3074
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003075 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003076 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077
3078 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003080 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003081 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003082 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3083 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003084 break;
3085 }
Chris Yef59a2f42020-10-16 12:55:26 -07003086 case EventEntry::Type::SENSOR: {
3087 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3088 break;
3089 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003090 case EventEntry::Type::CONFIGURATION_CHANGED:
3091 case EventEntry::Type::DEVICE_RESET: {
3092 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003093 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003094 break;
3095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 }
3097
3098 // Remember that we are waiting for this dispatch to complete.
3099 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003100 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102
3103 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003104 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003105 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003106}
3107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003108/**
3109 * This function is purely for debugging. It helps us understand where the user interaction
3110 * was taking place. For example, if user is touching launcher, we will see a log that user
3111 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3112 * We will see both launcher and wallpaper in that list.
3113 * Once the interaction with a particular set of connections starts, no new logs will be printed
3114 * until the set of interacted connections changes.
3115 *
3116 * The following items are skipped, to reduce the logspam:
3117 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3118 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3119 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3120 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3121 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003122 */
3123void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3124 const std::vector<InputTarget>& targets) {
3125 // Skip ACTION_UP events, and all events other than keys and motions
3126 if (entry.type == EventEntry::Type::KEY) {
3127 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3128 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3129 return;
3130 }
3131 } else if (entry.type == EventEntry::Type::MOTION) {
3132 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3133 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3134 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3135 return;
3136 }
3137 } else {
3138 return; // Not a key or a motion
3139 }
3140
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003141 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003142 std::vector<sp<Connection>> newConnections;
3143 for (const InputTarget& target : targets) {
3144 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3145 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3146 continue; // Skip windows that receive ACTION_OUTSIDE
3147 }
3148
3149 sp<IBinder> token = target.inputChannel->getConnectionToken();
3150 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003151 if (connection == nullptr) {
3152 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003153 }
3154 newConnectionTokens.insert(std::move(token));
3155 newConnections.emplace_back(connection);
3156 }
3157 if (newConnectionTokens == mInteractionConnectionTokens) {
3158 return; // no change
3159 }
3160 mInteractionConnectionTokens = newConnectionTokens;
3161
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003162 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003163 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003164 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003165 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003166 std::string message = "Interaction with: " + targetList;
3167 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003168 message += "<none>";
3169 }
3170 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3171}
3172
chaviwfd6d3512019-03-25 13:23:49 -07003173void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003174 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003175 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003176 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3177 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003178 return;
3179 }
3180
Vishnu Nairc519ff72021-01-21 08:23:08 -08003181 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003182 if (focusedToken == token) {
3183 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003184 return;
3185 }
3186
Prabir Pradhancef936d2021-07-21 16:17:52 +00003187 auto command = [this, token]() REQUIRES(mLock) {
3188 scoped_unlock unlock(mLock);
3189 mPolicy->onPointerDownOutsideFocus(token);
3190 };
3191 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192}
3193
3194void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003196 if (ATRACE_ENABLED()) {
3197 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003199 ATRACE_NAME(message.c_str());
3200 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003201 if (DEBUG_DISPATCH_CYCLE) {
3202 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003205 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003206 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003208 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003209 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003210 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211
3212 // Publish the event.
3213 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003214 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3215 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003216 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003217 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3218 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003221 status = connection->inputPublisher
3222 .publishKeyEvent(dispatchEntry->seq,
3223 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3224 keyEntry.source, keyEntry.displayId,
3225 std::move(hmac), dispatchEntry->resolvedAction,
3226 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3227 keyEntry.scanCode, keyEntry.metaState,
3228 keyEntry.repeatCount, keyEntry.downTime,
3229 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003230 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003233 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238
chaviw82357092020-01-28 13:13:06 -08003239 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3242 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003243 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003244 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3245 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003246 // Don't apply window scale here since we don't want scale to affect raw
3247 // coordinates. The scale will be sent back to the client and applied
3248 // later when requesting relative coordinates.
3249 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3250 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 }
3252 usingCoords = scaledCoords;
3253 }
3254 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255 // We don't want the dispatch target to know.
3256 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 scaledCoords[i].clear();
3259 }
3260 usingCoords = scaledCoords;
3261 }
3262 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003264 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265
3266 // Publish the motion event.
3267 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003268 .publishMotionEvent(dispatchEntry->seq,
3269 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003270 motionEntry.deviceId, motionEntry.source,
3271 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003272 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003273 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003275 motionEntry.edgeFlags, motionEntry.metaState,
3276 motionEntry.buttonState,
3277 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003278 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003279 motionEntry.xPrecision, motionEntry.yPrecision,
3280 motionEntry.xCursorPosition,
3281 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003282 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003283 motionEntry.downTime, motionEntry.eventTime,
3284 motionEntry.pointerCount,
3285 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003286 break;
3287 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003288
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003289 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003291 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003292 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003293 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003294 break;
3295 }
3296
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003297 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3298 const TouchModeEntry& touchModeEntry =
3299 static_cast<const TouchModeEntry&>(eventEntry);
3300 status = connection->inputPublisher
3301 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3302 touchModeEntry.inTouchMode);
3303
3304 break;
3305 }
3306
Prabir Pradhan99987712020-11-10 18:43:05 -08003307 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3308 const auto& captureEntry =
3309 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3310 status = connection->inputPublisher
3311 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003312 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003313 break;
3314 }
3315
arthurhungb89ccb02020-12-30 16:19:01 +08003316 case EventEntry::Type::DRAG: {
3317 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3318 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3319 dragEntry.id, dragEntry.x,
3320 dragEntry.y,
3321 dragEntry.isExiting);
3322 break;
3323 }
3324
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003325 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003326 case EventEntry::Type::DEVICE_RESET:
3327 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003328 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003329 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
3333
3334 // Check the result.
3335 if (status) {
3336 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003337 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 "This is unexpected because the wait queue is empty, so the pipe "
3340 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003341 "event to it, status=%s(%d)",
3342 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3343 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3345 } else {
3346 // Pipe is full and we are waiting for the app to finish process some events
3347 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003348 if (DEBUG_DISPATCH_CYCLE) {
3349 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3350 "waiting for the application to catch up",
3351 connection->getInputChannelName().c_str());
3352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354 } else {
3355 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003356 "status=%s(%d)",
3357 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3358 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3360 }
3361 return;
3362 }
3363
3364 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003365 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3366 connection->outboundQueue.end(),
3367 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003368 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003369 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003370 if (connection->responsive) {
3371 mAnrTracker.insert(dispatchEntry->timeoutTime,
3372 connection->inputChannel->getConnectionToken());
3373 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003374 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
3376}
3377
chaviw09c8d2d2020-08-24 15:48:26 -07003378std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3379 size_t size;
3380 switch (event.type) {
3381 case VerifiedInputEvent::Type::KEY: {
3382 size = sizeof(VerifiedKeyEvent);
3383 break;
3384 }
3385 case VerifiedInputEvent::Type::MOTION: {
3386 size = sizeof(VerifiedMotionEvent);
3387 break;
3388 }
3389 }
3390 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3391 return mHmacKeyManager.sign(start, size);
3392}
3393
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003394const std::array<uint8_t, 32> InputDispatcher::getSignature(
3395 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003396 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3397 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003398 // Only sign events up and down events as the purely move events
3399 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003400 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003401 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003402
3403 VerifiedMotionEvent verifiedEvent =
3404 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3405 verifiedEvent.actionMasked = actionMasked;
3406 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3407 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003408}
3409
3410const std::array<uint8_t, 32> InputDispatcher::getSignature(
3411 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3412 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3413 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3414 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003415 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003416}
3417
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003419 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003420 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003421 if (DEBUG_DISPATCH_CYCLE) {
3422 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3423 connection->getInputChannelName().c_str(), seq, toString(handled));
3424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003426 if (connection->status == Connection::Status::BROKEN ||
3427 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 return;
3429 }
3430
3431 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003432 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3433 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3434 };
3435 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436}
3437
3438void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439 const sp<Connection>& connection,
3440 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003441 if (DEBUG_DISPATCH_CYCLE) {
3442 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3443 connection->getInputChannelName().c_str(), toString(notify));
3444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445
3446 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003447 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003448 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003449 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003450 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
3452 // The connection appears to be unrecoverably broken.
3453 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003454 if (connection->status == Connection::Status::NORMAL) {
3455 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456
3457 if (notify) {
3458 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003459 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3460 connection->getInputChannelName().c_str());
3461
3462 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003463 scoped_unlock unlock(mLock);
3464 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3465 };
3466 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
3468 }
3469}
3470
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003471void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3472 while (!queue.empty()) {
3473 DispatchEntry* dispatchEntry = queue.front();
3474 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003475 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 }
3477}
3478
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003479void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003481 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
3483 delete dispatchEntry;
3484}
3485
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003486int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3487 std::scoped_lock _l(mLock);
3488 sp<Connection> connection = getConnectionLocked(connectionToken);
3489 if (connection == nullptr) {
3490 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3491 connectionToken.get(), events);
3492 return 0; // remove the callback
3493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003495 bool notify;
3496 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3497 if (!(events & ALOOPER_EVENT_INPUT)) {
3498 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3499 "events=0x%x",
3500 connection->getInputChannelName().c_str(), events);
3501 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
3503
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003504 nsecs_t currentTime = now();
3505 bool gotOne = false;
3506 status_t status = OK;
3507 for (;;) {
3508 Result<InputPublisher::ConsumerResponse> result =
3509 connection->inputPublisher.receiveConsumerResponse();
3510 if (!result.ok()) {
3511 status = result.error().code();
3512 break;
3513 }
3514
3515 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3516 const InputPublisher::Finished& finish =
3517 std::get<InputPublisher::Finished>(*result);
3518 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3519 finish.consumeTime);
3520 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003521 if (shouldReportMetricsForConnection(*connection)) {
3522 const InputPublisher::Timeline& timeline =
3523 std::get<InputPublisher::Timeline>(*result);
3524 mLatencyTracker
3525 .trackGraphicsLatency(timeline.inputEventId,
3526 connection->inputChannel->getConnectionToken(),
3527 std::move(timeline.graphicsTimeline));
3528 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003529 }
3530 gotOne = true;
3531 }
3532 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003533 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003534 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 return 1;
3536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 }
3538
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003539 notify = status != DEAD_OBJECT || !connection->monitor;
3540 if (notify) {
3541 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3542 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3543 status);
3544 }
3545 } else {
3546 // Monitor channels are never explicitly unregistered.
3547 // We do it automatically when the remote endpoint is closed so don't warn about them.
3548 const bool stillHaveWindowHandle =
3549 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3550 notify = !connection->monitor && stillHaveWindowHandle;
3551 if (notify) {
3552 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3553 connection->getInputChannelName().c_str(), events);
3554 }
3555 }
3556
3557 // Remove the channel.
3558 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3559 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560}
3561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003562void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003564 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003565 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567}
3568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003569void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003570 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003571 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3572 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3573}
3574
3575void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3576 const CancelationOptions& options,
3577 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3578 for (const auto& it : monitorsByDisplay) {
3579 const std::vector<Monitor>& monitors = it.second;
3580 for (const Monitor& monitor : monitors) {
3581 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003582 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003583 }
3584}
3585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003587 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003588 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003589 if (connection == nullptr) {
3590 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003592
3593 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594}
3595
3596void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3597 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003598 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 return;
3600 }
3601
3602 nsecs_t currentTime = now();
3603
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003604 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003605 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003607 if (cancelationEvents.empty()) {
3608 return;
3609 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003610 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3611 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3612 "with reality: %s, mode=%d.",
3613 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3614 options.mode);
3615 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003616
Arthur Hungb3307ee2021-10-14 10:57:37 +00003617 std::string reason = std::string("reason=").append(options.reason);
3618 android_log_event_list(LOGTAG_INPUT_CANCEL)
3619 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3620
Svet Ganov5d3bc372020-01-26 23:11:07 -08003621 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003622 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3624 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003625 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003626 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003627 target.globalScaleFactor = windowInfo->globalScaleFactor;
3628 }
3629 target.inputChannel = connection->inputChannel;
3630 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3631
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003632 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003633 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003634 switch (cancelationEventEntry->type) {
3635 case EventEntry::Type::KEY: {
3636 logOutboundKeyDetails("cancel - ",
3637 static_cast<const KeyEntry&>(*cancelationEventEntry));
3638 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003640 case EventEntry::Type::MOTION: {
3641 logOutboundMotionDetails("cancel - ",
3642 static_cast<const MotionEntry&>(*cancelationEventEntry));
3643 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003645 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003646 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003647 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3648 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003649 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003650 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003651 break;
3652 }
3653 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003654 case EventEntry::Type::DEVICE_RESET:
3655 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003656 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003657 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003658 break;
3659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3663 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003665
3666 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667}
3668
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3670 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003671 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003672 return;
3673 }
3674
3675 nsecs_t currentTime = now();
3676
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003677 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003678 connection->inputState.synthesizePointerDownEvents(currentTime);
3679
3680 if (downEvents.empty()) {
3681 return;
3682 }
3683
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003684 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003685 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3686 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003687 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003688
3689 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003690 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003691 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3692 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003693 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003694 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003695 target.globalScaleFactor = windowInfo->globalScaleFactor;
3696 }
3697 target.inputChannel = connection->inputChannel;
3698 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3699
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003700 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003701 switch (downEventEntry->type) {
3702 case EventEntry::Type::MOTION: {
3703 logOutboundMotionDetails("down - ",
3704 static_cast<const MotionEntry&>(*downEventEntry));
3705 break;
3706 }
3707
3708 case EventEntry::Type::KEY:
3709 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003710 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003711 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003712 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003713 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003714 case EventEntry::Type::SENSOR:
3715 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003717 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003718 break;
3719 }
3720 }
3721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003722 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3723 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003724 }
3725
3726 startDispatchCycleLocked(currentTime, connection);
3727}
3728
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003729std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3730 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 ALOG_ASSERT(pointerIds.value != 0);
3732
3733 uint32_t splitPointerIndexMap[MAX_POINTERS];
3734 PointerProperties splitPointerProperties[MAX_POINTERS];
3735 PointerCoords splitPointerCoords[MAX_POINTERS];
3736
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003737 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 uint32_t splitPointerCount = 0;
3739
3740 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003743 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 uint32_t pointerId = uint32_t(pointerProperties.id);
3745 if (pointerIds.hasBit(pointerId)) {
3746 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3747 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3748 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003749 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 splitPointerCount += 1;
3751 }
3752 }
3753
3754 if (splitPointerCount != pointerIds.count()) {
3755 // This is bad. We are missing some of the pointers that we expected to deliver.
3756 // Most likely this indicates that we received an ACTION_MOVE events that has
3757 // different pointer ids than we expected based on the previous ACTION_DOWN
3758 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3759 // in this way.
3760 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003761 "we expected there to be %d pointers. This probably means we received "
3762 "a broken sequence of pointer ids from the input device.",
3763 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003764 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
3766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003767 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003769 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3770 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3772 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003773 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 uint32_t pointerId = uint32_t(pointerProperties.id);
3775 if (pointerIds.hasBit(pointerId)) {
3776 if (pointerIds.count() == 1) {
3777 // The first/last pointer went down/up.
3778 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003780 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3781 ? AMOTION_EVENT_ACTION_CANCEL
3782 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 } else {
3784 // A secondary pointer went down/up.
3785 uint32_t splitPointerIndex = 0;
3786 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3787 splitPointerIndex += 1;
3788 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003789 action = maskedAction |
3790 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 }
3792 } else {
3793 // An unrelated pointer changed.
3794 action = AMOTION_EVENT_ACTION_MOVE;
3795 }
3796 }
3797
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003798 int32_t newId = mIdGenerator.nextId();
3799 if (ATRACE_ENABLED()) {
3800 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3801 ") to MotionEvent(id=0x%" PRIx32 ").",
3802 originalMotionEntry.id, newId);
3803 ATRACE_NAME(message.c_str());
3804 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003805 std::unique_ptr<MotionEntry> splitMotionEntry =
3806 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3807 originalMotionEntry.deviceId, originalMotionEntry.source,
3808 originalMotionEntry.displayId,
3809 originalMotionEntry.policyFlags, action,
3810 originalMotionEntry.actionButton,
3811 originalMotionEntry.flags, originalMotionEntry.metaState,
3812 originalMotionEntry.buttonState,
3813 originalMotionEntry.classification,
3814 originalMotionEntry.edgeFlags,
3815 originalMotionEntry.xPrecision,
3816 originalMotionEntry.yPrecision,
3817 originalMotionEntry.xCursorPosition,
3818 originalMotionEntry.yCursorPosition,
3819 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003820 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003822 if (originalMotionEntry.injectionState) {
3823 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 splitMotionEntry->injectionState->refCount += 1;
3825 }
3826
3827 return splitMotionEntry;
3828}
3829
3830void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003831 if (DEBUG_INBOUND_EVENT_DETAILS) {
3832 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834
Antonio Kantekf16f2832021-09-28 04:39:20 +00003835 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003837 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003839 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3840 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3841 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 } // release lock
3843
3844 if (needWake) {
3845 mLooper->wake();
3846 }
3847}
3848
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003849/**
3850 * If one of the meta shortcuts is detected, process them here:
3851 * Meta + Backspace -> generate BACK
3852 * Meta + Enter -> generate HOME
3853 * This will potentially overwrite keyCode and metaState.
3854 */
3855void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003856 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003857 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3858 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3859 if (keyCode == AKEYCODE_DEL) {
3860 newKeyCode = AKEYCODE_BACK;
3861 } else if (keyCode == AKEYCODE_ENTER) {
3862 newKeyCode = AKEYCODE_HOME;
3863 }
3864 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003865 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003866 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003867 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003868 keyCode = newKeyCode;
3869 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3870 }
3871 } else if (action == AKEY_EVENT_ACTION_UP) {
3872 // In order to maintain a consistent stream of up and down events, check to see if the key
3873 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3874 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003875 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003876 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003877 auto replacementIt = mReplacedKeys.find(replacement);
3878 if (replacementIt != mReplacedKeys.end()) {
3879 keyCode = replacementIt->second;
3880 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003881 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3882 }
3883 }
3884}
3885
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003887 if (DEBUG_INBOUND_EVENT_DETAILS) {
3888 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3889 "policyFlags=0x%x, action=0x%x, "
3890 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3891 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3892 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3893 args->downTime);
3894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 if (!validateKeyEvent(args->action)) {
3896 return;
3897 }
3898
3899 uint32_t policyFlags = args->policyFlags;
3900 int32_t flags = args->flags;
3901 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003902 // InputDispatcher tracks and generates key repeats on behalf of
3903 // whatever notifies it, so repeatCount should always be set to 0
3904 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3906 policyFlags |= POLICY_FLAG_VIRTUAL;
3907 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 if (policyFlags & POLICY_FLAG_FUNCTION) {
3910 metaState |= AMETA_FUNCTION_ON;
3911 }
3912
3913 policyFlags |= POLICY_FLAG_TRUSTED;
3914
Michael Wright78f24442014-08-06 15:55:28 -07003915 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003916 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003917
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003919 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003920 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3921 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922
Michael Wright2b3c3302018-03-02 17:19:13 +00003923 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003925 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3926 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003927 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929
Antonio Kantekf16f2832021-09-28 04:39:20 +00003930 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 { // acquire lock
3932 mLock.lock();
3933
3934 if (shouldSendKeyToInputFilterLocked(args)) {
3935 mLock.unlock();
3936
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003937 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3939 return; // event was consumed by the filter
3940 }
3941
3942 mLock.lock();
3943 }
3944
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003945 std::unique_ptr<KeyEntry> newEntry =
3946 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3947 args->displayId, policyFlags, args->action, flags,
3948 keyCode, args->scanCode, metaState, repeatCount,
3949 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003951 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 mLock.unlock();
3953 } // release lock
3954
3955 if (needWake) {
3956 mLooper->wake();
3957 }
3958}
3959
3960bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3961 return mInputFilterEnabled;
3962}
3963
3964void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003965 if (DEBUG_INBOUND_EVENT_DETAILS) {
3966 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3967 "displayId=%" PRId32 ", policyFlags=0x%x, "
3968 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3969 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3970 "yCursorPosition=%f, downTime=%" PRId64,
3971 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3972 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3973 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3974 args->xCursorPosition, args->yCursorPosition, args->downTime);
3975 for (uint32_t i = 0; i < args->pointerCount; i++) {
3976 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3977 "x=%f, y=%f, pressure=%f, size=%f, "
3978 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3979 "orientation=%f",
3980 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3981 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3982 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3983 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3984 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3985 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3986 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3987 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3988 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3989 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003992 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3993 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 return;
3995 }
3996
3997 uint32_t policyFlags = args->policyFlags;
3998 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003999
4000 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004001 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004002 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4003 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006
Antonio Kantekf16f2832021-09-28 04:39:20 +00004007 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 { // acquire lock
4009 mLock.lock();
4010
4011 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004012 ui::Transform displayTransform;
4013 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4014 displayTransform = it->second.transform;
4015 }
4016
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 mLock.unlock();
4018
4019 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004020 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4021 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004022 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004023 displayTransform, args->xPrecision, args->yPrecision,
4024 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004025 args->downTime, args->eventTime, args->pointerCount,
4026 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027
4028 policyFlags |= POLICY_FLAG_FILTERED;
4029 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4030 return; // event was consumed by the filter
4031 }
4032
4033 mLock.lock();
4034 }
4035
4036 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004037 std::unique_ptr<MotionEntry> newEntry =
4038 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4039 args->source, args->displayId, policyFlags,
4040 args->action, args->actionButton, args->flags,
4041 args->metaState, args->buttonState,
4042 args->classification, args->edgeFlags,
4043 args->xPrecision, args->yPrecision,
4044 args->xCursorPosition, args->yCursorPosition,
4045 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004046 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004048 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4049 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4050 !mInputFilterEnabled) {
4051 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4052 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4053 }
4054
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004055 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 mLock.unlock();
4057 } // release lock
4058
4059 if (needWake) {
4060 mLooper->wake();
4061 }
4062}
4063
Chris Yef59a2f42020-10-16 12:55:26 -07004064void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004065 if (DEBUG_INBOUND_EVENT_DETAILS) {
4066 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4067 " sensorType=%s",
4068 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004069 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004070 }
Chris Yef59a2f42020-10-16 12:55:26 -07004071
Antonio Kantekf16f2832021-09-28 04:39:20 +00004072 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004073 { // acquire lock
4074 mLock.lock();
4075
4076 // Just enqueue a new sensor event.
4077 std::unique_ptr<SensorEntry> newEntry =
4078 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4079 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4080 args->sensorType, args->accuracy,
4081 args->accuracyChanged, args->values);
4082
4083 needWake = enqueueInboundEventLocked(std::move(newEntry));
4084 mLock.unlock();
4085 } // release lock
4086
4087 if (needWake) {
4088 mLooper->wake();
4089 }
4090}
4091
Chris Yefb552902021-02-03 17:18:37 -08004092void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 if (DEBUG_INBOUND_EVENT_DETAILS) {
4094 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4095 args->deviceId, args->isOn);
4096 }
Chris Yefb552902021-02-03 17:18:37 -08004097 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4098}
4099
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004101 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102}
4103
4104void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004105 if (DEBUG_INBOUND_EVENT_DETAILS) {
4106 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4107 "switchMask=0x%08x",
4108 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
4111 uint32_t policyFlags = args->policyFlags;
4112 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114}
4115
4116void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 if (DEBUG_INBOUND_EVENT_DETAILS) {
4118 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4119 args->deviceId);
4120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121
Antonio Kantekf16f2832021-09-28 04:39:20 +00004122 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004124 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004126 std::unique_ptr<DeviceResetEntry> newEntry =
4127 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4128 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 } // release lock
4130
4131 if (needWake) {
4132 mLooper->wake();
4133 }
4134}
4135
Prabir Pradhan7e186182020-11-10 13:56:45 -08004136void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004137 if (DEBUG_INBOUND_EVENT_DETAILS) {
4138 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004139 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004140 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004141
Antonio Kantekf16f2832021-09-28 04:39:20 +00004142 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004143 { // acquire lock
4144 std::scoped_lock _l(mLock);
4145 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004146 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004147 needWake = enqueueInboundEventLocked(std::move(entry));
4148 } // release lock
4149
4150 if (needWake) {
4151 mLooper->wake();
4152 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004153}
4154
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004155InputEventInjectionResult InputDispatcher::injectInputEvent(
4156 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4157 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004158 if (DEBUG_INBOUND_EVENT_DETAILS) {
4159 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4160 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4161 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4162 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004163 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
4165 policyFlags |= POLICY_FLAG_INJECTED;
4166 if (hasInjectionPermission(injectorPid, injectorUid)) {
4167 policyFlags |= POLICY_FLAG_TRUSTED;
4168 }
4169
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004170 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004171 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4172 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4173 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4174 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4175 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004177 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004179 }
4180
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004184 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4185 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004190 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004191 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4192 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4193 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004194 int32_t keyCode = incomingKey.getKeyCode();
4195 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004196 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004198 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004200 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4201 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4202 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4205 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004206 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207
4208 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4209 android::base::Timer t;
4210 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4211 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4212 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4213 std::to_string(t.duration().count()).c_str());
4214 }
4215 }
4216
4217 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004218 std::unique_ptr<KeyEntry> injectedEntry =
4219 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004221 incomingKey.getDisplayId(), policyFlags, action,
4222 flags, keyCode, incomingKey.getScanCode(), metaState,
4223 incomingKey.getRepeatCount(),
4224 incomingKey.getDownTime());
4225 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004231 const int32_t action = motionEvent.getAction();
4232 const bool isPointerEvent =
4233 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4234 // If a pointer event has no displayId specified, inject it to the default display.
4235 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4236 ? ADISPLAY_ID_DEFAULT
4237 : event->getDisplayId();
4238 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004240 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 }
4245
4246 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 android::base::Timer t;
4249 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4250 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4251 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4252 std::to_string(t.duration().count()).c_str());
4253 }
4254 }
4255
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004256 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4257 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4258 }
4259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004261 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4262 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004264 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4265 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004266 displayId, policyFlags, action, actionButton,
4267 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004268 motionEvent.getButtonState(),
4269 motionEvent.getClassification(),
4270 motionEvent.getEdgeFlags(),
4271 motionEvent.getXPrecision(),
4272 motionEvent.getYPrecision(),
4273 motionEvent.getRawXCursorPosition(),
4274 motionEvent.getRawYCursorPosition(),
4275 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004276 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004277 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 sampleEventTimes += 1;
4281 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4284 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004285 displayId, policyFlags, action, actionButton,
4286 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 motionEvent.getButtonState(),
4288 motionEvent.getClassification(),
4289 motionEvent.getEdgeFlags(),
4290 motionEvent.getXPrecision(),
4291 motionEvent.getYPrecision(),
4292 motionEvent.getRawXCursorPosition(),
4293 motionEvent.getRawYCursorPosition(),
4294 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004296 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004297 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4298 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 }
4301 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004305 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308
4309 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 injectionState->injectionIsAsync = true;
4312 }
4313
4314 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004315 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
4317 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004318 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004320 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322
4323 mLock.unlock();
4324
4325 if (needWake) {
4326 mLooper->wake();
4327 }
4328
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004331 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 if (syncMode == InputEventInjectionSync::NONE) {
4334 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 } else {
4336 for (;;) {
4337 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004338 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 break;
4340 }
4341
4342 nsecs_t remainingTimeout = endTime - now();
4343 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004344 if (DEBUG_INJECTION) {
4345 ALOGD("injectInputEvent - Timed out waiting for injection result "
4346 "to become available.");
4347 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004348 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 break;
4350 }
4351
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004352 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
4354
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4356 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 if (DEBUG_INJECTION) {
4359 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4360 injectionState->pendingForegroundDispatches);
4361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 nsecs_t remainingTimeout = endTime - now();
4363 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004364 if (DEBUG_INJECTION) {
4365 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4366 "dispatches to finish.");
4367 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 break;
4370 }
4371
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004372 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374 }
4375 }
4376
4377 injectionState->release();
4378 } // release lock
4379
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004380 if (DEBUG_INJECTION) {
4381 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4382 injectionResult, injectorPid, injectorUid);
4383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384
4385 return injectionResult;
4386}
4387
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004388std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004389 std::array<uint8_t, 32> calculatedHmac;
4390 std::unique_ptr<VerifiedInputEvent> result;
4391 switch (event.getType()) {
4392 case AINPUT_EVENT_TYPE_KEY: {
4393 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4394 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4395 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004396 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004397 break;
4398 }
4399 case AINPUT_EVENT_TYPE_MOTION: {
4400 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4401 VerifiedMotionEvent verifiedMotionEvent =
4402 verifiedMotionEventFromMotionEvent(motionEvent);
4403 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004404 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004405 break;
4406 }
4407 default: {
4408 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4409 return nullptr;
4410 }
4411 }
4412 if (calculatedHmac == INVALID_HMAC) {
4413 return nullptr;
4414 }
4415 if (calculatedHmac != event.getHmac()) {
4416 return nullptr;
4417 }
4418 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004419}
4420
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 return injectorUid == 0 ||
4423 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424}
4425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004428 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 if (DEBUG_INJECTION) {
4431 ALOGD("Setting input event injection result to %d. "
4432 "injectorPid=%d, injectorUid=%d",
4433 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 // Log the outcome since the injector did not wait for the injection result.
4438 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004439 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 ALOGV("Asynchronous input event injection succeeded.");
4441 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 ALOGW("Asynchronous input event injection failed.");
4444 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004445 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004446 ALOGW("Asynchronous input event injection permission denied.");
4447 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 ALOGW("Asynchronous input event injection timed out.");
4450 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 case InputEventInjectionResult::PENDING:
4452 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4453 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 }
4455 }
4456
4457 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004458 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460}
4461
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004462void InputDispatcher::transformMotionEntryForInjectionLocked(
4463 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004464 // Input injection works in the logical display coordinate space, but the input pipeline works
4465 // display space, so we need to transform the injected events accordingly.
4466 const auto it = mDisplayInfos.find(entry.displayId);
4467 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004468 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004469
4470 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4471 PointerCoords& pc = entry.pointerCoords[i];
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004472 // Make a copy of the injected coords. We cannot change them in place because some of them
4473 // are interdependent (for example, X coordinate might depend on the Y coordinate).
4474 PointerCoords injectedCoords = entry.pointerCoords[i];
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004475
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004476 BitSet64 bits(injectedCoords.bits);
4477 while (!bits.isEmpty()) {
4478 const auto axis = static_cast<int32_t>(bits.clearFirstMarkedBit());
4479 const float value =
4480 MotionEvent::calculateTransformedAxisValue(axis, entry.source,
4481 transformToDisplay, injectedCoords);
4482 pc.setAxisValue(axis, value);
4483 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004484 }
4485}
4486
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004487void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4488 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 if (injectionState) {
4490 injectionState->pendingForegroundDispatches += 1;
4491 }
4492}
4493
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004494void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4495 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 if (injectionState) {
4497 injectionState->pendingForegroundDispatches -= 1;
4498
4499 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004500 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 }
4502 }
4503}
4504
chaviw98318de2021-05-19 16:45:23 -05004505const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004506 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004507 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004508 auto it = mWindowHandlesByDisplay.find(displayId);
4509 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004510}
4511
chaviw98318de2021-05-19 16:45:23 -05004512sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004513 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004514 if (windowHandleToken == nullptr) {
4515 return nullptr;
4516 }
4517
Arthur Hungb92218b2018-08-14 12:00:21 +08004518 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004519 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4520 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004521 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004522 return windowHandle;
4523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 }
4525 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004526 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527}
4528
chaviw98318de2021-05-19 16:45:23 -05004529sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4530 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004531 if (windowHandleToken == nullptr) {
4532 return nullptr;
4533 }
4534
chaviw98318de2021-05-19 16:45:23 -05004535 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004536 if (windowHandle->getToken() == windowHandleToken) {
4537 return windowHandle;
4538 }
4539 }
4540 return nullptr;
4541}
4542
chaviw98318de2021-05-19 16:45:23 -05004543sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4544 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004545 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004546 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4547 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004548 if (handle->getId() == windowHandle->getId() &&
4549 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004550 if (windowHandle->getInfo()->displayId != it.first) {
4551 ALOGE("Found window %s in display %" PRId32
4552 ", but it should belong to display %" PRId32,
4553 windowHandle->getName().c_str(), it.first,
4554 windowHandle->getInfo()->displayId);
4555 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004556 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004560 return nullptr;
4561}
4562
chaviw98318de2021-05-19 16:45:23 -05004563sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004564 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4565 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566}
4567
chaviw98318de2021-05-19 16:45:23 -05004568bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004569 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4570 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004571 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004572 if (connection != nullptr && noInputChannel) {
4573 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4574 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4575 return false;
4576 }
4577
4578 if (connection == nullptr) {
4579 if (!noInputChannel) {
4580 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4581 }
4582 return false;
4583 }
4584 if (!connection->responsive) {
4585 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4586 return false;
4587 }
4588 return true;
4589}
4590
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004591std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4592 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004593 auto connectionIt = mConnectionsByToken.find(token);
4594 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004595 return nullptr;
4596 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004597 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004598}
4599
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004600void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004601 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4602 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004603 // Remove all handles on a display if there are no windows left.
4604 mWindowHandlesByDisplay.erase(displayId);
4605 return;
4606 }
4607
4608 // Since we compare the pointer of input window handles across window updates, we need
4609 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004610 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4611 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4612 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004613 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004614 }
4615
chaviw98318de2021-05-19 16:45:23 -05004616 std::vector<sp<WindowInfoHandle>> newHandles;
4617 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004618 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004619 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004620 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004621 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4622 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4623 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004624 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004625 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004626 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004627 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004628 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004629 }
4630
4631 if (info->displayId != displayId) {
4632 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4633 handle->getName().c_str(), displayId, info->displayId);
4634 continue;
4635 }
4636
Robert Carredd13602020-04-13 17:24:34 -07004637 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4638 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004639 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004640 oldHandle->updateFrom(handle);
4641 newHandles.push_back(oldHandle);
4642 } else {
4643 newHandles.push_back(handle);
4644 }
4645 }
4646
4647 // Insert or replace
4648 mWindowHandlesByDisplay[displayId] = newHandles;
4649}
4650
Arthur Hung72d8dc32020-03-28 00:48:39 +00004651void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004652 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004653 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004654 { // acquire lock
4655 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004656 for (const auto& [displayId, handles] : handlesPerDisplay) {
4657 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004658 }
4659 }
4660 // Wake up poll loop since it may need to make new input dispatching choices.
4661 mLooper->wake();
4662}
4663
Arthur Hungb92218b2018-08-14 12:00:21 +08004664/**
4665 * Called from InputManagerService, update window handle list by displayId that can receive input.
4666 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4667 * If set an empty list, remove all handles from the specific display.
4668 * For focused handle, check if need to change and send a cancel event to previous one.
4669 * For removed handle, check if need to send a cancel event if already in touch.
4670 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004671void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004672 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004673 if (DEBUG_FOCUS) {
4674 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004675 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004676 windowList += iwh->getName() + " ";
4677 }
4678 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680
Prabir Pradhand65552b2021-10-07 11:23:50 -07004681 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004682 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004683 const WindowInfo& info = *window->getInfo();
4684
4685 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4686 const bool noInputWindow = info.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004687 if (noInputWindow && window->getToken() != nullptr) {
4688 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4689 window->getName().c_str());
4690 window->releaseChannel();
4691 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004692
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004693 // Ensure all spy windows are trusted overlays
4694 LOG_ALWAYS_FATAL_IF(info.isSpy() && !info.trustedOverlay,
4695 "%s has feature SPY, but is not a trusted overlay.",
4696 window->getName().c_str());
4697
Prabir Pradhand65552b2021-10-07 11:23:50 -07004698 // Ensure all stylus interceptors are trusted overlays
4699 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() && !info.trustedOverlay,
4700 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4701 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004702 }
4703
Arthur Hung72d8dc32020-03-28 00:48:39 +00004704 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004705 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004707 // Save the old windows' orientation by ID before it gets updated.
4708 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004709 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004710 oldWindowOrientations.emplace(handle->getId(),
4711 handle->getInfo()->transform.getOrientation());
4712 }
4713
chaviw98318de2021-05-19 16:45:23 -05004714 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004715
chaviw98318de2021-05-19 16:45:23 -05004716 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004717 if (mLastHoverWindowHandle &&
4718 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4719 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004720 mLastHoverWindowHandle = nullptr;
4721 }
4722
Vishnu Nairc519ff72021-01-21 08:23:08 -08004723 std::optional<FocusResolver::FocusChanges> changes =
4724 mFocusResolver.setInputWindows(displayId, windowHandles);
4725 if (changes) {
4726 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004729 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4730 mTouchStatesByDisplay.find(displayId);
4731 if (stateIt != mTouchStatesByDisplay.end()) {
4732 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004733 for (size_t i = 0; i < state.windows.size();) {
4734 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004735 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004736 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004737 ALOGD("Touched window was removed: %s in display %" PRId32,
4738 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004739 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004740 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004741 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4742 if (touchedInputChannel != nullptr) {
4743 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4744 "touched window was removed");
4745 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004746 // Since we are about to drop the touch, cancel the events for the wallpaper as
4747 // well.
4748 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4749 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4750 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4751 if (wallpaper != nullptr) {
4752 sp<Connection> wallpaperConnection =
4753 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004754 if (wallpaperConnection != nullptr) {
4755 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4756 options);
4757 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004758 }
4759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004761 state.windows.erase(state.windows.begin() + i);
4762 } else {
4763 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 }
4765 }
arthurhungb89ccb02020-12-30 16:19:01 +08004766
arthurhung6d4bed92021-03-17 11:59:33 +08004767 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004768 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004769 if (mDragState &&
4770 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004771 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004772 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004773 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004774 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004775
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004776 // Determine if the orientation of any of the input windows have changed, and cancel all
4777 // pointer events if necessary.
4778 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4779 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4780 if (newWindowHandle != nullptr &&
4781 newWindowHandle->getInfo()->transform.getOrientation() !=
4782 oldWindowOrientations[oldWindowHandle->getId()]) {
4783 std::shared_ptr<InputChannel> inputChannel =
4784 getInputChannelLocked(newWindowHandle->getToken());
4785 if (inputChannel != nullptr) {
4786 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4787 "touched window's orientation changed");
4788 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004789 }
4790 }
4791 }
4792
Arthur Hung72d8dc32020-03-28 00:48:39 +00004793 // Release information for windows that are no longer present.
4794 // This ensures that unused input channels are released promptly.
4795 // Otherwise, they might stick around until the window handle is destroyed
4796 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004797 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004798 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004799 if (DEBUG_FOCUS) {
4800 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004801 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004802 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004803 }
chaviw291d88a2019-02-14 10:33:58 -08004804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805}
4806
4807void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004808 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004809 if (DEBUG_FOCUS) {
4810 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4811 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4812 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004813 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004814 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004815 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 } // release lock
4817
4818 // Wake up poll loop since it may need to make new input dispatching choices.
4819 mLooper->wake();
4820}
4821
Vishnu Nair599f1412021-06-21 10:39:58 -07004822void InputDispatcher::setFocusedApplicationLocked(
4823 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4824 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4825 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4826
4827 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4828 return; // This application is already focused. No need to wake up or change anything.
4829 }
4830
4831 // Set the new application handle.
4832 if (inputApplicationHandle != nullptr) {
4833 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4834 } else {
4835 mFocusedApplicationHandlesByDisplay.erase(displayId);
4836 }
4837
4838 // No matter what the old focused application was, stop waiting on it because it is
4839 // no longer focused.
4840 resetNoFocusedWindowTimeoutLocked();
4841}
4842
Tiger Huang721e26f2018-07-24 22:26:19 +08004843/**
4844 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4845 * the display not specified.
4846 *
4847 * We track any unreleased events for each window. If a window loses the ability to receive the
4848 * released event, we will send a cancel event to it. So when the focused display is changed, we
4849 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4850 * display. The display-specified events won't be affected.
4851 */
4852void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004853 if (DEBUG_FOCUS) {
4854 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4855 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004856 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004857 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004858
4859 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004860 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004861 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004862 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004863 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004864 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004865 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004866 CancelationOptions
4867 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4868 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004869 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004870 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4871 }
4872 }
4873 mFocusedDisplayId = displayId;
4874
Chris Ye3c2d6f52020-08-09 10:39:48 -07004875 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004876 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004877 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004878
Vishnu Nairad321cd2020-08-20 16:40:21 -07004879 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004880 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004881 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004882 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004883 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004884 }
4885 }
4886 }
4887
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004888 if (DEBUG_FOCUS) {
4889 logDispatchStateLocked();
4890 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004891 } // release lock
4892
4893 // Wake up poll loop since it may need to make new input dispatching choices.
4894 mLooper->wake();
4895}
4896
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004898 if (DEBUG_FOCUS) {
4899 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
4902 bool changed;
4903 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004904 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
4906 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4907 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004908 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 }
4910
4911 if (mDispatchEnabled && !enabled) {
4912 resetAndDropEverythingLocked("dispatcher is being disabled");
4913 }
4914
4915 mDispatchEnabled = enabled;
4916 mDispatchFrozen = frozen;
4917 changed = true;
4918 } else {
4919 changed = false;
4920 }
4921
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004922 if (DEBUG_FOCUS) {
4923 logDispatchStateLocked();
4924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 } // release lock
4926
4927 if (changed) {
4928 // Wake up poll loop since it may need to make new input dispatching choices.
4929 mLooper->wake();
4930 }
4931}
4932
4933void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004934 if (DEBUG_FOCUS) {
4935 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937
4938 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004939 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940
4941 if (mInputFilterEnabled == enabled) {
4942 return;
4943 }
4944
4945 mInputFilterEnabled = enabled;
4946 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4947 } // release lock
4948
4949 // Wake up poll loop since there might be work to do to drop everything.
4950 mLooper->wake();
4951}
4952
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004953void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004954 bool needWake = false;
4955 {
4956 std::scoped_lock lock(mLock);
4957 if (mInTouchMode == inTouchMode) {
4958 return;
4959 }
4960 if (DEBUG_TOUCH_MODE) {
4961 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4962 toString(inTouchMode));
4963 // TODO(b/198487159): Also print the current last interacted apps.
4964 }
4965
4966 // TODO(b/198499018): Store touch mode per display.
4967 mInTouchMode = inTouchMode;
4968
4969 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4970 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4971 needWake = enqueueInboundEventLocked(std::move(entry));
4972 } // release lock
4973
4974 if (needWake) {
4975 mLooper->wake();
4976 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004977}
4978
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004979void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4980 if (opacity < 0 || opacity > 1) {
4981 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4982 return;
4983 }
4984
4985 std::scoped_lock lock(mLock);
4986 mMaximumObscuringOpacityForTouch = opacity;
4987}
4988
4989void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4990 std::scoped_lock lock(mLock);
4991 mBlockUntrustedTouchesMode = mode;
4992}
4993
Arthur Hungabbb9d82021-09-01 14:52:30 +00004994std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4995 const sp<IBinder>& token) {
4996 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4997 for (TouchedWindow& w : state.windows) {
4998 if (w.windowHandle->getToken() == token) {
4999 return std::make_pair(&state, &w);
5000 }
5001 }
5002 }
5003 return std::make_pair(nullptr, nullptr);
5004}
5005
arthurhungb89ccb02020-12-30 16:19:01 +08005006bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5007 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005008 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005009 if (DEBUG_FOCUS) {
5010 ALOGD("Trivial transfer to same window.");
5011 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005012 return true;
5013 }
5014
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005016 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017
Arthur Hungabbb9d82021-09-01 14:52:30 +00005018 // Find the target touch state and touched window by fromToken.
5019 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5020 if (state == nullptr || touchedWindow == nullptr) {
5021 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 return false;
5023 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005024
5025 const int32_t displayId = state->displayId;
5026 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5027 if (toWindowHandle == nullptr) {
5028 ALOGW("Cannot transfer focus because to window not found.");
5029 return false;
5030 }
5031
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005032 if (DEBUG_FOCUS) {
5033 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005034 touchedWindow->windowHandle->getName().c_str(),
5035 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
5037
Arthur Hungabbb9d82021-09-01 14:52:30 +00005038 // Erase old window.
5039 int32_t oldTargetFlags = touchedWindow->targetFlags;
5040 BitSet32 pointerIds = touchedWindow->pointerIds;
5041 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042
Arthur Hungabbb9d82021-09-01 14:52:30 +00005043 // Add new window.
5044 int32_t newTargetFlags = oldTargetFlags &
5045 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5046 InputTarget::FLAG_DISPATCH_AS_IS);
5047 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048
Arthur Hungabbb9d82021-09-01 14:52:30 +00005049 // Store the dragging window.
5050 if (isDragDrop) {
5051 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 }
5053
Arthur Hungabbb9d82021-09-01 14:52:30 +00005054 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005055 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5056 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005057 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005058 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005059 CancelationOptions
5060 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5061 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005063 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064 }
5065
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005066 if (DEBUG_FOCUS) {
5067 logDispatchStateLocked();
5068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 } // release lock
5070
5071 // Wake up poll loop since it may need to make new input dispatching choices.
5072 mLooper->wake();
5073 return true;
5074}
5075
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005076// Binder call
5077bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5078 sp<IBinder> fromToken;
5079 { // acquire lock
5080 std::scoped_lock _l(mLock);
5081
Arthur Hungabbb9d82021-09-01 14:52:30 +00005082 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5083 [](const auto& pair) { return pair.second.windows.size() == 1; });
5084 if (it == mTouchStatesByDisplay.end()) {
5085 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5086 return false;
5087 }
5088 const int32_t displayId = it->first;
5089 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005090 if (toWindowHandle == nullptr) {
5091 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5092 return false;
5093 }
5094
Arthur Hungabbb9d82021-09-01 14:52:30 +00005095 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005096 const TouchedWindow& touchedWindow = state.windows[0];
5097 fromToken = touchedWindow.windowHandle->getToken();
5098 } // release lock
5099
5100 return transferTouchFocus(fromToken, destChannelToken);
5101}
5102
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005104 if (DEBUG_FOCUS) {
5105 ALOGD("Resetting and dropping all events (%s).", reason);
5106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107
5108 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5109 synthesizeCancelationEventsForAllConnectionsLocked(options);
5110
5111 resetKeyRepeatLocked();
5112 releasePendingEventLocked();
5113 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005114 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005117 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005119 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120}
5121
5122void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005123 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 dumpDispatchStateLocked(dump);
5125
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005126 std::istringstream stream(dump);
5127 std::string line;
5128
5129 while (std::getline(stream, line, '\n')) {
5130 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 }
5132}
5133
Prabir Pradhan99987712020-11-10 18:43:05 -08005134std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5135 std::string dump;
5136
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005137 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5138 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005139
5140 std::string windowName = "None";
5141 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005142 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005143 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5144 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5145 : "token has capture without window";
5146 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005147 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005148
5149 return dump;
5150}
5151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005153 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5154 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5155 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005156 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157
Tiger Huang721e26f2018-07-24 22:26:19 +08005158 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5159 dump += StringPrintf(INDENT "FocusedApplications:\n");
5160 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5161 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005162 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005163 const std::chrono::duration timeout =
5164 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005165 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005166 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005167 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005170 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005172
Vishnu Nairc519ff72021-01-21 08:23:08 -08005173 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005174 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005176 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005178 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5179 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005180 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005181 state.displayId, toString(state.down), toString(state.split),
5182 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005183 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005184 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005185 for (size_t i = 0; i < state.windows.size(); i++) {
5186 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005187 dump += StringPrintf(INDENT4
5188 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5189 i, touchedWindow.windowHandle->getName().c_str(),
5190 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005191 }
5192 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005193 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 }
5196 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005197 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 }
5199
arthurhung6d4bed92021-03-17 11:59:33 +08005200 if (mDragState) {
5201 dump += StringPrintf(INDENT "DragState:\n");
5202 mDragState->dump(dump, INDENT2);
5203 }
5204
Arthur Hungb92218b2018-08-14 12:00:21 +08005205 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005206 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5207 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5208 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5209 const auto& displayInfo = it->second;
5210 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5211 displayInfo.logicalHeight);
5212 displayInfo.transform.dump(dump, "transform", INDENT4);
5213 } else {
5214 dump += INDENT2 "No DisplayInfo found!\n";
5215 }
5216
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005217 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005218 dump += INDENT2 "Windows:\n";
5219 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005220 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5221 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005223 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005224 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005225 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005226 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005227 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005228 "applicationInfo.name=%s, "
5229 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005230 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005231 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005232 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005233 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005234 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005235 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005236 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005237 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005238 windowInfo->frameLeft, windowInfo->frameTop,
5239 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005240 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005241 windowInfo->applicationInfo.name.c_str(),
5242 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005243 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005244 dump += StringPrintf(", inputFeatures=%s",
5245 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005246 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005247 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005248 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005249 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005250 millis(windowInfo->dispatchingTimeout),
5251 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005252 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005253 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005254 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005255 }
5256 } else {
5257 dump += INDENT2 "Windows: <none>\n";
5258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 }
5260 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005261 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
5263
Michael Wright3dd60e22019-03-27 22:06:44 +00005264 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005265 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005266 const std::vector<Monitor>& monitors = it.second;
5267 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5268 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005269 }
5270 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005271 const std::vector<Monitor>& monitors = it.second;
5272 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5273 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005276 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 }
5278
5279 nsecs_t currentTime = now();
5280
5281 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005282 if (!mRecentQueue.empty()) {
5283 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005284 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005285 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005286 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005287 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
5289 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005290 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 }
5292
5293 // Dump event currently being dispatched.
5294 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005295 dump += INDENT "PendingEvent:\n";
5296 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005297 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005298 dump += StringPrintf(", age=%" PRId64 "ms\n",
5299 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005301 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 }
5303
5304 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005305 if (!mInboundQueue.empty()) {
5306 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005307 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005309 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005310 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
5312 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005313 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 }
5315
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005316 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005317 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005318 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5319 const KeyReplacement& replacement = pair.first;
5320 int32_t newKeyCode = pair.second;
5321 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005322 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005323 }
5324 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005325 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005326 }
5327
Prabir Pradhancef936d2021-07-21 16:17:52 +00005328 if (!mCommandQueue.empty()) {
5329 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5330 } else {
5331 dump += INDENT "CommandQueue: <empty>\n";
5332 }
5333
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005334 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005335 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005336 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005337 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005338 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005339 connection->inputChannel->getFd().get(),
5340 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005341 connection->getWindowName().c_str(),
5342 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005343 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005345 if (!connection->outboundQueue.empty()) {
5346 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5347 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005348 dump += dumpQueue(connection->outboundQueue, currentTime);
5349
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005351 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352 }
5353
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005354 if (!connection->waitQueue.empty()) {
5355 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5356 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005357 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005359 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 }
5361 }
5362 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005363 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 }
5365
5366 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005367 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5368 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005370 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 }
5372
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005373 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005374 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5375 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5376 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005377 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005378 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379}
5380
Michael Wright3dd60e22019-03-27 22:06:44 +00005381void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5382 const size_t numMonitors = monitors.size();
5383 for (size_t i = 0; i < numMonitors; i++) {
5384 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005385 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005386 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5387 dump += "\n";
5388 }
5389}
5390
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005391class LooperEventCallback : public LooperCallback {
5392public:
5393 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5394 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5395
5396private:
5397 std::function<int(int events)> mCallback;
5398};
5399
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005400Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005401 if (DEBUG_CHANNEL_CREATION) {
5402 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005405 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005406 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005407 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005408
5409 if (result) {
5410 return base::Error(result) << "Failed to open input channel pair with name " << name;
5411 }
5412
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005414 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005415 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005416 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005417 sp<Connection> connection =
5418 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005420 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5421 ALOGE("Created a new connection, but the token %p is already known", token.get());
5422 }
5423 mConnectionsByToken.emplace(token, connection);
5424
5425 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5426 this, std::placeholders::_1, token);
5427
5428 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 } // release lock
5430
5431 // Wake the looper because some connections have changed.
5432 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005433 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434}
5435
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005436Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5437 bool isGestureMonitor,
5438 const std::string& name,
5439 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005440 std::shared_ptr<InputChannel> serverChannel;
5441 std::unique_ptr<InputChannel> clientChannel;
5442 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5443 if (result) {
5444 return base::Error(result) << "Failed to open input channel pair with name " << name;
5445 }
5446
Michael Wright3dd60e22019-03-27 22:06:44 +00005447 { // acquire lock
5448 std::scoped_lock _l(mLock);
5449
5450 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005451 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5452 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005453 }
5454
Garfield Tan15601662020-09-22 15:32:38 -07005455 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005456 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005457 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005458
5459 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5460 ALOGE("Created a new connection, but the token %p is already known", token.get());
5461 }
5462 mConnectionsByToken.emplace(token, connection);
5463 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5464 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005465
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005466 auto& monitorsByDisplay =
5467 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005468 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005469
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005470 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005471 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5472 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005473 }
Garfield Tan15601662020-09-22 15:32:38 -07005474
Michael Wright3dd60e22019-03-27 22:06:44 +00005475 // Wake the looper because some connections have changed.
5476 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005477 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005478}
5479
Garfield Tan15601662020-09-22 15:32:38 -07005480status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005482 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483
Garfield Tan15601662020-09-22 15:32:38 -07005484 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 if (status) {
5486 return status;
5487 }
5488 } // release lock
5489
5490 // Wake the poll loop because removing the connection may have changed the current
5491 // synchronization state.
5492 mLooper->wake();
5493 return OK;
5494}
5495
Garfield Tan15601662020-09-22 15:32:38 -07005496status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5497 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005498 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005499 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005500 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 return BAD_VALUE;
5502 }
5503
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005504 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005505
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005507 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 }
5509
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005510 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511
5512 nsecs_t currentTime = now();
5513 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5514
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005515 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 return OK;
5517}
5518
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005519void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5520 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5521 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005522}
5523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005524void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005525 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005526 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005527 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005528 std::vector<Monitor>& monitors = it->second;
5529 const size_t numMonitors = monitors.size();
5530 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005531 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005532 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5533 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005534 monitors.erase(monitors.begin() + i);
5535 break;
5536 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005537 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005538 if (monitors.empty()) {
5539 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005540 } else {
5541 ++it;
5542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 }
5544}
5545
Michael Wright3dd60e22019-03-27 22:06:44 +00005546status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5547 { // acquire lock
5548 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005549
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005550 TouchState* statePtr = nullptr;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005551 std::shared_ptr<InputChannel> requestingChannel;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005552 int32_t displayId;
5553 int32_t deviceId;
5554 const std::optional<int32_t> foundGestureMonitorDisplayId =
5555 findGestureMonitorDisplayByTokenLocked(token);
5556
5557 // TODO: Optimize this function for pilfering from windows when removing gesture monitors.
5558 if (foundGestureMonitorDisplayId) {
5559 // A gesture monitor has requested to pilfer pointers.
5560 displayId = *foundGestureMonitorDisplayId;
5561 auto stateIt = mTouchStatesByDisplay.find(displayId);
5562 if (stateIt == mTouchStatesByDisplay.end()) {
5563 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5564 return BAD_VALUE;
5565 }
5566 statePtr = &stateIt->second;
5567
5568 for (const auto& monitor : statePtr->gestureMonitors) {
5569 if (monitor.inputChannel->getConnectionToken() == token) {
5570 requestingChannel = monitor.inputChannel;
5571 deviceId = statePtr->deviceId;
5572 }
5573 }
5574 } else {
5575 // Check if a window has requested to pilfer pointers.
5576 for (auto& [curDisplayId, state] : mTouchStatesByDisplay) {
5577 const sp<WindowInfoHandle>& windowHandle = state.getWindow(token);
5578 if (windowHandle != nullptr) {
5579 displayId = curDisplayId;
5580 requestingChannel = getInputChannelLocked(token);
5581 deviceId = state.deviceId;
5582 statePtr = &state;
5583 break;
5584 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005585 }
5586 }
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005587
5588 if (requestingChannel == nullptr) {
5589 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5590 return BAD_VALUE;
5591 }
5592 TouchState& state = *statePtr;
5593 if (!state.down) {
5594 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005595 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005596 return BAD_VALUE;
5597 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005598
5599 // Send cancel events to all the input channels we're stealing from.
5600 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005601 "input channel stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005602 options.deviceId = deviceId;
5603 options.displayId = displayId;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005604 std::string canceledWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005605 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005606 std::shared_ptr<InputChannel> channel =
5607 getInputChannelLocked(window.windowHandle->getToken());
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005608 if (channel != nullptr && channel->getConnectionToken() != token) {
Michael Wright3a240c42019-12-10 20:53:41 +00005609 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005610 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5611 canceledWindows += channel->getName();
Michael Wright3a240c42019-12-10 20:53:41 +00005612 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005613 }
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005614 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5615 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005616 canceledWindows.c_str());
5617
Michael Wright3dd60e22019-03-27 22:06:44 +00005618 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hungfbfa5722021-11-16 02:45:54 +00005619 state.split = false;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005620 state.filterWindowsExcept(token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005621 }
5622 return OK;
5623}
5624
Prabir Pradhan99987712020-11-10 18:43:05 -08005625void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5626 { // acquire lock
5627 std::scoped_lock _l(mLock);
5628 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005629 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005630 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5631 windowHandle != nullptr ? windowHandle->getName().c_str()
5632 : "token without window");
5633 }
5634
Vishnu Nairc519ff72021-01-21 08:23:08 -08005635 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005636 if (focusedToken != windowToken) {
5637 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5638 enabled ? "enable" : "disable");
5639 return;
5640 }
5641
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005642 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005643 ALOGW("Ignoring request to %s Pointer Capture: "
5644 "window has %s requested pointer capture.",
5645 enabled ? "enable" : "disable", enabled ? "already" : "not");
5646 return;
5647 }
5648
Christine Franksb768bb42021-11-29 12:11:31 -08005649 if (enabled) {
5650 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5651 mIneligibleDisplaysForPointerCapture.end(),
5652 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5653 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5654 return;
5655 }
5656 }
5657
Prabir Pradhan99987712020-11-10 18:43:05 -08005658 setPointerCaptureLocked(enabled);
5659 } // release lock
5660
5661 // Wake the thread to process command entries.
5662 mLooper->wake();
5663}
5664
Christine Franksb768bb42021-11-29 12:11:31 -08005665void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5666 { // acquire lock
5667 std::scoped_lock _l(mLock);
5668 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5669 if (!isEligible) {
5670 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5671 }
5672 } // release lock
5673}
5674
Michael Wright3dd60e22019-03-27 22:06:44 +00005675std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5676 const sp<IBinder>& token) {
5677 for (const auto& it : mGestureMonitorsByDisplay) {
5678 const std::vector<Monitor>& monitors = it.second;
5679 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005680 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005681 return it.first;
5682 }
5683 }
5684 }
5685 return std::nullopt;
5686}
5687
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005688std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5689 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5690 if (gesturePid.has_value()) {
5691 return gesturePid;
5692 }
5693 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5694}
5695
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005696sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005697 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005698 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005699 }
5700
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005701 for (const auto& [token, connection] : mConnectionsByToken) {
5702 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005703 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 }
5705 }
Robert Carr4e670e52018-08-15 13:26:12 -07005706
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005707 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708}
5709
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005710std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5711 sp<Connection> connection = getConnectionLocked(connectionToken);
5712 if (connection == nullptr) {
5713 return "<nullptr>";
5714 }
5715 return connection->getInputChannelName();
5716}
5717
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005718void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005719 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005720 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005721}
5722
Prabir Pradhancef936d2021-07-21 16:17:52 +00005723void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5724 const sp<Connection>& connection, uint32_t seq,
5725 bool handled, nsecs_t consumeTime) {
5726 // Handle post-event policy actions.
5727 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5728 if (dispatchEntryIt == connection->waitQueue.end()) {
5729 return;
5730 }
5731 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5732 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5733 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5734 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5735 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5736 }
5737 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5738 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5739 connection->inputChannel->getConnectionToken(),
5740 dispatchEntry->deliveryTime, consumeTime, finishTime);
5741 }
5742
5743 bool restartEvent;
5744 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5745 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5746 restartEvent =
5747 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5748 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5749 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5750 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5751 handled);
5752 } else {
5753 restartEvent = false;
5754 }
5755
5756 // Dequeue the event and start the next cycle.
5757 // Because the lock might have been released, it is possible that the
5758 // contents of the wait queue to have been drained, so we need to double-check
5759 // a few things.
5760 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5761 if (dispatchEntryIt != connection->waitQueue.end()) {
5762 dispatchEntry = *dispatchEntryIt;
5763 connection->waitQueue.erase(dispatchEntryIt);
5764 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5765 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5766 if (!connection->responsive) {
5767 connection->responsive = isConnectionResponsive(*connection);
5768 if (connection->responsive) {
5769 // The connection was unresponsive, and now it's responsive.
5770 processConnectionResponsiveLocked(*connection);
5771 }
5772 }
5773 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005774 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005775 connection->outboundQueue.push_front(dispatchEntry);
5776 traceOutboundQueueLength(*connection);
5777 } else {
5778 releaseDispatchEntry(dispatchEntry);
5779 }
5780 }
5781
5782 // Start the next dispatch cycle for this connection.
5783 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784}
5785
Prabir Pradhancef936d2021-07-21 16:17:52 +00005786void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5787 const sp<IBinder>& newToken) {
5788 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5789 scoped_unlock unlock(mLock);
5790 mPolicy->notifyFocusChanged(oldToken, newToken);
5791 };
5792 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793}
5794
Prabir Pradhancef936d2021-07-21 16:17:52 +00005795void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5796 auto command = [this, token, x, y]() REQUIRES(mLock) {
5797 scoped_unlock unlock(mLock);
5798 mPolicy->notifyDropWindow(token, x, y);
5799 };
5800 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005801}
5802
Prabir Pradhancef936d2021-07-21 16:17:52 +00005803void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5804 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5805 scoped_unlock unlock(mLock);
5806 mPolicy->notifyUntrustedTouch(obscuringPackage);
5807 };
5808 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005809}
5810
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005811void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5812 if (connection == nullptr) {
5813 LOG_ALWAYS_FATAL("Caller must check for nullness");
5814 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005815 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5816 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005817 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005818 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005819 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005820 return;
5821 }
5822 /**
5823 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5824 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5825 * has changed. This could cause newer entries to time out before the already dispatched
5826 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5827 * processes the events linearly. So providing information about the oldest entry seems to be
5828 * most useful.
5829 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005830 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005831 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5832 std::string reason =
5833 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005834 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005835 ns2ms(currentWait),
5836 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005837 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005838 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005839
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005840 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5841
5842 // Stop waking up for events on this connection, it is already unresponsive
5843 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005844}
5845
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005846void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5847 std::string reason =
5848 StringPrintf("%s does not have a focused window", application->getName().c_str());
5849 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005850
Prabir Pradhancef936d2021-07-21 16:17:52 +00005851 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5852 scoped_unlock unlock(mLock);
5853 mPolicy->notifyNoFocusedWindowAnr(application);
5854 };
5855 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005856}
5857
chaviw98318de2021-05-19 16:45:23 -05005858void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005859 const std::string& reason) {
5860 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5861 updateLastAnrStateLocked(windowLabel, reason);
5862}
5863
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005864void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5865 const std::string& reason) {
5866 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005867 updateLastAnrStateLocked(windowLabel, reason);
5868}
5869
5870void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5871 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005873 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 struct tm tm;
5875 localtime_r(&t, &tm);
5876 char timestr[64];
5877 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005878 mLastAnrState.clear();
5879 mLastAnrState += INDENT "ANR:\n";
5880 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005881 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5882 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005883 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005884}
5885
Prabir Pradhancef936d2021-07-21 16:17:52 +00005886void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5887 KeyEntry& entry) {
5888 const KeyEvent event = createKeyEvent(entry);
5889 nsecs_t delay = 0;
5890 { // release lock
5891 scoped_unlock unlock(mLock);
5892 android::base::Timer t;
5893 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5894 entry.policyFlags);
5895 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5896 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5897 std::to_string(t.duration().count()).c_str());
5898 }
5899 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900
5901 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005902 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005903 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005904 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005906 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5907 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909}
5910
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005911void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005912 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5913 scoped_unlock unlock(mLock);
5914 mPolicy->notifyMonitorUnresponsive(pid, reason);
5915 };
5916 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005917}
5918
Prabir Pradhancef936d2021-07-21 16:17:52 +00005919void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005920 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005921 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5922 scoped_unlock unlock(mLock);
5923 mPolicy->notifyWindowUnresponsive(token, reason);
5924 };
5925 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005926}
5927
5928void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005929 auto command = [this, pid]() REQUIRES(mLock) {
5930 scoped_unlock unlock(mLock);
5931 mPolicy->notifyMonitorResponsive(pid);
5932 };
5933 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005934}
5935
Prabir Pradhancef936d2021-07-21 16:17:52 +00005936void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5937 auto command = [this, connectionToken]() REQUIRES(mLock) {
5938 scoped_unlock unlock(mLock);
5939 mPolicy->notifyWindowResponsive(connectionToken);
5940 };
5941 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005942}
5943
5944/**
5945 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5946 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5947 * command entry to the command queue.
5948 */
5949void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5950 std::string reason) {
5951 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5952 if (connection.monitor) {
5953 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5954 reason.c_str());
5955 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5956 if (!pid.has_value()) {
5957 ALOGE("Could not find unresponsive monitor for connection %s",
5958 connection.inputChannel->getName().c_str());
5959 return;
5960 }
5961 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5962 return;
5963 }
5964 // If not a monitor, must be a window
5965 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5966 reason.c_str());
5967 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5968}
5969
5970/**
5971 * Tell the policy that a connection has become responsive so that it can stop ANR.
5972 */
5973void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5974 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5975 if (connection.monitor) {
5976 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5977 if (!pid.has_value()) {
5978 ALOGE("Could not find responsive monitor for connection %s",
5979 connection.inputChannel->getName().c_str());
5980 return;
5981 }
5982 sendMonitorResponsiveCommandLocked(pid.value());
5983 return;
5984 }
5985 // If not a monitor, must be a window
5986 sendWindowResponsiveCommandLocked(connectionToken);
5987}
5988
Prabir Pradhancef936d2021-07-21 16:17:52 +00005989bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005990 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005991 KeyEntry& keyEntry, bool handled) {
5992 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005993 if (!handled) {
5994 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005995 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005996 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005997 return false;
5998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005999
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006000 // Get the fallback key state.
6001 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006002 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006003 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006004 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006005 connection->inputState.removeFallbackKey(originalKeyCode);
6006 }
6007
6008 if (handled || !dispatchEntry->hasForegroundTarget()) {
6009 // If the application handles the original key for which we previously
6010 // generated a fallback or if the window is not a foreground window,
6011 // then cancel the associated fallback key, if any.
6012 if (fallbackKeyCode != -1) {
6013 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006014 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6015 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6016 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6017 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6018 keyEntry.policyFlags);
6019 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006020 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006021 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022
6023 mLock.unlock();
6024
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006025 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006026 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027
6028 mLock.lock();
6029
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006030 // Cancel the fallback key.
6031 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006033 "application handled the original non-fallback key "
6034 "or is no longer a foreground target, "
6035 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036 options.keyCode = fallbackKeyCode;
6037 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039 connection->inputState.removeFallbackKey(originalKeyCode);
6040 }
6041 } else {
6042 // If the application did not handle a non-fallback key, first check
6043 // that we are in a good state to perform unhandled key event processing
6044 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006045 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006046 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006047 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6048 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6049 "since this is not an initial down. "
6050 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6051 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6052 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 return false;
6054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006057 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6058 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6059 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6060 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6061 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006062 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063
6064 mLock.unlock();
6065
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006066 bool fallback =
6067 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006068 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069
6070 mLock.lock();
6071
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006072 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006073 connection->inputState.removeFallbackKey(originalKeyCode);
6074 return false;
6075 }
6076
6077 // Latch the fallback keycode for this key on an initial down.
6078 // The fallback keycode cannot change at any other point in the lifecycle.
6079 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081 fallbackKeyCode = event.getKeyCode();
6082 } else {
6083 fallbackKeyCode = AKEYCODE_UNKNOWN;
6084 }
6085 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6086 }
6087
6088 ALOG_ASSERT(fallbackKeyCode != -1);
6089
6090 // Cancel the fallback key if the policy decides not to send it anymore.
6091 // We will continue to dispatch the key to the policy but we will no
6092 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006093 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6094 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006095 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6096 if (fallback) {
6097 ALOGD("Unhandled key event: Policy requested to send key %d"
6098 "as a fallback for %d, but on the DOWN it had requested "
6099 "to send %d instead. Fallback canceled.",
6100 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6101 } else {
6102 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6103 "but on the DOWN it had requested to send %d. "
6104 "Fallback canceled.",
6105 originalKeyCode, fallbackKeyCode);
6106 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006107 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006108
6109 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6110 "canceling fallback, policy no longer desires it");
6111 options.keyCode = fallbackKeyCode;
6112 synthesizeCancelationEventsForConnectionLocked(connection, options);
6113
6114 fallback = false;
6115 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006117 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118 }
6119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006121 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6122 {
6123 std::string msg;
6124 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6125 connection->inputState.getFallbackKeys();
6126 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6127 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6128 }
6129 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6130 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006132 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133
6134 if (fallback) {
6135 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006136 keyEntry.eventTime = event.getEventTime();
6137 keyEntry.deviceId = event.getDeviceId();
6138 keyEntry.source = event.getSource();
6139 keyEntry.displayId = event.getDisplayId();
6140 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6141 keyEntry.keyCode = fallbackKeyCode;
6142 keyEntry.scanCode = event.getScanCode();
6143 keyEntry.metaState = event.getMetaState();
6144 keyEntry.repeatCount = event.getRepeatCount();
6145 keyEntry.downTime = event.getDownTime();
6146 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006147
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006148 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6149 ALOGD("Unhandled key event: Dispatching fallback key. "
6150 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6151 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6152 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006153 return true; // restart the event
6154 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006155 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6156 ALOGD("Unhandled key event: No fallback key.");
6157 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006158
6159 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006160 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 }
6162 }
6163 return false;
6164}
6165
Prabir Pradhancef936d2021-07-21 16:17:52 +00006166bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006167 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006168 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006169 return false;
6170}
6171
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172void InputDispatcher::traceInboundQueueLengthLocked() {
6173 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006174 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 }
6176}
6177
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006178void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 if (ATRACE_ENABLED()) {
6180 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006181 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6182 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183 }
6184}
6185
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006186void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006187 if (ATRACE_ENABLED()) {
6188 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006189 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6190 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191 }
6192}
6193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006194void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006195 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006196
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006197 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198 dumpDispatchStateLocked(dump);
6199
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006200 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006201 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006202 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203 }
6204}
6205
6206void InputDispatcher::monitor() {
6207 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006208 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006210 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211}
6212
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006213/**
6214 * Wake up the dispatcher and wait until it processes all events and commands.
6215 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6216 * this method can be safely called from any thread, as long as you've ensured that
6217 * the work you are interested in completing has already been queued.
6218 */
6219bool InputDispatcher::waitForIdle() {
6220 /**
6221 * Timeout should represent the longest possible time that a device might spend processing
6222 * events and commands.
6223 */
6224 constexpr std::chrono::duration TIMEOUT = 100ms;
6225 std::unique_lock lock(mLock);
6226 mLooper->wake();
6227 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6228 return result == std::cv_status::no_timeout;
6229}
6230
Vishnu Naire798b472020-07-23 13:52:21 -07006231/**
6232 * Sets focus to the window identified by the token. This must be called
6233 * after updating any input window handles.
6234 *
6235 * Params:
6236 * request.token - input channel token used to identify the window that should gain focus.
6237 * request.focusedToken - the token that the caller expects currently to be focused. If the
6238 * specified token does not match the currently focused window, this request will be dropped.
6239 * If the specified focused token matches the currently focused window, the call will succeed.
6240 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6241 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6242 * when requesting the focus change. This determines which request gets
6243 * precedence if there is a focus change request from another source such as pointer down.
6244 */
Vishnu Nair958da932020-08-21 17:12:37 -07006245void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6246 { // acquire lock
6247 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006248 std::optional<FocusResolver::FocusChanges> changes =
6249 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6250 if (changes) {
6251 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006252 }
6253 } // release lock
6254 // Wake up poll loop since it may need to make new input dispatching choices.
6255 mLooper->wake();
6256}
6257
Vishnu Nairc519ff72021-01-21 08:23:08 -08006258void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6259 if (changes.oldFocus) {
6260 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006261 if (focusedInputChannel) {
6262 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6263 "focus left window");
6264 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006265 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006266 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006267 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006268 if (changes.newFocus) {
6269 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006270 }
6271
Prabir Pradhan99987712020-11-10 18:43:05 -08006272 // If a window has pointer capture, then it must have focus. We need to ensure that this
6273 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6274 // If the window loses focus before it loses pointer capture, then the window can be in a state
6275 // where it has pointer capture but not focus, violating the contract. Therefore we must
6276 // dispatch the pointer capture event before the focus event. Since focus events are added to
6277 // the front of the queue (above), we add the pointer capture event to the front of the queue
6278 // after the focus events are added. This ensures the pointer capture event ends up at the
6279 // front.
6280 disablePointerCaptureForcedLocked();
6281
Vishnu Nairc519ff72021-01-21 08:23:08 -08006282 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006283 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006284 }
6285}
Vishnu Nair958da932020-08-21 17:12:37 -07006286
Prabir Pradhan99987712020-11-10 18:43:05 -08006287void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006288 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006289 return;
6290 }
6291
6292 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6293
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006294 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006295 setPointerCaptureLocked(false);
6296 }
6297
6298 if (!mWindowTokenWithPointerCapture) {
6299 // No need to send capture changes because no window has capture.
6300 return;
6301 }
6302
6303 if (mPendingEvent != nullptr) {
6304 // Move the pending event to the front of the queue. This will give the chance
6305 // for the pending event to be dropped if it is a captured event.
6306 mInboundQueue.push_front(mPendingEvent);
6307 mPendingEvent = nullptr;
6308 }
6309
6310 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006311 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006312 mInboundQueue.push_front(std::move(entry));
6313}
6314
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006315void InputDispatcher::setPointerCaptureLocked(bool enable) {
6316 mCurrentPointerCaptureRequest.enable = enable;
6317 mCurrentPointerCaptureRequest.seq++;
6318 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006319 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006320 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006321 };
6322 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006323}
6324
Vishnu Nair599f1412021-06-21 10:39:58 -07006325void InputDispatcher::displayRemoved(int32_t displayId) {
6326 { // acquire lock
6327 std::scoped_lock _l(mLock);
6328 // Set an empty list to remove all handles from the specific display.
6329 setInputWindowsLocked(/* window handles */ {}, displayId);
6330 setFocusedApplicationLocked(displayId, nullptr);
6331 // Call focus resolver to clean up stale requests. This must be called after input windows
6332 // have been removed for the removed display.
6333 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006334 // Reset pointer capture eligibility, regardless of previous state.
6335 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006336 } // release lock
6337
6338 // Wake up poll loop since it may need to make new input dispatching choices.
6339 mLooper->wake();
6340}
6341
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006342void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6343 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006344 // The listener sends the windows as a flattened array. Separate the windows by display for
6345 // more convenient parsing.
6346 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006347 for (const auto& info : windowInfos) {
6348 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6349 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6350 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006351
6352 { // acquire lock
6353 std::scoped_lock _l(mLock);
6354 mDisplayInfos.clear();
6355 for (const auto& displayInfo : displayInfos) {
6356 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6357 }
6358
6359 for (const auto& [displayId, handles] : handlesPerDisplay) {
6360 setInputWindowsLocked(handles, displayId);
6361 }
6362 }
6363 // Wake up poll loop since it may need to make new input dispatching choices.
6364 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006365}
6366
Vishnu Nair062a8672021-09-03 16:07:44 -07006367bool InputDispatcher::shouldDropInput(
6368 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6369 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6370 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6371 isWindowObscuredLocked(windowHandle))) {
6372 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6373 "%" PRId32 ".",
6374 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6375 windowHandle->getInfo()->inputFeatures.string().c_str(),
6376 windowHandle->getInfo()->displayId);
6377 return true;
6378 }
6379 return false;
6380}
6381
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006382void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6383 const std::vector<gui::WindowInfo>& windowInfos,
6384 const std::vector<DisplayInfo>& displayInfos) {
6385 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6386}
6387
Arthur Hungdfd528e2021-12-08 13:23:04 +00006388void InputDispatcher::cancelCurrentTouch() {
6389 {
6390 std::scoped_lock _l(mLock);
6391 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6392 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6393 "cancel current touch");
6394 synthesizeCancelationEventsForAllConnectionsLocked(options);
6395
6396 mTouchStatesByDisplay.clear();
6397 mLastHoverWindowHandle.clear();
6398 }
6399 // Wake up poll loop since there might be work to do.
6400 mLooper->wake();
6401}
6402
Garfield Tane84e6f92019-08-29 17:28:41 -07006403} // namespace android::inputdispatcher