blob: 7a0022293ae6f23eb914b5a97479797a14370f45 [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
Antonio Kantekea47acb2021-12-23 12:41:25 -0800140// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000141constexpr 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 +0000420bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000421 // Do not keep track of gesture monitors. They receive every event and would disproportionately
422 // affect the statistics.
423 if (connection.monitor) {
424 return false;
425 }
426 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
427 if (!connection.responsive) {
428 return false;
429 }
430 return true;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000434 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
435 const int32_t& inputEventId = eventEntry.id;
436 if (inputEventId != dispatchEntry.resolvedEventId) {
437 // Event was transmuted
438 return false;
439 }
440 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
441 return false;
442 }
443 // Only track latency for events that originated from hardware
444 if (eventEntry.isSynthesized()) {
445 return false;
446 }
447 const EventEntry::Type& inputEventEntryType = eventEntry.type;
448 if (inputEventEntryType == EventEntry::Type::KEY) {
449 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
450 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
451 return false;
452 }
453 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
454 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
455 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
456 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
457 return false;
458 }
459 } else {
460 // Not a key or a motion
461 return false;
462 }
463 if (!shouldReportMetricsForConnection(connection)) {
464 return false;
465 }
466 return true;
467}
468
Prabir Pradhancef936d2021-07-21 16:17:52 +0000469/**
470 * Connection is responsive if it has no events in the waitQueue that are older than the
471 * current time.
472 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000473bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000474 const nsecs_t currentTime = now();
475 for (const DispatchEntry* entry : connection.waitQueue) {
476 if (entry->timeoutTime < currentTime) {
477 return false;
478 }
479 }
480 return true;
481}
482
Antonio Kantekf16f2832021-09-28 04:39:20 +0000483// Returns true if the event type passed as argument represents a user activity.
484bool isUserActivityEvent(const EventEntry& eventEntry) {
485 switch (eventEntry.type) {
486 case EventEntry::Type::FOCUS:
487 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
488 case EventEntry::Type::DRAG:
489 case EventEntry::Type::TOUCH_MODE_CHANGED:
490 case EventEntry::Type::SENSOR:
491 case EventEntry::Type::CONFIGURATION_CHANGED:
492 return false;
493 case EventEntry::Type::DEVICE_RESET:
494 case EventEntry::Type::KEY:
495 case EventEntry::Type::MOTION:
496 return true;
497 }
498}
499
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800500// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700501bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
502 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800503 const auto inputConfig = windowInfo.inputConfig;
504 if (windowInfo.displayId != displayId ||
505 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800506 return false;
507 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700508 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800509 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800510 return false;
511 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800512 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800513 return false;
514 }
515 return true;
516}
517
Prabir Pradhand65552b2021-10-07 11:23:50 -0700518bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
519 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
520 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
521 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
522}
523
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000524} // namespace
525
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526// --- InputDispatcher ---
527
Garfield Tan00f511d2019-06-12 16:55:40 -0700528InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
529 : mPolicy(policy),
530 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700531 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800532 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700533 mAppSwitchSawKeyDown(false),
534 mAppSwitchDueTime(LONG_LONG_MAX),
535 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800536 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700537 mDispatchEnabled(false),
538 mDispatchFrozen(false),
539 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800540 // mInTouchMode will be initialized by the WindowManager to the default device config.
541 // To avoid leaking stack in case that call never comes, and for tests,
542 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000543 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100544 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000545 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800546 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000547 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800548 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800550 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700552 mWindowInfoListener = new DispatcherWindowListener(*this);
553 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
554
Yi Kong9b14ac62018-07-17 13:48:38 -0700555 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556
557 policy->getDispatcherConfiguration(&mConfig);
558}
559
560InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000561 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562
Prabir Pradhancef936d2021-07-21 16:17:52 +0000563 resetKeyRepeatLocked();
564 releasePendingEventLocked();
565 drainInboundQueueLocked();
566 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000568 while (!mConnectionsByToken.empty()) {
569 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000570 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
571 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 }
573}
574
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700575status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700576 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700577 return ALREADY_EXISTS;
578 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700579 mThread = std::make_unique<InputThread>(
580 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
581 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700582}
583
584status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700585 if (mThread && mThread->isCallingThread()) {
586 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700587 return INVALID_OPERATION;
588 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700589 mThread.reset();
590 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591}
592
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593void InputDispatcher::dispatchOnce() {
594 nsecs_t nextWakeupTime = LONG_LONG_MAX;
595 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800596 std::scoped_lock _l(mLock);
597 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598
599 // Run a dispatch loop if there are no pending commands.
600 // The dispatch loop might enqueue commands to run afterwards.
601 if (!haveCommandsLocked()) {
602 dispatchOnceInnerLocked(&nextWakeupTime);
603 }
604
605 // Run all pending commands if there are any.
606 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000607 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 nextWakeupTime = LONG_LONG_MIN;
609 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800610
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700611 // If we are still waiting for ack on some events,
612 // we might have to wake up earlier to check if an app is anr'ing.
613 const nsecs_t nextAnrCheck = processAnrsLocked();
614 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
615
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800616 // We are about to enter an infinitely long sleep, because we have no commands or
617 // pending or queued events
618 if (nextWakeupTime == LONG_LONG_MAX) {
619 mDispatcherEnteredIdle.notify_all();
620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 } // release lock
622
623 // Wait for callback or timeout or wake. (make sure we round up, not down)
624 nsecs_t currentTime = now();
625 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
626 mLooper->pollOnce(timeoutMillis);
627}
628
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700629/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500630 * Raise ANR if there is no focused window.
631 * Before the ANR is raised, do a final state check:
632 * 1. The currently focused application must be the same one we are waiting for.
633 * 2. Ensure we still don't have a focused window.
634 */
635void InputDispatcher::processNoFocusedWindowAnrLocked() {
636 // Check if the application that we are waiting for is still focused.
637 std::shared_ptr<InputApplicationHandle> focusedApplication =
638 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
639 if (focusedApplication == nullptr ||
640 focusedApplication->getApplicationToken() !=
641 mAwaitedFocusedApplication->getApplicationToken()) {
642 // Unexpected because we should have reset the ANR timer when focused application changed
643 ALOGE("Waited for a focused window, but focused application has already changed to %s",
644 focusedApplication->getName().c_str());
645 return; // The focused application has changed.
646 }
647
chaviw98318de2021-05-19 16:45:23 -0500648 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500649 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
650 if (focusedWindowHandle != nullptr) {
651 return; // We now have a focused window. No need for ANR.
652 }
653 onAnrLocked(mAwaitedFocusedApplication);
654}
655
656/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700657 * Check if any of the connections' wait queues have events that are too old.
658 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
659 * Return the time at which we should wake up next.
660 */
661nsecs_t InputDispatcher::processAnrsLocked() {
662 const nsecs_t currentTime = now();
663 nsecs_t nextAnrCheck = LONG_LONG_MAX;
664 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
665 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
666 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500667 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700668 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500669 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700670 return LONG_LONG_MIN;
671 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500672 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
674 }
675 }
676
677 // Check if any connection ANRs are due
678 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
679 if (currentTime < nextAnrCheck) { // most likely scenario
680 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
681 }
682
683 // If we reached here, we have an unresponsive connection.
684 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
685 if (connection == nullptr) {
686 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
687 return nextAnrCheck;
688 }
689 connection->responsive = false;
690 // Stop waking up for this unresponsive connection
691 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000692 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700693 return LONG_LONG_MIN;
694}
695
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800696std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
697 const sp<Connection>& connection) {
698 if (connection->monitor) {
699 return mMonitorDispatchingTimeout;
700 }
701 const sp<WindowInfoHandle> window =
702 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700703 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500704 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500706 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707}
708
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
710 nsecs_t currentTime = now();
711
Jeff Browndc5992e2014-04-11 01:27:26 -0700712 // Reset the key repeat timer whenever normal dispatch is suspended while the
713 // device is in a non-interactive state. This is to ensure that we abort a key
714 // repeat if the device is just coming out of sleep.
715 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 resetKeyRepeatLocked();
717 }
718
719 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
720 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100721 if (DEBUG_FOCUS) {
722 ALOGD("Dispatch frozen. Waiting some more.");
723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 return;
725 }
726
727 // Optimize latency of app switches.
728 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
729 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
730 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
731 if (mAppSwitchDueTime < *nextWakeupTime) {
732 *nextWakeupTime = mAppSwitchDueTime;
733 }
734
735 // Ready to start a new event.
736 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700738 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 if (isAppSwitchDue) {
740 // The inbound queue is empty so the app switch key we were waiting
741 // for will never arrive. Stop waiting for it.
742 resetPendingAppSwitchLocked(false);
743 isAppSwitchDue = false;
744 }
745
746 // Synthesize a key repeat if appropriate.
747 if (mKeyRepeatState.lastKeyEntry) {
748 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
749 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
750 } else {
751 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
752 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
753 }
754 }
755 }
756
757 // Nothing to do if there is no pending event.
758 if (!mPendingEvent) {
759 return;
760 }
761 } else {
762 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700763 mPendingEvent = mInboundQueue.front();
764 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 traceInboundQueueLengthLocked();
766 }
767
768 // Poke user activity for this event.
769 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700770 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 }
773
774 // Now we have an event to dispatch.
775 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700776 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700782 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 }
784
785 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700786 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
788
789 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700790 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700791 const ConfigurationChangedEntry& typedEntry =
792 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700793 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 break;
796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700798 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 const DeviceResetEntry& typedEntry =
800 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 break;
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100806 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 std::shared_ptr<FocusEntry> typedEntry =
808 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100809 dispatchFocusLocked(currentTime, typedEntry);
810 done = true;
811 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
812 break;
813 }
814
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700815 case EventEntry::Type::TOUCH_MODE_CHANGED: {
816 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
817 dispatchTouchModeChangeLocked(currentTime, typedEntry);
818 done = true;
819 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
820 break;
821 }
822
Prabir Pradhan99987712020-11-10 18:43:05 -0800823 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
824 const auto typedEntry =
825 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
826 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
827 done = true;
828 break;
829 }
830
arthurhungb89ccb02020-12-30 16:19:01 +0800831 case EventEntry::Type::DRAG: {
832 std::shared_ptr<DragEntry> typedEntry =
833 std::static_pointer_cast<DragEntry>(mPendingEvent);
834 dispatchDragLocked(currentTime, typedEntry);
835 done = true;
836 break;
837 }
838
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700839 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700840 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700842 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 resetPendingAppSwitchLocked(true);
844 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700845 } else if (dropReason == DropReason::NOT_DROPPED) {
846 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700847 }
848 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700850 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700852 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
853 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700855 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 break;
857 }
858
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700859 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700860 std::shared_ptr<MotionEntry> motionEntry =
861 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700862 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
863 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700865 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
869 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Chris Yef59a2f42020-10-16 12:55:26 -0700874
875 case EventEntry::Type::SENSOR: {
876 std::shared_ptr<SensorEntry> sensorEntry =
877 std::static_pointer_cast<SensorEntry>(mPendingEvent);
878 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
879 dropReason = DropReason::APP_SWITCH;
880 }
881 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
882 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
883 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
884 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
885 dropReason = DropReason::STALE;
886 }
887 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
888 done = true;
889 break;
890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892
893 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700895 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Michael Wright3a981722015-06-10 15:26:13 +0100897 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898
899 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902}
903
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700904/**
905 * Return true if the events preceding this incoming motion event should be dropped
906 * Return false otherwise (the default behaviour)
907 */
908bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700909 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700910 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700911
912 // Optimize case where the current application is unresponsive and the user
913 // decides to touch a window in a different application.
914 // If the application takes too long to catch up then we drop all events preceding
915 // the touch into the other window.
916 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700917 int32_t displayId = motionEntry.displayId;
918 int32_t x = static_cast<int32_t>(
919 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
920 int32_t y = static_cast<int32_t>(
921 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700922
923 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500924 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700925 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 touchedWindowHandle->getApplicationToken() !=
928 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 ALOGI("Pruning input queue because user touched a different application while waiting "
931 "for %s",
932 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700933 return true;
934 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800936 // Alternatively, maybe there's a spy window that could handle this event.
937 const std::vector<sp<WindowInfoHandle>> touchedSpies =
938 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
939 for (const auto& windowHandle : touchedSpies) {
940 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000941 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800942 // This spy window could take more input. Drop all events preceding this
943 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800945 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 mAwaitedFocusedApplication->getName().c_str());
947 return true;
948 }
949 }
950 }
951
952 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
953 // yet been processed by some connections, the dispatcher will wait for these motion
954 // events to be processed before dispatching the key event. This is because these motion events
955 // may cause a new window to be launched, which the user might expect to receive focus.
956 // To prevent waiting forever for such events, just send the key to the currently focused window
957 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
958 ALOGD("Received a new pointer down event, stop waiting for events to process and "
959 "just send the pending key event to the focused window.");
960 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 }
962 return false;
963}
964
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700966 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 mInboundQueue.push_back(std::move(newEntry));
968 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 traceInboundQueueLengthLocked();
970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700971 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700972 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 // Optimize app switch latency.
974 // If the application takes too long to catch up then we drop all events preceding
975 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700978 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700980 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000982 if (DEBUG_APP_SWITCH) {
983 ALOGD("App switch is pending!");
984 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700985 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 mAppSwitchSawKeyDown = false;
987 needWake = true;
988 }
989 }
990 }
991 break;
992 }
993
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700994 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700995 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
996 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700997 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001002 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1003 break;
1004 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001005 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001006 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001007 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001008 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001009 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1010 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001011 // nothing to do
1012 break;
1013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 return needWake;
1017}
1018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001019void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001020 // Do not store sensor event in recent queue to avoid flooding the queue.
1021 if (entry->type != EventEntry::Type::SENSOR) {
1022 mRecentQueue.push_back(entry);
1023 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001024 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001025 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027}
1028
chaviw98318de2021-05-19 16:45:23 -05001029sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1030 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001031 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001032 bool addOutsideTargets,
1033 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001034 if (addOutsideTargets && touchState == nullptr) {
1035 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001038 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001039 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001040 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001041 continue;
1042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001044 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001045 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001046 return windowHandle;
1047 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001048
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001049 if (addOutsideTargets &&
1050 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001051 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1052 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
1054 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001055 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056}
1057
Prabir Pradhand65552b2021-10-07 11:23:50 -07001058std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1059 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001060 // Traverse windows from front to back and gather the touched spy windows.
1061 std::vector<sp<WindowInfoHandle>> spyWindows;
1062 const auto& windowHandles = getWindowHandlesLocked(displayId);
1063 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1064 const WindowInfo& info = *windowHandle->getInfo();
1065
Prabir Pradhand65552b2021-10-07 11:23:50 -07001066 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001067 continue;
1068 }
1069 if (!info.isSpy()) {
1070 // The first touched non-spy window was found, so return the spy windows touched so far.
1071 return spyWindows;
1072 }
1073 spyWindows.push_back(windowHandle);
1074 }
1075 return spyWindows;
1076}
1077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 const char* reason;
1080 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001082 if (DEBUG_INBOUND_EVENT_DETAILS) {
1083 ALOGD("Dropped event because policy consumed it.");
1084 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 reason = "inbound event was dropped because the policy consumed it";
1086 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 case DropReason::DISABLED:
1088 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because input dispatch is disabled.");
1090 }
1091 reason = "inbound event was dropped because input dispatch is disabled";
1092 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 ALOGI("Dropped event because of pending overdue app switch.");
1095 reason = "inbound event was dropped because of pending overdue app switch";
1096 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 ALOGI("Dropped event because the current application is not responding and the user "
1099 "has started interacting with a different application.");
1100 reason = "inbound event was dropped because the current application is not responding "
1101 "and the user has started interacting with a different application";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because it is stale.");
1105 reason = "inbound event was dropped because it is stale";
1106 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001107 case DropReason::NO_POINTER_CAPTURE:
1108 ALOGI("Dropped event because there is no window with Pointer Capture.");
1109 reason = "inbound event was dropped because there is no window with Pointer Capture";
1110 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001111 case DropReason::NOT_DROPPED: {
1112 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
1116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001117 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001118 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1120 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001123 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1125 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1127 synthesizeCancelationEventsForAllConnectionsLocked(options);
1128 } else {
1129 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1130 synthesizeCancelationEventsForAllConnectionsLocked(options);
1131 }
1132 break;
1133 }
Chris Yef59a2f42020-10-16 12:55:26 -07001134 case EventEntry::Type::SENSOR: {
1135 break;
1136 }
arthurhungb89ccb02020-12-30 16:19:01 +08001137 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1138 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 break;
1140 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001141 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001142 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001143 case EventEntry::Type::CONFIGURATION_CHANGED:
1144 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001145 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001146 break;
1147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149}
1150
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001151static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1153 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154}
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1157 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1158 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1159 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160}
1161
1162bool InputDispatcher::isAppSwitchPendingLocked() {
1163 return mAppSwitchDueTime != LONG_LONG_MAX;
1164}
1165
1166void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1167 mAppSwitchDueTime = LONG_LONG_MAX;
1168
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001169 if (DEBUG_APP_SWITCH) {
1170 if (handled) {
1171 ALOGD("App switch has arrived.");
1172 } else {
1173 ALOGD("App switch was abandoned.");
1174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001179 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180}
1181
Prabir Pradhancef936d2021-07-21 16:17:52 +00001182bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001183 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 return false;
1185 }
1186
1187 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001188 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001190 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1191 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 return true;
1194}
1195
Prabir Pradhancef936d2021-07-21 16:17:52 +00001196void InputDispatcher::postCommandLocked(Command&& command) {
1197 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198}
1199
1200void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001201 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 releaseInboundEventLocked(entry);
1205 }
1206 traceInboundQueueLengthLocked();
1207}
1208
1209void InputDispatcher::releasePendingEventLocked() {
1210 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001212 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214}
1215
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001216void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001218 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001219 if (DEBUG_DISPATCH_CYCLE) {
1220 ALOGD("Injected inbound event was dropped.");
1221 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001225 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228}
1229
1230void InputDispatcher::resetKeyRepeatLocked() {
1231 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001232 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234}
1235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1237 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238
Michael Wright2e732952014-09-24 13:26:59 -07001239 uint32_t policyFlags = entry->policyFlags &
1240 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 std::shared_ptr<KeyEntry> newEntry =
1243 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1244 entry->source, entry->displayId, policyFlags, entry->action,
1245 entry->flags, entry->keyCode, entry->scanCode,
1246 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 newEntry->syntheticRepeat = true;
1249 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252}
1253
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001256 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1257 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259
1260 // Reset key repeating in case a keyboard device was added or removed or something.
1261 resetKeyRepeatLocked();
1262
1263 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001264 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1265 scoped_unlock unlock(mLock);
1266 mPolicy->notifyConfigurationChanged(eventTime);
1267 };
1268 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 return true;
1270}
1271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1273 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001274 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1275 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1276 entry.deviceId);
1277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278
liushenxiang42232912021-05-21 20:24:09 +08001279 // Reset key repeating in case a keyboard device was disabled or enabled.
1280 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1281 resetKeyRepeatLocked();
1282 }
1283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 synthesizeCancelationEventsForAllConnectionsLocked(options);
1287 return true;
1288}
1289
Vishnu Nairad321cd2020-08-20 16:40:21 -07001290void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001291 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001292 if (mPendingEvent != nullptr) {
1293 // Move the pending event to the front of the queue. This will give the chance
1294 // for the pending event to get dispatched to the newly focused window
1295 mInboundQueue.push_front(mPendingEvent);
1296 mPendingEvent = nullptr;
1297 }
1298
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 std::unique_ptr<FocusEntry> focusEntry =
1300 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1301 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302
1303 // This event should go to the front of the queue, but behind all other focus events
1304 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001306 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 [](const std::shared_ptr<EventEntry>& event) {
1308 return event->type == EventEntry::Type::FOCUS;
1309 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001310
1311 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001312 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001313}
1314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001316 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001317 if (channel == nullptr) {
1318 return; // Window has gone away
1319 }
1320 InputTarget target;
1321 target.inputChannel = channel;
1322 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1323 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001324 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1325 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001326 std::string reason = std::string("reason=").append(entry->reason);
1327 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001328 dispatchEventLocked(currentTime, entry, {target});
1329}
1330
Prabir Pradhan99987712020-11-10 18:43:05 -08001331void InputDispatcher::dispatchPointerCaptureChangedLocked(
1332 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1333 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001334 dropReason = DropReason::NOT_DROPPED;
1335
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001337 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001338
1339 if (entry->pointerCaptureRequest.enable) {
1340 // Enable Pointer Capture.
1341 if (haveWindowWithPointerCapture &&
1342 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1343 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1344 "to the window.");
1345 }
1346 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001347 // This can happen if a window requests capture and immediately releases capture.
1348 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001349 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001350 return;
1351 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001352 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1353 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1354 return;
1355 }
1356
Vishnu Nairc519ff72021-01-21 08:23:08 -08001357 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001358 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1359 mWindowTokenWithPointerCapture = token;
1360 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001361 // Disable Pointer Capture.
1362 // We do not check if the sequence number matches for requests to disable Pointer Capture
1363 // for two reasons:
1364 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1365 // to disable capture with the same sequence number: one generated by
1366 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1367 // Capture being disabled in InputReader.
1368 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1369 // actual Pointer Capture state that affects events being generated by input devices is
1370 // in InputReader.
1371 if (!haveWindowWithPointerCapture) {
1372 // Pointer capture was already forcefully disabled because of focus change.
1373 dropReason = DropReason::NOT_DROPPED;
1374 return;
1375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 token = mWindowTokenWithPointerCapture;
1377 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001378 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001379 setPointerCaptureLocked(false);
1380 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001381 }
1382
1383 auto channel = getInputChannelLocked(token);
1384 if (channel == nullptr) {
1385 // Window has gone away, clean up Pointer Capture state.
1386 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001387 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001388 setPointerCaptureLocked(false);
1389 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 return;
1391 }
1392 InputTarget target;
1393 target.inputChannel = channel;
1394 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1395 entry->dispatchInProgress = true;
1396 dispatchEventLocked(currentTime, entry, {target});
1397
1398 dropReason = DropReason::NOT_DROPPED;
1399}
1400
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001401void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1402 const std::shared_ptr<TouchModeEntry>& entry) {
1403 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1404 getWindowHandlesLocked(mFocusedDisplayId);
1405 if (windowHandles.empty()) {
1406 return;
1407 }
1408 const std::vector<InputTarget> inputTargets =
1409 getInputTargetsFromWindowHandlesLocked(windowHandles);
1410 if (inputTargets.empty()) {
1411 return;
1412 }
1413 entry->dispatchInProgress = true;
1414 dispatchEventLocked(currentTime, entry, inputTargets);
1415}
1416
1417std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1418 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1419 std::vector<InputTarget> inputTargets;
1420 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1421 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1422 const sp<IBinder>& token = handle->getToken();
1423 if (token == nullptr) {
1424 continue;
1425 }
1426 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1427 if (channel == nullptr) {
1428 continue; // Window has gone away
1429 }
1430 InputTarget target;
1431 target.inputChannel = channel;
1432 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1433 inputTargets.push_back(target);
1434 }
1435 return inputTargets;
1436}
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001441 if (!entry->dispatchInProgress) {
1442 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1443 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1444 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1445 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001446 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 // We have seen two identical key downs in a row which indicates that the device
1448 // driver is automatically generating key repeats itself. We take note of the
1449 // repeat here, but we disable our own next key repeat timer since it is clear that
1450 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001451 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1452 // Make sure we don't get key down from a different device. If a different
1453 // device Id has same key pressed down, the new device Id will replace the
1454 // current one to hold the key repeat with repeat count reset.
1455 // In the future when got a KEY_UP on the device id, drop it and do not
1456 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1458 resetKeyRepeatLocked();
1459 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1460 } else {
1461 // Not a repeat. Save key down state in case we do see a repeat later.
1462 resetKeyRepeatLocked();
1463 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1464 }
1465 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001466 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1467 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001468 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001469 if (DEBUG_INBOUND_EVENT_DETAILS) {
1470 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1471 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 resetKeyRepeatLocked();
1474 }
1475
1476 if (entry->repeatCount == 1) {
1477 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1478 } else {
1479 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1480 }
1481
1482 entry->dispatchInProgress = true;
1483
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001484 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 }
1486
1487 // Handle case where the policy asked us to try again later last time.
1488 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1489 if (currentTime < entry->interceptKeyWakeupTime) {
1490 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1491 *nextWakeupTime = entry->interceptKeyWakeupTime;
1492 }
1493 return false; // wait until next wakeup
1494 }
1495 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1496 entry->interceptKeyWakeupTime = 0;
1497 }
1498
1499 // Give the policy a chance to intercept the key.
1500 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1501 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001502 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001503 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001504
1505 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1506 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1507 };
1508 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 return false; // wait for the command to run
1510 } else {
1511 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1512 }
1513 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001514 if (*dropReason == DropReason::NOT_DROPPED) {
1515 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 }
1517 }
1518
1519 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001520 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001522 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1523 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001524 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 return true;
1526 }
1527
1528 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001529 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001530 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001531 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 return false;
1534 }
1535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001536 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001537 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return true;
1539 }
1540
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001541 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001542 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
1544 // Dispatch the key.
1545 dispatchEventLocked(currentTime, entry, inputTargets);
1546 return true;
1547}
1548
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001550 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1551 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1552 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1553 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1554 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1555 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1556 entry.metaState, entry.repeatCount, entry.downTime);
1557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558}
1559
Prabir Pradhancef936d2021-07-21 16:17:52 +00001560void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1561 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001562 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001563 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1564 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1565 "source=0x%x, sensorType=%s",
1566 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001567 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001568 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001569 auto command = [this, entry]() REQUIRES(mLock) {
1570 scoped_unlock unlock(mLock);
1571
1572 if (entry->accuracyChanged) {
1573 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1574 }
1575 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1576 entry->hwTimestamp, entry->values);
1577 };
1578 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001579}
1580
1581bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1583 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001584 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001585 }
Chris Yef59a2f42020-10-16 12:55:26 -07001586 { // acquire lock
1587 std::scoped_lock _l(mLock);
1588
1589 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1590 std::shared_ptr<EventEntry> entry = *it;
1591 if (entry->type == EventEntry::Type::SENSOR) {
1592 it = mInboundQueue.erase(it);
1593 releaseInboundEventLocked(entry);
1594 }
1595 }
1596 }
1597 return true;
1598}
1599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001600bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001601 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001602 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001604 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 entry->dispatchInProgress = true;
1606
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 }
1609
1610 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001611 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001612 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001613 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1614 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 return true;
1616 }
1617
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001618 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619
1620 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001621 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
1623 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001624 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 if (isPointerEvent) {
1626 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001628 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001629 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 } else {
1631 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001632 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001635 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 return false;
1637 }
1638
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001639 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001641 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1642 return true;
1643 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001644 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001645 CancelationOptions::Mode mode(isPointerEvent
1646 ? CancelationOptions::CANCEL_POINTER_EVENTS
1647 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1648 CancelationOptions options(mode, "input event injection failed");
1649 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 return true;
1651 }
1652
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001653 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
1656 // Dispatch the motion.
1657 if (conflictingPointerActions) {
1658 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 synthesizeCancelationEventsForAllConnectionsLocked(options);
1661 }
1662 dispatchEventLocked(currentTime, entry, inputTargets);
1663 return true;
1664}
1665
chaviw98318de2021-05-19 16:45:23 -05001666void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001667 bool isExiting, const MotionEntry& motionEntry) {
1668 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1669 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1670 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1671 PointerCoords pointerCoords;
1672 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1673 pointerCoords.transform(windowHandle->getInfo()->transform);
1674
1675 std::unique_ptr<DragEntry> dragEntry =
1676 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1677 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1678 pointerCoords.getY());
1679
1680 enqueueInboundEventLocked(std::move(dragEntry));
1681}
1682
1683void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1684 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1685 if (channel == nullptr) {
1686 return; // Window has gone away
1687 }
1688 InputTarget target;
1689 target.inputChannel = channel;
1690 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1691 entry->dispatchInProgress = true;
1692 dispatchEventLocked(currentTime, entry, {target});
1693}
1694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001695void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001696 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1697 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1698 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001699 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001700 "metaState=0x%x, buttonState=0x%x,"
1701 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1702 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001703 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1704 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1705 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001707 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1708 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1709 "x=%f, y=%f, pressure=%f, size=%f, "
1710 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1711 "orientation=%f",
1712 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1713 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1714 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1717 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1718 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1719 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1720 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1721 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724}
1725
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001726void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1727 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001730 if (DEBUG_DISPATCH_CYCLE) {
1731 ALOGD("dispatchEventToCurrentInputTargets");
1732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001734 updateInteractionTokensLocked(*eventEntry, inputTargets);
1735
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1737
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001738 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001740 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001741 sp<Connection> connection =
1742 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001743 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001744 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001746 if (DEBUG_FOCUS) {
1747 ALOGD("Dropping event delivery to target with channel '%s' because it "
1748 "is no longer registered with the input dispatcher.",
1749 inputTarget.inputChannel->getName().c_str());
1750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 }
1752 }
1753}
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1756 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1757 // If the policy decides to close the app, we will get a channel removal event via
1758 // unregisterInputChannel, and will clean up the connection that way. We are already not
1759 // sending new pointers to the connection when it blocked, but focused events will continue to
1760 // pile up.
1761 ALOGW("Canceling events for %s because it is unresponsive",
1762 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001763 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1765 "application not responding");
1766 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768}
1769
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001771 if (DEBUG_FOCUS) {
1772 ALOGD("Resetting ANR timeouts.");
1773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
1775 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001776 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001777 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778}
1779
Tiger Huang721e26f2018-07-24 22:26:19 +08001780/**
1781 * Get the display id that the given event should go to. If this event specifies a valid display id,
1782 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1783 * Focused display is the display that the user most recently interacted with.
1784 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001785int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001786 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001787 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001788 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1790 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 break;
1792 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001793 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001794 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1795 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001796 break;
1797 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001798 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001799 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001800 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001801 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001802 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001803 case EventEntry::Type::SENSOR:
1804 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001805 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 return ADISPLAY_ID_NONE;
1807 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001808 }
1809 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1810}
1811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1813 const char* focusedWindowName) {
1814 if (mAnrTracker.empty()) {
1815 // already processed all events that we waited for
1816 mKeyIsWaitingForEventsTimeout = std::nullopt;
1817 return false;
1818 }
1819
1820 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1821 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001822 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001823 mKeyIsWaitingForEventsTimeout = currentTime +
1824 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1825 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001826 return true;
1827 }
1828
1829 // We still have pending events, and already started the timer
1830 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1831 return true; // Still waiting
1832 }
1833
1834 // Waited too long, and some connection still hasn't processed all motions
1835 // Just send the key to the focused window
1836 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1837 focusedWindowName);
1838 mKeyIsWaitingForEventsTimeout = std::nullopt;
1839 return false;
1840}
1841
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1843 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1844 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
Tiger Huang721e26f2018-07-24 22:26:19 +08001847 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001848 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001849 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001850 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1851
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 // If there is no currently focused window and no focused application
1853 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1855 ALOGI("Dropping %s event because there is no focused window or focused application in "
1856 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001857 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 }
1860
Vishnu Nair062a8672021-09-03 16:07:44 -07001861 // Drop key events if requested by input feature
1862 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1863 return InputEventInjectionResult::FAILED;
1864 }
1865
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001866 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1867 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1868 // start interacting with another application via touch (app switch). This code can be removed
1869 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1870 // an app is expected to have a focused window.
1871 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1872 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1873 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001874 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1875 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1876 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001877 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001878 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 ALOGW("Waiting because no window has focus but %s may eventually add a "
1880 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001881 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001883 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1885 // Already raised ANR. Drop the event
1886 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001887 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889 } else {
1890 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001891 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 }
1893 }
1894
1895 // we have a valid, non-null focused window
1896 resetNoFocusedWindowTimeoutLocked();
1897
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001899 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
1902
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001903 if (focusedWindowHandle->getInfo()->inputConfig.test(
1904 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001905 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 }
1908
1909 // If the event is a key event, then we must wait for all previous events to
1910 // complete before delivering it because previous events may have the
1911 // side-effect of transferring focus to a different window and we want to
1912 // ensure that the following keys are sent to the new window.
1913 //
1914 // Suppose the user touches a button in a window then immediately presses "A".
1915 // If the button causes a pop-up window to appear then we want to ensure that
1916 // the "A" key is delivered to the new pop-up window. This is because users
1917 // often anticipate pending UI changes when typing on a keyboard.
1918 // To obtain this behavior, we must serialize key events with respect to all
1919 // prior input events.
1920 if (entry.type == EventEntry::Type::KEY) {
1921 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1922 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001923 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926
1927 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001928 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001929 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1930 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931
1932 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934}
1935
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936/**
1937 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1938 * that are currently unresponsive.
1939 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001940std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1941 const std::vector<Monitor>& monitors) const {
1942 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001944 [this](const Monitor& monitor) REQUIRES(mLock) {
1945 sp<Connection> connection =
1946 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001947 if (connection == nullptr) {
1948 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001949 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950 return false;
1951 }
1952 if (!connection->responsive) {
1953 ALOGW("Unresponsive monitor %s will not get the new gesture",
1954 connection->inputChannel->getName().c_str());
1955 return false;
1956 }
1957 return true;
1958 });
1959 return responsiveMonitors;
1960}
1961
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1963 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1964 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001965 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 enum InjectionPermission {
1967 INJECTION_PERMISSION_UNKNOWN,
1968 INJECTION_PERMISSION_GRANTED,
1969 INJECTION_PERMISSION_DENIED
1970 };
1971
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 // For security reasons, we defer updating the touch state until we are sure that
1973 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001974 const int32_t displayId = entry.displayId;
1975 const int32_t action = entry.action;
1976 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
1978 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001981 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1982 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001984 // Copy current touch state into tempTouchState.
1985 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1986 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001987 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001989 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1990 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08001991 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001992 }
1993
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001994 bool isSplit = tempTouchState.split;
1995 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1996 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1997 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001998
1999 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2000 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2001 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2002 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2003 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002004 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 bool wrongDevice = false;
2006 if (newGesture) {
2007 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002009 ALOGI("Dropping event because a pointer for a different device is already down "
2010 "in display %" PRId32,
2011 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002012 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 switchedDevice = false;
2015 wrongDevice = true;
2016 goto Failed;
2017 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002018 tempTouchState.reset();
2019 tempTouchState.down = down;
2020 tempTouchState.deviceId = entry.deviceId;
2021 tempTouchState.source = entry.source;
2022 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002024 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002025 ALOGI("Dropping move event because a pointer for a different device is already active "
2026 "in display %" PRId32,
2027 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002028 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002029 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002030 switchedDevice = false;
2031 wrongDevice = true;
2032 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034
2035 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2036 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2037
Garfield Tan00f511d2019-06-12 16:55:40 -07002038 int32_t x;
2039 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002040 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002041 // Always dispatch mouse events to cursor position.
2042 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002043 x = int32_t(entry.xCursorPosition);
2044 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002045 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002046 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2047 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002048 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002049 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002050 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002051 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002052 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002053
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002055 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002056 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2057 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002060 }
2061
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002062 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002064 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2065 // New window supports splitting, but we should never split mouse events.
2066 isSplit = !isFromMouse;
2067 } else if (isSplit) {
2068 // New window does not support splitting but we have already split events.
2069 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002070 newTouchedWindowHandle = nullptr;
2071 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002072 } else {
2073 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002074 // be delivered to a new window which supports split touch. Pointers from a mouse device
2075 // should never be split.
2076 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002077 }
2078
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002079 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002080 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002081 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2082 newHoverWindowHandle = nullptr;
2083 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002086 }
2087
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002088 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002089 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002090 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002091 // Process the foreground window first so that it is the first to receive the event.
2092 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002093 }
2094
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002095 if (newTouchedWindows.empty()) {
2096 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2097 x, y, displayId);
2098 injectionResult = InputEventInjectionResult::FAILED;
2099 goto Failed;
2100 }
2101
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002102 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2103 const WindowInfo& info = *windowHandle->getInfo();
2104
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002105 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002106 ALOGI("Not sending touch event to %s because it is paused",
2107 windowHandle->getName().c_str());
2108 continue;
2109 }
2110
2111 // Ensure the window has a connection and the connection is responsive
2112 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2113 if (!isResponsive) {
2114 ALOGW("Not sending touch gesture to %s because it is not responsive",
2115 windowHandle->getName().c_str());
2116 continue;
2117 }
2118
2119 // Drop events that can't be trusted due to occlusion
2120 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2121 TouchOcclusionInfo occlusionInfo =
2122 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2123 if (!isTouchTrustedLocked(occlusionInfo)) {
2124 if (DEBUG_TOUCH_OCCLUSION) {
2125 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2126 for (const auto& log : occlusionInfo.debugInfo) {
2127 ALOGD("%s", log.c_str());
2128 }
2129 }
2130 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2131 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2132 ALOGW("Dropping untrusted touch event due to %s/%d",
2133 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2134 continue;
2135 }
2136 }
2137 }
2138
2139 // Drop touch events if requested by input feature
2140 if (shouldDropInput(entry, windowHandle)) {
2141 continue;
2142 }
2143
2144 // Set target flags.
2145 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2146
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002147 if (!info.isSpy()) {
2148 // There should only be one new foreground (non-spy) window at this location.
2149 targetFlags |= InputTarget::FLAG_FOREGROUND;
2150 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002151
2152 if (isSplit) {
2153 targetFlags |= InputTarget::FLAG_SPLIT;
2154 }
2155 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2156 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2157 } else if (isWindowObscuredLocked(windowHandle)) {
2158 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2159 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002160
2161 // Update the temporary touch state.
2162 BitSet32 pointerIds;
2163 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002165 pointerIds.markBit(pointerId);
2166 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002167
2168 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 } else {
2171 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2172
2173 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002175 if (DEBUG_FOCUS) {
2176 ALOGD("Dropping event because the pointer is not down or we previously "
2177 "dropped the pointer down event in display %" PRId32,
2178 displayId);
2179 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002180 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 goto Failed;
2182 }
2183
arthurhung6d4bed92021-03-17 11:59:33 +08002184 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002185
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002187 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002189 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2190 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191
Prabir Pradhand65552b2021-10-07 11:23:50 -07002192 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002193 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002195 newTouchedWindowHandle =
2196 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002197
2198 // Drop touch events if requested by input feature
2199 if (newTouchedWindowHandle != nullptr &&
2200 shouldDropInput(entry, newTouchedWindowHandle)) {
2201 newTouchedWindowHandle = nullptr;
2202 }
2203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002204 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2205 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002206 if (DEBUG_FOCUS) {
2207 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2208 oldTouchedWindowHandle->getName().c_str(),
2209 newTouchedWindowHandle->getName().c_str(), displayId);
2210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2213 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2214 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215
2216 // Make a slippery entrance into the new window.
2217 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002218 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 int32_t targetFlags =
2222 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 if (isSplit) {
2224 targetFlags |= InputTarget::FLAG_SPLIT;
2225 }
2226 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2227 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002228 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2229 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
2232 BitSet32 pointerIds;
2233 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002234 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002236 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
2238 }
2239 }
2240
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002241 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002243 // Let the previous window know that the hover sequence is over, unless we already did
2244 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002245 if (mLastHoverWindowHandle != nullptr &&
2246 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2247 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002248 if (DEBUG_HOVER) {
2249 ALOGD("Sending hover exit event to window %s.",
2250 mLastHoverWindowHandle->getName().c_str());
2251 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2253 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
2255
Garfield Tandf26e862020-07-01 20:18:19 -07002256 // Let the new window know that the hover sequence is starting, unless we already did it
2257 // when dispatching it as is to newTouchedWindowHandle.
2258 if (newHoverWindowHandle != nullptr &&
2259 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2260 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002261 if (DEBUG_HOVER) {
2262 ALOGD("Sending hover enter event to window %s.",
2263 newHoverWindowHandle->getName().c_str());
2264 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002265 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2266 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2267 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269 }
2270
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002271 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2272 // of the touched windows we previously found if they became paused or unresponsive or were
2273 // removed.
2274 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2275 [](const TouchedWindow& touchedWindow) {
2276 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2277 touchedWindow.windowHandle->getInfo()->isSpy();
2278 })) {
2279 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2280 displayId);
2281 injectionResult = InputEventInjectionResult::FAILED;
2282 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002285 // Check permission to inject into all touched foreground windows.
2286 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2287 [this, &entry](const TouchedWindow& touchedWindow) {
2288 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2289 !checkInjectionPermission(touchedWindow.windowHandle,
2290 entry.injectionState);
2291 })) {
2292 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2293 injectionPermission = INJECTION_PERMISSION_DENIED;
2294 goto Failed;
2295 }
2296 // Permission granted to inject into all touched foreground windows.
2297 injectionPermission = INJECTION_PERMISSION_GRANTED;
2298
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 // Check whether windows listening for outside touches are owned by the same UID. If it is
2300 // set the policy flag that we will not reveal coordinate information to this window.
2301 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002302 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002304 if (foregroundWindowHandle) {
2305 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002306 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002307 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002308 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2309 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2310 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 InputTarget::FLAG_ZERO_COORDS,
2312 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315 }
2316 }
2317 }
2318
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 // If this is the first pointer going down and the touched window has a wallpaper
2320 // then also add the touched wallpaper windows so they are locked in for the duration
2321 // of the touch gesture.
2322 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2323 // engine only supports touch events. We would need to add a mechanism similar
2324 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2325 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002326 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002327 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002328 if (foregroundWindowHandle &&
2329 foregroundWindowHandle->getInfo()->inputConfig.test(
2330 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002331 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002332 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002333 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2334 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002335 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002336 windowHandle->getInfo()->inputConfig.test(
2337 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002338 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 .addOrUpdateWindow(windowHandle,
2340 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2341 InputTarget::
2342 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2343 InputTarget::FLAG_DISPATCH_AS_IS,
2344 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 }
2346 }
2347 }
2348 }
2349
2350 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002351 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002353 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
2358 // Drop the outside or hover touch windows since we will not care about them
2359 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002360 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
2362Failed:
2363 // Check injection permission once and for all.
2364 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002365 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 injectionPermission = INJECTION_PERMISSION_GRANTED;
2367 } else {
2368 injectionPermission = INJECTION_PERMISSION_DENIED;
2369 }
2370 }
2371
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002372 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2373 return injectionResult;
2374 }
2375
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002377 if (!wrongDevice) {
2378 if (switchedDevice) {
2379 if (DEBUG_FOCUS) {
2380 ALOGD("Conflicting pointer actions: Switched to a different device.");
2381 }
2382 *outConflictingPointerActions = true;
2383 }
2384
2385 if (isHoverAction) {
2386 // Started hovering, therefore no longer down.
2387 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002388 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002389 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2390 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 *outConflictingPointerActions = true;
2393 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 tempTouchState.reset();
2395 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2396 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2397 tempTouchState.deviceId = entry.deviceId;
2398 tempTouchState.source = entry.source;
2399 tempTouchState.displayId = displayId;
2400 }
2401 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2402 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2403 // All pointers up or canceled.
2404 tempTouchState.reset();
2405 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2406 // First pointer went down.
2407 if (oldState && oldState->down) {
2408 if (DEBUG_FOCUS) {
2409 ALOGD("Conflicting pointer actions: Down received while already down.");
2410 }
2411 *outConflictingPointerActions = true;
2412 }
2413 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2414 // One pointer went up.
2415 if (isSplit) {
2416 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2417 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002419 for (size_t i = 0; i < tempTouchState.windows.size();) {
2420 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2421 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2422 touchedWindow.pointerIds.clearBit(pointerId);
2423 if (touchedWindow.pointerIds.isEmpty()) {
2424 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2425 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002428 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002430 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002431 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002432
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002433 // Save changes unless the action was scroll in which case the temporary touch
2434 // state was only valid for this one action.
2435 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2436 if (tempTouchState.displayId >= 0) {
2437 mTouchStatesByDisplay[displayId] = tempTouchState;
2438 } else {
2439 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002443 // Update hover state.
2444 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 }
2446
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 return injectionResult;
2448}
2449
arthurhung6d4bed92021-03-17 11:59:33 +08002450void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002451 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2452 // have an explicit reason to support it.
2453 constexpr bool isStylus = false;
2454
chaviw98318de2021-05-19 16:45:23 -05002455 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002456 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002457 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002458 if (dropWindow) {
2459 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002460 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002461 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002462 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002463 }
2464 mDragState.reset();
2465}
2466
2467void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2468 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002469 return;
2470 }
2471
arthurhung6d4bed92021-03-17 11:59:33 +08002472 if (!mDragState->isStartDrag) {
2473 mDragState->isStartDrag = true;
2474 mDragState->isStylusButtonDownAtStart =
2475 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2476 }
2477
arthurhungb89ccb02020-12-30 16:19:01 +08002478 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2479 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2480 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2481 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002482 // Handle the special case : stylus button no longer pressed.
2483 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2484 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2485 finishDragAndDrop(entry.displayId, x, y);
2486 return;
2487 }
2488
Prabir Pradhand65552b2021-10-07 11:23:50 -07002489 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2490 // we have an explicit reason to support it.
2491 constexpr bool isStylus = false;
2492
chaviw98318de2021-05-19 16:45:23 -05002493 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002494 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002495 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002496 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002497 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2498 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2499 if (mDragState->dragHoverWindowHandle != nullptr) {
2500 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2501 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002502 }
arthurhung6d4bed92021-03-17 11:59:33 +08002503 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002504 }
2505 // enqueue drag location if needed.
2506 if (hoverWindowHandle != nullptr) {
2507 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2508 }
arthurhung6d4bed92021-03-17 11:59:33 +08002509 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2510 finishDragAndDrop(entry.displayId, x, y);
2511 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002512 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002513 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002514 }
2515}
2516
chaviw98318de2021-05-19 16:45:23 -05002517void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 int32_t targetFlags, BitSet32 pointerIds,
2519 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002520 std::vector<InputTarget>::iterator it =
2521 std::find_if(inputTargets.begin(), inputTargets.end(),
2522 [&windowHandle](const InputTarget& inputTarget) {
2523 return inputTarget.inputChannel->getConnectionToken() ==
2524 windowHandle->getToken();
2525 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002526
chaviw98318de2021-05-19 16:45:23 -05002527 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002528
2529 if (it == inputTargets.end()) {
2530 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002531 std::shared_ptr<InputChannel> inputChannel =
2532 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002533 if (inputChannel == nullptr) {
2534 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2535 return;
2536 }
2537 inputTarget.inputChannel = inputChannel;
2538 inputTarget.flags = targetFlags;
2539 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002540 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2541 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002542 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002543 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002544 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002545 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002546 inputTargets.push_back(inputTarget);
2547 it = inputTargets.end() - 1;
2548 }
2549
2550 ALOG_ASSERT(it->flags == targetFlags);
2551 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2552
chaviw1ff3d1e2020-07-01 15:53:47 -07002553 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554}
2555
Michael Wright3dd60e22019-03-27 22:06:44 +00002556void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002557 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002558 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2559 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002560
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002561 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2562 InputTarget target;
2563 target.inputChannel = monitor.inputChannel;
2564 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2565 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2566 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002567 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002568 target.setDefaultPointerTransform(target.displayTransform);
2569 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571}
2572
chaviw98318de2021-05-19 16:45:23 -05002573bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 const InjectionState* injectionState) {
2575 if (injectionState &&
2576 (windowHandle == nullptr ||
2577 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2578 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002579 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 "owned by uid %d",
2582 injectionState->injectorPid, injectionState->injectorUid,
2583 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 } else {
2585 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
2588 return false;
2589 }
2590 return true;
2591}
2592
Robert Carrc9bf1d32020-04-13 17:21:08 -07002593/**
2594 * Indicate whether one window handle should be considered as obscuring
2595 * another window handle. We only check a few preconditions. Actually
2596 * checking the bounds is left to the caller.
2597 */
chaviw98318de2021-05-19 16:45:23 -05002598static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2599 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002600 // Compare by token so cloned layers aren't counted
2601 if (haveSameToken(windowHandle, otherHandle)) {
2602 return false;
2603 }
2604 auto info = windowHandle->getInfo();
2605 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002606 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002607 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002608 } else if (otherInfo->alpha == 0 &&
2609 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002610 // Those act as if they were invisible, so we don't need to flag them.
2611 // We do want to potentially flag touchable windows even if they have 0
2612 // opacity, since they can consume touches and alter the effects of the
2613 // user interaction (eg. apps that rely on
2614 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2615 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2616 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002617 } else if (info->ownerUid == otherInfo->ownerUid) {
2618 // If ownerUid is the same we don't generate occlusion events as there
2619 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002620 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002621 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002622 return false;
2623 } else if (otherInfo->displayId != info->displayId) {
2624 return false;
2625 }
2626 return true;
2627}
2628
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002629/**
2630 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2631 * untrusted, one should check:
2632 *
2633 * 1. If result.hasBlockingOcclusion is true.
2634 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2635 * BLOCK_UNTRUSTED.
2636 *
2637 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2638 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2639 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2640 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2641 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2642 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2643 *
2644 * If neither of those is true, then it means the touch can be allowed.
2645 */
2646InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002647 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2648 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002649 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002650 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002651 TouchOcclusionInfo info;
2652 info.hasBlockingOcclusion = false;
2653 info.obscuringOpacity = 0;
2654 info.obscuringUid = -1;
2655 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002656 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002657 if (windowHandle == otherHandle) {
2658 break; // All future windows are below us. Exit early.
2659 }
chaviw98318de2021-05-19 16:45:23 -05002660 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002661 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2662 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002663 if (DEBUG_TOUCH_OCCLUSION) {
2664 info.debugInfo.push_back(
2665 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2666 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002667 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2668 // we perform the checks below to see if the touch can be propagated or not based on the
2669 // window's touch occlusion mode
2670 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2671 info.hasBlockingOcclusion = true;
2672 info.obscuringUid = otherInfo->ownerUid;
2673 info.obscuringPackage = otherInfo->packageName;
2674 break;
2675 }
2676 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2677 uint32_t uid = otherInfo->ownerUid;
2678 float opacity =
2679 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2680 // Given windows A and B:
2681 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2682 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2683 opacityByUid[uid] = opacity;
2684 if (opacity > info.obscuringOpacity) {
2685 info.obscuringOpacity = opacity;
2686 info.obscuringUid = uid;
2687 info.obscuringPackage = otherInfo->packageName;
2688 }
2689 }
2690 }
2691 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002692 if (DEBUG_TOUCH_OCCLUSION) {
2693 info.debugInfo.push_back(
2694 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2695 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002696 return info;
2697}
2698
chaviw98318de2021-05-19 16:45:23 -05002699std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002700 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002701 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2702 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2703 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2704 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002705 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2706 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2707 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2708 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2709 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002710 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002711 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002712}
2713
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002714bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2715 if (occlusionInfo.hasBlockingOcclusion) {
2716 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2717 occlusionInfo.obscuringUid);
2718 return false;
2719 }
2720 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2721 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2722 "%.2f, maximum allowed = %.2f)",
2723 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2724 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2725 return false;
2726 }
2727 return true;
2728}
2729
chaviw98318de2021-05-19 16:45:23 -05002730bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002733 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2734 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002735 if (windowHandle == otherHandle) {
2736 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 }
chaviw98318de2021-05-19 16:45:23 -05002738 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002739 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002740 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 return true;
2742 }
2743 }
2744 return false;
2745}
2746
chaviw98318de2021-05-19 16:45:23 -05002747bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002748 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002749 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2750 const WindowInfo* windowInfo = windowHandle->getInfo();
2751 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002752 if (windowHandle == otherHandle) {
2753 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002754 }
chaviw98318de2021-05-19 16:45:23 -05002755 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002756 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002757 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002758 return true;
2759 }
2760 }
2761 return false;
2762}
2763
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002764std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002765 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002766 if (applicationHandle != nullptr) {
2767 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002768 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 } else {
2770 return applicationHandle->getName();
2771 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002772 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002773 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002775 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 }
2777}
2778
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002779void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002780 if (!isUserActivityEvent(eventEntry)) {
2781 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002782 return;
2783 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002784 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002785 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002786 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002787 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002788 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002789 if (DEBUG_DISPATCH_CYCLE) {
2790 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 return;
2793 }
2794 }
2795
2796 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002797 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002798 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2800 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 return;
2802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002804 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 eventType = USER_ACTIVITY_EVENT_TOUCH;
2806 }
2807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002809 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002810 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2811 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 return;
2813 }
2814 eventType = USER_ACTIVITY_EVENT_BUTTON;
2815 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002817 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002818 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002819 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002820 break;
2821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
2823
Prabir Pradhancef936d2021-07-21 16:17:52 +00002824 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2825 REQUIRES(mLock) {
2826 scoped_unlock unlock(mLock);
2827 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2828 };
2829 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830}
2831
2832void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002834 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002835 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002836 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002838 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002839 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002840 ATRACE_NAME(message.c_str());
2841 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002842 if (DEBUG_DISPATCH_CYCLE) {
2843 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2844 "globalScaleFactor=%f, pointerIds=0x%x %s",
2845 connection->getInputChannelName().c_str(), inputTarget.flags,
2846 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2847 inputTarget.getPointerInfoString().c_str());
2848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
2850 // Skip this event if the connection status is not normal.
2851 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002852 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002853 if (DEBUG_DISPATCH_CYCLE) {
2854 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002855 connection->getInputChannelName().c_str(),
2856 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 return;
2859 }
2860
2861 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002862 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2863 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2864 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002865 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002867 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002868 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002869 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002870 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 if (!splitMotionEntry) {
2872 return; // split event was dropped
2873 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002874 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2875 std::string reason = std::string("reason=pointer cancel on split window");
2876 android_log_event_list(LOGTAG_INPUT_CANCEL)
2877 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2878 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002879 if (DEBUG_FOCUS) {
2880 ALOGD("channel '%s' ~ Split motion event.",
2881 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002882 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002883 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002884 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2885 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 return;
2887 }
2888 }
2889
2890 // Not splitting. Enqueue dispatch entries for the event as is.
2891 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2892}
2893
2894void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002896 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002897 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002898 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002900 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002901 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002902 ATRACE_NAME(message.c_str());
2903 }
2904
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002905 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906
2907 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002908 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002910 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002912 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002914 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002916 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002918 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
2921 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002922 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 startDispatchCycleLocked(currentTime, connection);
2924 }
2925}
2926
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002928 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002929 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002931 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2933 connection->getInputChannelName().c_str(),
2934 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002935 ATRACE_NAME(message.c_str());
2936 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002937 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 if (!(inputTargetFlags & dispatchMode)) {
2939 return;
2940 }
2941 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2942
2943 // This is a new event.
2944 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002945 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002946 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002948 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2949 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002950 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002953 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002955 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 dispatchEntry->resolvedAction = keyEntry.action;
2957 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2960 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002961 if (DEBUG_DISPATCH_CYCLE) {
2962 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2963 "event",
2964 connection->getInputChannelName().c_str());
2965 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 return; // skip the inconsistent event
2967 }
2968 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002971 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002972 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002973 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2974 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2975 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2976 static_cast<int32_t>(IdGenerator::Source::OTHER);
2977 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2979 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2980 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2981 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2982 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2984 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2985 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2986 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2987 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2988 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002989 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002990 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 }
2992 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002993 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2994 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002995 if (DEBUG_DISPATCH_CYCLE) {
2996 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2997 "enter event",
2998 connection->getInputChannelName().c_str());
2999 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003000 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3001 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003005 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3007 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3008 }
3009 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3010 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3014 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003015 if (DEBUG_DISPATCH_CYCLE) {
3016 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3017 "event",
3018 connection->getInputChannelName().c_str());
3019 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003020 return; // skip the inconsistent event
3021 }
3022
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003023 dispatchEntry->resolvedEventId =
3024 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3025 ? mIdGenerator.nextId()
3026 : motionEntry.id;
3027 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3028 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3029 ") to MotionEvent(id=0x%" PRIx32 ").",
3030 motionEntry.id, dispatchEntry->resolvedEventId);
3031 ATRACE_NAME(message.c_str());
3032 }
3033
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003034 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3035 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3036 // Skip reporting pointer down outside focus to the policy.
3037 break;
3038 }
3039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003041 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042
3043 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003045 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003046 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003047 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3048 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003049 break;
3050 }
Chris Yef59a2f42020-10-16 12:55:26 -07003051 case EventEntry::Type::SENSOR: {
3052 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3053 break;
3054 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003055 case EventEntry::Type::CONFIGURATION_CHANGED:
3056 case EventEntry::Type::DEVICE_RESET: {
3057 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003058 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003059 break;
3060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 }
3062
3063 // Remember that we are waiting for this dispatch to complete.
3064 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003065 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 }
3067
3068 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003069 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003070 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003071}
3072
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003073/**
3074 * This function is purely for debugging. It helps us understand where the user interaction
3075 * was taking place. For example, if user is touching launcher, we will see a log that user
3076 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3077 * We will see both launcher and wallpaper in that list.
3078 * Once the interaction with a particular set of connections starts, no new logs will be printed
3079 * until the set of interacted connections changes.
3080 *
3081 * The following items are skipped, to reduce the logspam:
3082 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3083 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3084 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3085 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3086 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003087 */
3088void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3089 const std::vector<InputTarget>& targets) {
3090 // Skip ACTION_UP events, and all events other than keys and motions
3091 if (entry.type == EventEntry::Type::KEY) {
3092 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3093 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3094 return;
3095 }
3096 } else if (entry.type == EventEntry::Type::MOTION) {
3097 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3098 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3099 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3100 return;
3101 }
3102 } else {
3103 return; // Not a key or a motion
3104 }
3105
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003106 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003107 std::vector<sp<Connection>> newConnections;
3108 for (const InputTarget& target : targets) {
3109 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3110 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3111 continue; // Skip windows that receive ACTION_OUTSIDE
3112 }
3113
3114 sp<IBinder> token = target.inputChannel->getConnectionToken();
3115 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003116 if (connection == nullptr) {
3117 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003118 }
3119 newConnectionTokens.insert(std::move(token));
3120 newConnections.emplace_back(connection);
3121 }
3122 if (newConnectionTokens == mInteractionConnectionTokens) {
3123 return; // no change
3124 }
3125 mInteractionConnectionTokens = newConnectionTokens;
3126
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003127 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003128 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003129 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003130 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003131 std::string message = "Interaction with: " + targetList;
3132 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003133 message += "<none>";
3134 }
3135 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3136}
3137
chaviwfd6d3512019-03-25 13:23:49 -07003138void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003139 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003140 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003141 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3142 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003143 return;
3144 }
3145
Vishnu Nairc519ff72021-01-21 08:23:08 -08003146 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003147 if (focusedToken == token) {
3148 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003149 return;
3150 }
3151
Prabir Pradhancef936d2021-07-21 16:17:52 +00003152 auto command = [this, token]() REQUIRES(mLock) {
3153 scoped_unlock unlock(mLock);
3154 mPolicy->onPointerDownOutsideFocus(token);
3155 };
3156 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157}
3158
3159void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003161 if (ATRACE_ENABLED()) {
3162 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003164 ATRACE_NAME(message.c_str());
3165 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003166 if (DEBUG_DISPATCH_CYCLE) {
3167 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003170 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003171 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003173 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003174 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175
3176 // Publish the event.
3177 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003178 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3179 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003180 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3182 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 status = connection->inputPublisher
3186 .publishKeyEvent(dispatchEntry->seq,
3187 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3188 keyEntry.source, keyEntry.displayId,
3189 std::move(hmac), dispatchEntry->resolvedAction,
3190 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3191 keyEntry.scanCode, keyEntry.metaState,
3192 keyEntry.repeatCount, keyEntry.downTime,
3193 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 }
3196
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003197 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003198 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003201 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202
chaviw82357092020-01-28 13:13:06 -08003203 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3206 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003207 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003208 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3209 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003210 // Don't apply window scale here since we don't want scale to affect raw
3211 // coordinates. The scale will be sent back to the client and applied
3212 // later when requesting relative coordinates.
3213 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3214 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 }
3216 usingCoords = scaledCoords;
3217 }
3218 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 // We don't want the dispatch target to know.
3220 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003221 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 scaledCoords[i].clear();
3223 }
3224 usingCoords = scaledCoords;
3225 }
3226 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003228 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229
3230 // Publish the motion event.
3231 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003232 .publishMotionEvent(dispatchEntry->seq,
3233 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 motionEntry.deviceId, motionEntry.source,
3235 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 motionEntry.edgeFlags, motionEntry.metaState,
3240 motionEntry.buttonState,
3241 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003242 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003243 motionEntry.xPrecision, motionEntry.yPrecision,
3244 motionEntry.xCursorPosition,
3245 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003246 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 motionEntry.downTime, motionEntry.eventTime,
3248 motionEntry.pointerCount,
3249 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 break;
3251 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003252
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003253 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003254 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003255 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003257 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003258 break;
3259 }
3260
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003261 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3262 const TouchModeEntry& touchModeEntry =
3263 static_cast<const TouchModeEntry&>(eventEntry);
3264 status = connection->inputPublisher
3265 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3266 touchModeEntry.inTouchMode);
3267
3268 break;
3269 }
3270
Prabir Pradhan99987712020-11-10 18:43:05 -08003271 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3272 const auto& captureEntry =
3273 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3274 status = connection->inputPublisher
3275 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003276 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003277 break;
3278 }
3279
arthurhungb89ccb02020-12-30 16:19:01 +08003280 case EventEntry::Type::DRAG: {
3281 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3282 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3283 dragEntry.id, dragEntry.x,
3284 dragEntry.y,
3285 dragEntry.isExiting);
3286 break;
3287 }
3288
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003289 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003290 case EventEntry::Type::DEVICE_RESET:
3291 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003292 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003293 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
3297
3298 // Check the result.
3299 if (status) {
3300 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003301 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303 "This is unexpected because the wait queue is empty, so the pipe "
3304 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003305 "event to it, status=%s(%d)",
3306 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3307 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3309 } else {
3310 // Pipe is full and we are waiting for the app to finish process some events
3311 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003312 if (DEBUG_DISPATCH_CYCLE) {
3313 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3314 "waiting for the application to catch up",
3315 connection->getInputChannelName().c_str());
3316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 }
3318 } else {
3319 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003320 "status=%s(%d)",
3321 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3322 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3324 }
3325 return;
3326 }
3327
3328 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003329 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3330 connection->outboundQueue.end(),
3331 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003332 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003334 if (connection->responsive) {
3335 mAnrTracker.insert(dispatchEntry->timeoutTime,
3336 connection->inputChannel->getConnectionToken());
3337 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003338 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 }
3340}
3341
chaviw09c8d2d2020-08-24 15:48:26 -07003342std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3343 size_t size;
3344 switch (event.type) {
3345 case VerifiedInputEvent::Type::KEY: {
3346 size = sizeof(VerifiedKeyEvent);
3347 break;
3348 }
3349 case VerifiedInputEvent::Type::MOTION: {
3350 size = sizeof(VerifiedMotionEvent);
3351 break;
3352 }
3353 }
3354 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3355 return mHmacKeyManager.sign(start, size);
3356}
3357
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003358const std::array<uint8_t, 32> InputDispatcher::getSignature(
3359 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003360 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3361 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003362 // Only sign events up and down events as the purely move events
3363 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003364 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003365 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003366
3367 VerifiedMotionEvent verifiedEvent =
3368 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3369 verifiedEvent.actionMasked = actionMasked;
3370 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3371 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003372}
3373
3374const std::array<uint8_t, 32> InputDispatcher::getSignature(
3375 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3376 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3377 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3378 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003379 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003380}
3381
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003384 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003385 if (DEBUG_DISPATCH_CYCLE) {
3386 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3387 connection->getInputChannelName().c_str(), seq, toString(handled));
3388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003390 if (connection->status == Connection::Status::BROKEN ||
3391 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 return;
3393 }
3394
3395 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003396 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3397 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3398 };
3399 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400}
3401
3402void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 const sp<Connection>& connection,
3404 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003405 if (DEBUG_DISPATCH_CYCLE) {
3406 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3407 connection->getInputChannelName().c_str(), toString(notify));
3408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409
3410 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003411 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003412 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003413 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415
3416 // The connection appears to be unrecoverably broken.
3417 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003418 if (connection->status == Connection::Status::NORMAL) {
3419 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420
3421 if (notify) {
3422 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003423 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3424 connection->getInputChannelName().c_str());
3425
3426 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003427 scoped_unlock unlock(mLock);
3428 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3429 };
3430 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 }
3432 }
3433}
3434
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003435void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3436 while (!queue.empty()) {
3437 DispatchEntry* dispatchEntry = queue.front();
3438 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003439 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 }
3441}
3442
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003443void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003445 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 }
3447 delete dispatchEntry;
3448}
3449
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003450int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3451 std::scoped_lock _l(mLock);
3452 sp<Connection> connection = getConnectionLocked(connectionToken);
3453 if (connection == nullptr) {
3454 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3455 connectionToken.get(), events);
3456 return 0; // remove the callback
3457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003459 bool notify;
3460 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3461 if (!(events & ALOOPER_EVENT_INPUT)) {
3462 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3463 "events=0x%x",
3464 connection->getInputChannelName().c_str(), events);
3465 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 }
3467
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003468 nsecs_t currentTime = now();
3469 bool gotOne = false;
3470 status_t status = OK;
3471 for (;;) {
3472 Result<InputPublisher::ConsumerResponse> result =
3473 connection->inputPublisher.receiveConsumerResponse();
3474 if (!result.ok()) {
3475 status = result.error().code();
3476 break;
3477 }
3478
3479 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3480 const InputPublisher::Finished& finish =
3481 std::get<InputPublisher::Finished>(*result);
3482 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3483 finish.consumeTime);
3484 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003485 if (shouldReportMetricsForConnection(*connection)) {
3486 const InputPublisher::Timeline& timeline =
3487 std::get<InputPublisher::Timeline>(*result);
3488 mLatencyTracker
3489 .trackGraphicsLatency(timeline.inputEventId,
3490 connection->inputChannel->getConnectionToken(),
3491 std::move(timeline.graphicsTimeline));
3492 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003493 }
3494 gotOne = true;
3495 }
3496 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003497 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003498 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 return 1;
3500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 }
3502
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003503 notify = status != DEAD_OBJECT || !connection->monitor;
3504 if (notify) {
3505 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3506 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3507 status);
3508 }
3509 } else {
3510 // Monitor channels are never explicitly unregistered.
3511 // We do it automatically when the remote endpoint is closed so don't warn about them.
3512 const bool stillHaveWindowHandle =
3513 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3514 notify = !connection->monitor && stillHaveWindowHandle;
3515 if (notify) {
3516 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3517 connection->getInputChannelName().c_str(), events);
3518 }
3519 }
3520
3521 // Remove the channel.
3522 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3523 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524}
3525
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003526void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003528 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003529 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 }
3531}
3532
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003533void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003534 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003535 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003536 for (const Monitor& monitor : monitors) {
3537 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003538 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003539 }
3540}
3541
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003543 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003544 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003545 if (connection == nullptr) {
3546 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003548
3549 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550}
3551
3552void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3553 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003554 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 return;
3556 }
3557
3558 nsecs_t currentTime = now();
3559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003560 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003561 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003563 if (cancelationEvents.empty()) {
3564 return;
3565 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003566 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3567 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3568 "with reality: %s, mode=%d.",
3569 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3570 options.mode);
3571 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003572
Arthur Hungb3307ee2021-10-14 10:57:37 +00003573 std::string reason = std::string("reason=").append(options.reason);
3574 android_log_event_list(LOGTAG_INPUT_CANCEL)
3575 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3576
Svet Ganov5d3bc372020-01-26 23:11:07 -08003577 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003578 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003579 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3580 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003581 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003582 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003583 target.globalScaleFactor = windowInfo->globalScaleFactor;
3584 }
3585 target.inputChannel = connection->inputChannel;
3586 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3587
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003588 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003590 switch (cancelationEventEntry->type) {
3591 case EventEntry::Type::KEY: {
3592 logOutboundKeyDetails("cancel - ",
3593 static_cast<const KeyEntry&>(*cancelationEventEntry));
3594 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003596 case EventEntry::Type::MOTION: {
3597 logOutboundMotionDetails("cancel - ",
3598 static_cast<const MotionEntry&>(*cancelationEventEntry));
3599 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003601 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003602 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003603 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3604 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003605 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003606 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003607 break;
3608 }
3609 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003610 case EventEntry::Type::DEVICE_RESET:
3611 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003612 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003613 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003614 break;
3615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003618 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3619 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003621
3622 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623}
3624
Svet Ganov5d3bc372020-01-26 23:11:07 -08003625void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3626 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003627 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003628 return;
3629 }
3630
3631 nsecs_t currentTime = now();
3632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003633 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003634 connection->inputState.synthesizePointerDownEvents(currentTime);
3635
3636 if (downEvents.empty()) {
3637 return;
3638 }
3639
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003640 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003641 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3642 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003643 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003644
3645 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003646 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003647 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3648 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003649 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003650 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003651 target.globalScaleFactor = windowInfo->globalScaleFactor;
3652 }
3653 target.inputChannel = connection->inputChannel;
3654 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3655
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003656 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003657 switch (downEventEntry->type) {
3658 case EventEntry::Type::MOTION: {
3659 logOutboundMotionDetails("down - ",
3660 static_cast<const MotionEntry&>(*downEventEntry));
3661 break;
3662 }
3663
3664 case EventEntry::Type::KEY:
3665 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003666 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003667 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003668 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003669 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003670 case EventEntry::Type::SENSOR:
3671 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003672 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003673 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003674 break;
3675 }
3676 }
3677
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003678 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3679 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003680 }
3681
3682 startDispatchCycleLocked(currentTime, connection);
3683}
3684
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003685std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3686 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 ALOG_ASSERT(pointerIds.value != 0);
3688
3689 uint32_t splitPointerIndexMap[MAX_POINTERS];
3690 PointerProperties splitPointerProperties[MAX_POINTERS];
3691 PointerCoords splitPointerCoords[MAX_POINTERS];
3692
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003693 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 uint32_t splitPointerCount = 0;
3695
3696 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003699 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 uint32_t pointerId = uint32_t(pointerProperties.id);
3701 if (pointerIds.hasBit(pointerId)) {
3702 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3703 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3704 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003705 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 splitPointerCount += 1;
3707 }
3708 }
3709
3710 if (splitPointerCount != pointerIds.count()) {
3711 // This is bad. We are missing some of the pointers that we expected to deliver.
3712 // Most likely this indicates that we received an ACTION_MOVE events that has
3713 // different pointer ids than we expected based on the previous ACTION_DOWN
3714 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3715 // in this way.
3716 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003717 "we expected there to be %d pointers. This probably means we received "
3718 "a broken sequence of pointer ids from the input device.",
3719 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003720 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 }
3722
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003723 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003725 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3726 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3728 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003729 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 uint32_t pointerId = uint32_t(pointerProperties.id);
3731 if (pointerIds.hasBit(pointerId)) {
3732 if (pointerIds.count() == 1) {
3733 // The first/last pointer went down/up.
3734 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003736 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3737 ? AMOTION_EVENT_ACTION_CANCEL
3738 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 } else {
3740 // A secondary pointer went down/up.
3741 uint32_t splitPointerIndex = 0;
3742 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3743 splitPointerIndex += 1;
3744 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003745 action = maskedAction |
3746 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 }
3748 } else {
3749 // An unrelated pointer changed.
3750 action = AMOTION_EVENT_ACTION_MOVE;
3751 }
3752 }
3753
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003754 int32_t newId = mIdGenerator.nextId();
3755 if (ATRACE_ENABLED()) {
3756 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3757 ") to MotionEvent(id=0x%" PRIx32 ").",
3758 originalMotionEntry.id, newId);
3759 ATRACE_NAME(message.c_str());
3760 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003761 std::unique_ptr<MotionEntry> splitMotionEntry =
3762 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3763 originalMotionEntry.deviceId, originalMotionEntry.source,
3764 originalMotionEntry.displayId,
3765 originalMotionEntry.policyFlags, action,
3766 originalMotionEntry.actionButton,
3767 originalMotionEntry.flags, originalMotionEntry.metaState,
3768 originalMotionEntry.buttonState,
3769 originalMotionEntry.classification,
3770 originalMotionEntry.edgeFlags,
3771 originalMotionEntry.xPrecision,
3772 originalMotionEntry.yPrecision,
3773 originalMotionEntry.xCursorPosition,
3774 originalMotionEntry.yCursorPosition,
3775 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003776 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003778 if (originalMotionEntry.injectionState) {
3779 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 splitMotionEntry->injectionState->refCount += 1;
3781 }
3782
3783 return splitMotionEntry;
3784}
3785
3786void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003787 if (DEBUG_INBOUND_EVENT_DETAILS) {
3788 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790
Antonio Kantekf16f2832021-09-28 04:39:20 +00003791 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003793 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003795 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3796 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3797 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 } // release lock
3799
3800 if (needWake) {
3801 mLooper->wake();
3802 }
3803}
3804
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003805/**
3806 * If one of the meta shortcuts is detected, process them here:
3807 * Meta + Backspace -> generate BACK
3808 * Meta + Enter -> generate HOME
3809 * This will potentially overwrite keyCode and metaState.
3810 */
3811void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003812 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003813 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3814 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3815 if (keyCode == AKEYCODE_DEL) {
3816 newKeyCode = AKEYCODE_BACK;
3817 } else if (keyCode == AKEYCODE_ENTER) {
3818 newKeyCode = AKEYCODE_HOME;
3819 }
3820 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003821 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003822 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003823 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003824 keyCode = newKeyCode;
3825 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3826 }
3827 } else if (action == AKEY_EVENT_ACTION_UP) {
3828 // In order to maintain a consistent stream of up and down events, check to see if the key
3829 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3830 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003831 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003832 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003833 auto replacementIt = mReplacedKeys.find(replacement);
3834 if (replacementIt != mReplacedKeys.end()) {
3835 keyCode = replacementIt->second;
3836 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003837 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3838 }
3839 }
3840}
3841
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003843 if (DEBUG_INBOUND_EVENT_DETAILS) {
3844 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3845 "policyFlags=0x%x, action=0x%x, "
3846 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3847 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3848 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3849 args->downTime);
3850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 if (!validateKeyEvent(args->action)) {
3852 return;
3853 }
3854
3855 uint32_t policyFlags = args->policyFlags;
3856 int32_t flags = args->flags;
3857 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003858 // InputDispatcher tracks and generates key repeats on behalf of
3859 // whatever notifies it, so repeatCount should always be set to 0
3860 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3862 policyFlags |= POLICY_FLAG_VIRTUAL;
3863 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 if (policyFlags & POLICY_FLAG_FUNCTION) {
3866 metaState |= AMETA_FUNCTION_ON;
3867 }
3868
3869 policyFlags |= POLICY_FLAG_TRUSTED;
3870
Michael Wright78f24442014-08-06 15:55:28 -07003871 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003872 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003873
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003875 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003876 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3877 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
Michael Wright2b3c3302018-03-02 17:19:13 +00003879 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003881 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3882 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003883 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
Antonio Kantekf16f2832021-09-28 04:39:20 +00003886 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 { // acquire lock
3888 mLock.lock();
3889
3890 if (shouldSendKeyToInputFilterLocked(args)) {
3891 mLock.unlock();
3892
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003893 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3895 return; // event was consumed by the filter
3896 }
3897
3898 mLock.lock();
3899 }
3900
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003901 std::unique_ptr<KeyEntry> newEntry =
3902 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3903 args->displayId, policyFlags, args->action, flags,
3904 keyCode, args->scanCode, metaState, repeatCount,
3905 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003907 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 mLock.unlock();
3909 } // release lock
3910
3911 if (needWake) {
3912 mLooper->wake();
3913 }
3914}
3915
3916bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3917 return mInputFilterEnabled;
3918}
3919
3920void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003921 if (DEBUG_INBOUND_EVENT_DETAILS) {
3922 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3923 "displayId=%" PRId32 ", policyFlags=0x%x, "
3924 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3925 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3926 "yCursorPosition=%f, downTime=%" PRId64,
3927 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3928 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3929 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3930 args->xCursorPosition, args->yCursorPosition, args->downTime);
3931 for (uint32_t i = 0; i < args->pointerCount; i++) {
3932 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3933 "x=%f, y=%f, pressure=%f, size=%f, "
3934 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3935 "orientation=%f",
3936 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3937 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3938 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3939 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3940 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3941 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3942 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3943 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3944 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3945 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003948 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3949 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 return;
3951 }
3952
3953 uint32_t policyFlags = args->policyFlags;
3954 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003955
3956 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003957 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003958 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3959 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Antonio Kantekf16f2832021-09-28 04:39:20 +00003963 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 { // acquire lock
3965 mLock.lock();
3966
3967 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003968 ui::Transform displayTransform;
3969 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3970 displayTransform = it->second.transform;
3971 }
3972
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 mLock.unlock();
3974
3975 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003976 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3977 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003978 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003979 displayTransform, args->xPrecision, args->yPrecision,
3980 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003981 args->downTime, args->eventTime, args->pointerCount,
3982 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983
3984 policyFlags |= POLICY_FLAG_FILTERED;
3985 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3986 return; // event was consumed by the filter
3987 }
3988
3989 mLock.lock();
3990 }
3991
3992 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003993 std::unique_ptr<MotionEntry> newEntry =
3994 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3995 args->source, args->displayId, policyFlags,
3996 args->action, args->actionButton, args->flags,
3997 args->metaState, args->buttonState,
3998 args->classification, args->edgeFlags,
3999 args->xPrecision, args->yPrecision,
4000 args->xCursorPosition, args->yCursorPosition,
4001 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004002 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004004 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4005 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4006 !mInputFilterEnabled) {
4007 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4008 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4009 }
4010
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004011 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 mLock.unlock();
4013 } // release lock
4014
4015 if (needWake) {
4016 mLooper->wake();
4017 }
4018}
4019
Chris Yef59a2f42020-10-16 12:55:26 -07004020void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 if (DEBUG_INBOUND_EVENT_DETAILS) {
4022 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4023 " sensorType=%s",
4024 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004025 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004026 }
Chris Yef59a2f42020-10-16 12:55:26 -07004027
Antonio Kantekf16f2832021-09-28 04:39:20 +00004028 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004029 { // acquire lock
4030 mLock.lock();
4031
4032 // Just enqueue a new sensor event.
4033 std::unique_ptr<SensorEntry> newEntry =
4034 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4035 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4036 args->sensorType, args->accuracy,
4037 args->accuracyChanged, args->values);
4038
4039 needWake = enqueueInboundEventLocked(std::move(newEntry));
4040 mLock.unlock();
4041 } // release lock
4042
4043 if (needWake) {
4044 mLooper->wake();
4045 }
4046}
4047
Chris Yefb552902021-02-03 17:18:37 -08004048void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004049 if (DEBUG_INBOUND_EVENT_DETAILS) {
4050 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4051 args->deviceId, args->isOn);
4052 }
Chris Yefb552902021-02-03 17:18:37 -08004053 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4054}
4055
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004057 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058}
4059
4060void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004061 if (DEBUG_INBOUND_EVENT_DETAILS) {
4062 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4063 "switchMask=0x%08x",
4064 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
4067 uint32_t policyFlags = args->policyFlags;
4068 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004069 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070}
4071
4072void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004073 if (DEBUG_INBOUND_EVENT_DETAILS) {
4074 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4075 args->deviceId);
4076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Antonio Kantekf16f2832021-09-28 04:39:20 +00004078 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004080 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004082 std::unique_ptr<DeviceResetEntry> newEntry =
4083 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4084 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 } // release lock
4086
4087 if (needWake) {
4088 mLooper->wake();
4089 }
4090}
4091
Prabir Pradhan7e186182020-11-10 13:56:45 -08004092void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 if (DEBUG_INBOUND_EVENT_DETAILS) {
4094 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004095 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004096 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004097
Antonio Kantekf16f2832021-09-28 04:39:20 +00004098 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004099 { // acquire lock
4100 std::scoped_lock _l(mLock);
4101 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004102 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004103 needWake = enqueueInboundEventLocked(std::move(entry));
4104 } // release lock
4105
4106 if (needWake) {
4107 mLooper->wake();
4108 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004109}
4110
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004111InputEventInjectionResult InputDispatcher::injectInputEvent(
4112 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4113 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004114 if (DEBUG_INBOUND_EVENT_DETAILS) {
4115 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4116 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4117 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4118 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004119 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
4121 policyFlags |= POLICY_FLAG_INJECTED;
4122 if (hasInjectionPermission(injectorPid, injectorUid)) {
4123 policyFlags |= POLICY_FLAG_TRUSTED;
4124 }
4125
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004126 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004127 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4128 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4129 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4130 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4131 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004132 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004133 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004134 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004135 }
4136
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004137 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004139 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004140 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4141 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004143 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004146 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004147 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4148 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4149 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004150 int32_t keyCode = incomingKey.getKeyCode();
4151 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004152 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004154 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004155 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004156 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4157 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4158 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4161 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004162 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163
4164 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4165 android::base::Timer t;
4166 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4167 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4168 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4169 std::to_string(t.duration().count()).c_str());
4170 }
4171 }
4172
4173 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004174 std::unique_ptr<KeyEntry> injectedEntry =
4175 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004177 incomingKey.getDisplayId(), policyFlags, action,
4178 flags, keyCode, incomingKey.getScanCode(), metaState,
4179 incomingKey.getRepeatCount(),
4180 incomingKey.getDownTime());
4181 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004182 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 }
4184
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004186 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004187 const int32_t action = motionEvent.getAction();
4188 const bool isPointerEvent =
4189 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4190 // If a pointer event has no displayId specified, inject it to the default display.
4191 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4192 ? ADISPLAY_ID_DEFAULT
4193 : event->getDisplayId();
4194 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004195 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004196 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004197 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004198 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004199 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 }
4201
4202 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004203 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 android::base::Timer t;
4205 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4206 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4207 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4208 std::to_string(t.duration().count()).c_str());
4209 }
4210 }
4211
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004212 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4213 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4214 }
4215
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004217 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4218 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004219 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4221 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004222 displayId, policyFlags, action, actionButton,
4223 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 motionEvent.getButtonState(),
4225 motionEvent.getClassification(),
4226 motionEvent.getEdgeFlags(),
4227 motionEvent.getXPrecision(),
4228 motionEvent.getYPrecision(),
4229 motionEvent.getRawXCursorPosition(),
4230 motionEvent.getRawYCursorPosition(),
4231 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004232 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004233 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004234 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 sampleEventTimes += 1;
4237 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4240 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004241 displayId, policyFlags, action, actionButton,
4242 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 motionEvent.getButtonState(),
4244 motionEvent.getClassification(),
4245 motionEvent.getEdgeFlags(),
4246 motionEvent.getXPrecision(),
4247 motionEvent.getYPrecision(),
4248 motionEvent.getRawXCursorPosition(),
4249 motionEvent.getRawYCursorPosition(),
4250 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004251 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004252 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004253 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4254 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004255 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004256 }
4257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004261 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004262 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
4264
4265 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 injectionState->injectionIsAsync = true;
4268 }
4269
4270 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004271 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272
4273 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004274 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004275 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004276 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
4279 mLock.unlock();
4280
4281 if (needWake) {
4282 mLooper->wake();
4283 }
4284
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004285 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004287 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004289 if (syncMode == InputEventInjectionSync::NONE) {
4290 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 } else {
4292 for (;;) {
4293 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004294 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 break;
4296 }
4297
4298 nsecs_t remainingTimeout = endTime - now();
4299 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004300 if (DEBUG_INJECTION) {
4301 ALOGD("injectInputEvent - Timed out waiting for injection result "
4302 "to become available.");
4303 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004304 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 break;
4306 }
4307
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004308 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 }
4310
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004311 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4312 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004314 if (DEBUG_INJECTION) {
4315 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4316 injectionState->pendingForegroundDispatches);
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 nsecs_t remainingTimeout = endTime - now();
4319 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004320 if (DEBUG_INJECTION) {
4321 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4322 "dispatches to finish.");
4323 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004324 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 break;
4326 }
4327
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004328 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 }
4330 }
4331 }
4332
4333 injectionState->release();
4334 } // release lock
4335
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004336 if (DEBUG_INJECTION) {
4337 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4338 injectionResult, injectorPid, injectorUid);
4339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340
4341 return injectionResult;
4342}
4343
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004344std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004345 std::array<uint8_t, 32> calculatedHmac;
4346 std::unique_ptr<VerifiedInputEvent> result;
4347 switch (event.getType()) {
4348 case AINPUT_EVENT_TYPE_KEY: {
4349 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4350 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4351 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004352 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004353 break;
4354 }
4355 case AINPUT_EVENT_TYPE_MOTION: {
4356 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4357 VerifiedMotionEvent verifiedMotionEvent =
4358 verifiedMotionEventFromMotionEvent(motionEvent);
4359 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004360 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004361 break;
4362 }
4363 default: {
4364 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4365 return nullptr;
4366 }
4367 }
4368 if (calculatedHmac == INVALID_HMAC) {
4369 return nullptr;
4370 }
4371 if (calculatedHmac != event.getHmac()) {
4372 return nullptr;
4373 }
4374 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004375}
4376
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004378 return injectorUid == 0 ||
4379 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380}
4381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004384 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004386 if (DEBUG_INJECTION) {
4387 ALOGD("Setting input event injection result to %d. "
4388 "injectorPid=%d, injectorUid=%d",
4389 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004392 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 // Log the outcome since the injector did not wait for the injection result.
4394 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004396 ALOGV("Asynchronous input event injection succeeded.");
4397 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004398 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 ALOGW("Asynchronous input event injection failed.");
4400 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004402 ALOGW("Asynchronous input event injection permission denied.");
4403 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 ALOGW("Asynchronous input event injection timed out.");
4406 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 case InputEventInjectionResult::PENDING:
4408 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4409 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 }
4411 }
4412
4413 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004414 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 }
4416}
4417
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004418void InputDispatcher::transformMotionEntryForInjectionLocked(
4419 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004420 // Input injection works in the logical display coordinate space, but the input pipeline works
4421 // display space, so we need to transform the injected events accordingly.
4422 const auto it = mDisplayInfos.find(entry.displayId);
4423 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004424 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004425
4426 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004427 entry.pointerCoords[i] =
4428 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4429 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004430 }
4431}
4432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004433void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4434 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 if (injectionState) {
4436 injectionState->pendingForegroundDispatches += 1;
4437 }
4438}
4439
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004440void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4441 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 if (injectionState) {
4443 injectionState->pendingForegroundDispatches -= 1;
4444
4445 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004446 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 }
4448 }
4449}
4450
chaviw98318de2021-05-19 16:45:23 -05004451const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004452 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004453 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004454 auto it = mWindowHandlesByDisplay.find(displayId);
4455 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004456}
4457
chaviw98318de2021-05-19 16:45:23 -05004458sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004459 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004460 if (windowHandleToken == nullptr) {
4461 return nullptr;
4462 }
4463
Arthur Hungb92218b2018-08-14 12:00:21 +08004464 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004465 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4466 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004467 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004468 return windowHandle;
4469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 }
4471 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004472 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473}
4474
chaviw98318de2021-05-19 16:45:23 -05004475sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4476 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004477 if (windowHandleToken == nullptr) {
4478 return nullptr;
4479 }
4480
chaviw98318de2021-05-19 16:45:23 -05004481 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004482 if (windowHandle->getToken() == windowHandleToken) {
4483 return windowHandle;
4484 }
4485 }
4486 return nullptr;
4487}
4488
chaviw98318de2021-05-19 16:45:23 -05004489sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4490 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004491 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004492 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4493 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004494 if (handle->getId() == windowHandle->getId() &&
4495 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004496 if (windowHandle->getInfo()->displayId != it.first) {
4497 ALOGE("Found window %s in display %" PRId32
4498 ", but it should belong to display %" PRId32,
4499 windowHandle->getName().c_str(), it.first,
4500 windowHandle->getInfo()->displayId);
4501 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004502 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 }
4505 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004506 return nullptr;
4507}
4508
chaviw98318de2021-05-19 16:45:23 -05004509sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004510 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4511 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512}
4513
chaviw98318de2021-05-19 16:45:23 -05004514bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004515 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4516 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004517 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004518 if (connection != nullptr && noInputChannel) {
4519 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4520 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4521 return false;
4522 }
4523
4524 if (connection == nullptr) {
4525 if (!noInputChannel) {
4526 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4527 }
4528 return false;
4529 }
4530 if (!connection->responsive) {
4531 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4532 return false;
4533 }
4534 return true;
4535}
4536
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004537std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4538 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004539 auto connectionIt = mConnectionsByToken.find(token);
4540 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004541 return nullptr;
4542 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004543 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004544}
4545
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004546void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004547 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4548 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004549 // Remove all handles on a display if there are no windows left.
4550 mWindowHandlesByDisplay.erase(displayId);
4551 return;
4552 }
4553
4554 // Since we compare the pointer of input window handles across window updates, we need
4555 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004556 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4557 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4558 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004559 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004560 }
4561
chaviw98318de2021-05-19 16:45:23 -05004562 std::vector<sp<WindowInfoHandle>> newHandles;
4563 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004564 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004565 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004566 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004567 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004568 const bool canReceiveInput =
4569 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4570 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004571 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004572 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004573 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004574 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004575 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004576 }
4577
4578 if (info->displayId != displayId) {
4579 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4580 handle->getName().c_str(), displayId, info->displayId);
4581 continue;
4582 }
4583
Robert Carredd13602020-04-13 17:24:34 -07004584 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4585 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004586 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004587 oldHandle->updateFrom(handle);
4588 newHandles.push_back(oldHandle);
4589 } else {
4590 newHandles.push_back(handle);
4591 }
4592 }
4593
4594 // Insert or replace
4595 mWindowHandlesByDisplay[displayId] = newHandles;
4596}
4597
Arthur Hung72d8dc32020-03-28 00:48:39 +00004598void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004599 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004600 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004601 { // acquire lock
4602 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004603 for (const auto& [displayId, handles] : handlesPerDisplay) {
4604 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004605 }
4606 }
4607 // Wake up poll loop since it may need to make new input dispatching choices.
4608 mLooper->wake();
4609}
4610
Arthur Hungb92218b2018-08-14 12:00:21 +08004611/**
4612 * Called from InputManagerService, update window handle list by displayId that can receive input.
4613 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4614 * If set an empty list, remove all handles from the specific display.
4615 * For focused handle, check if need to change and send a cancel event to previous one.
4616 * For removed handle, check if need to send a cancel event if already in touch.
4617 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004618void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004619 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004620 if (DEBUG_FOCUS) {
4621 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004622 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004623 windowList += iwh->getName() + " ";
4624 }
4625 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Prabir Pradhand65552b2021-10-07 11:23:50 -07004628 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004629 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004630 const WindowInfo& info = *window->getInfo();
4631
4632 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004633 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004634 if (noInputWindow && window->getToken() != nullptr) {
4635 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4636 window->getName().c_str());
4637 window->releaseChannel();
4638 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004639
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004640 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004641 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4642 !info.inputConfig.test(
4643 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004644 "%s has feature SPY, but is not a trusted overlay.",
4645 window->getName().c_str());
4646
Prabir Pradhand65552b2021-10-07 11:23:50 -07004647 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004648 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4649 !info.inputConfig.test(
4650 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004651 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4652 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004653 }
4654
Arthur Hung72d8dc32020-03-28 00:48:39 +00004655 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004656 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004658 // Save the old windows' orientation by ID before it gets updated.
4659 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004660 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004661 oldWindowOrientations.emplace(handle->getId(),
4662 handle->getInfo()->transform.getOrientation());
4663 }
4664
chaviw98318de2021-05-19 16:45:23 -05004665 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004666
chaviw98318de2021-05-19 16:45:23 -05004667 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004668 if (mLastHoverWindowHandle &&
4669 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4670 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004671 mLastHoverWindowHandle = nullptr;
4672 }
4673
Vishnu Nairc519ff72021-01-21 08:23:08 -08004674 std::optional<FocusResolver::FocusChanges> changes =
4675 mFocusResolver.setInputWindows(displayId, windowHandles);
4676 if (changes) {
4677 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004680 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4681 mTouchStatesByDisplay.find(displayId);
4682 if (stateIt != mTouchStatesByDisplay.end()) {
4683 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004684 for (size_t i = 0; i < state.windows.size();) {
4685 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004686 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004687 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004688 ALOGD("Touched window was removed: %s in display %" PRId32,
4689 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004690 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004691 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004692 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4693 if (touchedInputChannel != nullptr) {
4694 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4695 "touched window was removed");
4696 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004697 // Since we are about to drop the touch, cancel the events for the wallpaper as
4698 // well.
4699 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004700 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4701 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004702 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4703 if (wallpaper != nullptr) {
4704 sp<Connection> wallpaperConnection =
4705 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004706 if (wallpaperConnection != nullptr) {
4707 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4708 options);
4709 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004710 }
4711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004713 state.windows.erase(state.windows.begin() + i);
4714 } else {
4715 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 }
4717 }
arthurhungb89ccb02020-12-30 16:19:01 +08004718
arthurhung6d4bed92021-03-17 11:59:33 +08004719 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004720 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004721 if (mDragState &&
4722 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004723 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004724 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004725 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004726 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004727
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004728 // Determine if the orientation of any of the input windows have changed, and cancel all
4729 // pointer events if necessary.
4730 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4731 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4732 if (newWindowHandle != nullptr &&
4733 newWindowHandle->getInfo()->transform.getOrientation() !=
4734 oldWindowOrientations[oldWindowHandle->getId()]) {
4735 std::shared_ptr<InputChannel> inputChannel =
4736 getInputChannelLocked(newWindowHandle->getToken());
4737 if (inputChannel != nullptr) {
4738 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4739 "touched window's orientation changed");
4740 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004741 }
4742 }
4743 }
4744
Arthur Hung72d8dc32020-03-28 00:48:39 +00004745 // Release information for windows that are no longer present.
4746 // This ensures that unused input channels are released promptly.
4747 // Otherwise, they might stick around until the window handle is destroyed
4748 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004749 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004750 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004751 if (DEBUG_FOCUS) {
4752 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004753 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004754 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004755 }
chaviw291d88a2019-02-14 10:33:58 -08004756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757}
4758
4759void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004760 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004761 if (DEBUG_FOCUS) {
4762 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4763 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4764 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004765 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004766 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004767 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 } // release lock
4769
4770 // Wake up poll loop since it may need to make new input dispatching choices.
4771 mLooper->wake();
4772}
4773
Vishnu Nair599f1412021-06-21 10:39:58 -07004774void InputDispatcher::setFocusedApplicationLocked(
4775 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4776 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4777 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4778
4779 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4780 return; // This application is already focused. No need to wake up or change anything.
4781 }
4782
4783 // Set the new application handle.
4784 if (inputApplicationHandle != nullptr) {
4785 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4786 } else {
4787 mFocusedApplicationHandlesByDisplay.erase(displayId);
4788 }
4789
4790 // No matter what the old focused application was, stop waiting on it because it is
4791 // no longer focused.
4792 resetNoFocusedWindowTimeoutLocked();
4793}
4794
Tiger Huang721e26f2018-07-24 22:26:19 +08004795/**
4796 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4797 * the display not specified.
4798 *
4799 * We track any unreleased events for each window. If a window loses the ability to receive the
4800 * released event, we will send a cancel event to it. So when the focused display is changed, we
4801 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4802 * display. The display-specified events won't be affected.
4803 */
4804void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 if (DEBUG_FOCUS) {
4806 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4807 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004808 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004809 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004810
4811 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004812 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004813 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004814 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004815 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004816 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004817 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004818 CancelationOptions
4819 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4820 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004821 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004822 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4823 }
4824 }
4825 mFocusedDisplayId = displayId;
4826
Chris Ye3c2d6f52020-08-09 10:39:48 -07004827 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004828 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004829 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004830
Vishnu Nairad321cd2020-08-20 16:40:21 -07004831 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004832 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004833 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004834 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004835 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004836 }
4837 }
4838 }
4839
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004840 if (DEBUG_FOCUS) {
4841 logDispatchStateLocked();
4842 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004843 } // release lock
4844
4845 // Wake up poll loop since it may need to make new input dispatching choices.
4846 mLooper->wake();
4847}
4848
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004850 if (DEBUG_FOCUS) {
4851 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853
4854 bool changed;
4855 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004856 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857
4858 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4859 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004860 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
4862
4863 if (mDispatchEnabled && !enabled) {
4864 resetAndDropEverythingLocked("dispatcher is being disabled");
4865 }
4866
4867 mDispatchEnabled = enabled;
4868 mDispatchFrozen = frozen;
4869 changed = true;
4870 } else {
4871 changed = false;
4872 }
4873
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004874 if (DEBUG_FOCUS) {
4875 logDispatchStateLocked();
4876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 } // release lock
4878
4879 if (changed) {
4880 // Wake up poll loop since it may need to make new input dispatching choices.
4881 mLooper->wake();
4882 }
4883}
4884
4885void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004886 if (DEBUG_FOCUS) {
4887 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889
4890 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004891 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892
4893 if (mInputFilterEnabled == enabled) {
4894 return;
4895 }
4896
4897 mInputFilterEnabled = enabled;
4898 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4899 } // release lock
4900
4901 // Wake up poll loop since there might be work to do to drop everything.
4902 mLooper->wake();
4903}
4904
Antonio Kantekea47acb2021-12-23 12:41:25 -08004905bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4906 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004907 bool needWake = false;
4908 {
4909 std::scoped_lock lock(mLock);
4910 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004911 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004912 }
4913 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004914 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4915 "hasPermission=%s)",
4916 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4917 }
4918 if (!hasPermission) {
4919 const sp<IBinder> focusedToken =
4920 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4921
Antonio Kantek019eb662022-02-08 13:41:52 -08004922 // TODO(b/218541064): if no window is currently focused, then we need to check the last
Antonio Kantekea47acb2021-12-23 12:41:25 -08004923 // interacted window (within 1 second timeout). We should allow touch mode change
4924 // if the last interacted window owner's pid/uid match the calling ones.
4925 if (focusedToken == nullptr) {
4926 return false;
4927 }
4928 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4929 if (windowHandle == nullptr) {
4930 return false;
4931 }
4932 const WindowInfo* windowInfo = windowHandle->getInfo();
4933 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4934 return false;
4935 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004936 }
4937
4938 // TODO(b/198499018): Store touch mode per display.
4939 mInTouchMode = inTouchMode;
4940
Antonio Kantekf16f2832021-09-28 04:39:20 +00004941 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4942 needWake = enqueueInboundEventLocked(std::move(entry));
4943 } // release lock
4944
4945 if (needWake) {
4946 mLooper->wake();
4947 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004948 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004949}
4950
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004951void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4952 if (opacity < 0 || opacity > 1) {
4953 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4954 return;
4955 }
4956
4957 std::scoped_lock lock(mLock);
4958 mMaximumObscuringOpacityForTouch = opacity;
4959}
4960
4961void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4962 std::scoped_lock lock(mLock);
4963 mBlockUntrustedTouchesMode = mode;
4964}
4965
Arthur Hungabbb9d82021-09-01 14:52:30 +00004966std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4967 const sp<IBinder>& token) {
4968 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4969 for (TouchedWindow& w : state.windows) {
4970 if (w.windowHandle->getToken() == token) {
4971 return std::make_pair(&state, &w);
4972 }
4973 }
4974 }
4975 return std::make_pair(nullptr, nullptr);
4976}
4977
arthurhungb89ccb02020-12-30 16:19:01 +08004978bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4979 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004980 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004981 if (DEBUG_FOCUS) {
4982 ALOGD("Trivial transfer to same window.");
4983 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004984 return true;
4985 }
4986
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004988 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989
Arthur Hungabbb9d82021-09-01 14:52:30 +00004990 // Find the target touch state and touched window by fromToken.
4991 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4992 if (state == nullptr || touchedWindow == nullptr) {
4993 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 return false;
4995 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004996
4997 const int32_t displayId = state->displayId;
4998 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4999 if (toWindowHandle == nullptr) {
5000 ALOGW("Cannot transfer focus because to window not found.");
5001 return false;
5002 }
5003
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005004 if (DEBUG_FOCUS) {
5005 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005006 touchedWindow->windowHandle->getName().c_str(),
5007 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009
Arthur Hungabbb9d82021-09-01 14:52:30 +00005010 // Erase old window.
5011 int32_t oldTargetFlags = touchedWindow->targetFlags;
5012 BitSet32 pointerIds = touchedWindow->pointerIds;
5013 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014
Arthur Hungabbb9d82021-09-01 14:52:30 +00005015 // Add new window.
5016 int32_t newTargetFlags = oldTargetFlags &
5017 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5018 InputTarget::FLAG_DISPATCH_AS_IS);
5019 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020
Arthur Hungabbb9d82021-09-01 14:52:30 +00005021 // Store the dragging window.
5022 if (isDragDrop) {
5023 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 }
5025
Arthur Hungabbb9d82021-09-01 14:52:30 +00005026 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005027 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5028 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005029 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005030 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005031 CancelationOptions
5032 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5033 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005035 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
5037
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005038 if (DEBUG_FOCUS) {
5039 logDispatchStateLocked();
5040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 } // release lock
5042
5043 // Wake up poll loop since it may need to make new input dispatching choices.
5044 mLooper->wake();
5045 return true;
5046}
5047
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005048// Binder call
5049bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5050 sp<IBinder> fromToken;
5051 { // acquire lock
5052 std::scoped_lock _l(mLock);
5053
Arthur Hungabbb9d82021-09-01 14:52:30 +00005054 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5055 [](const auto& pair) { return pair.second.windows.size() == 1; });
5056 if (it == mTouchStatesByDisplay.end()) {
5057 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5058 return false;
5059 }
5060 const int32_t displayId = it->first;
5061 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005062 if (toWindowHandle == nullptr) {
5063 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5064 return false;
5065 }
5066
Arthur Hungabbb9d82021-09-01 14:52:30 +00005067 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005068 const TouchedWindow& touchedWindow = state.windows[0];
5069 fromToken = touchedWindow.windowHandle->getToken();
5070 } // release lock
5071
5072 return transferTouchFocus(fromToken, destChannelToken);
5073}
5074
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005076 if (DEBUG_FOCUS) {
5077 ALOGD("Resetting and dropping all events (%s).", reason);
5078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
5080 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5081 synthesizeCancelationEventsForAllConnectionsLocked(options);
5082
5083 resetKeyRepeatLocked();
5084 releasePendingEventLocked();
5085 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005086 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005089 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005091 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092}
5093
5094void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005095 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 dumpDispatchStateLocked(dump);
5097
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005098 std::istringstream stream(dump);
5099 std::string line;
5100
5101 while (std::getline(stream, line, '\n')) {
5102 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 }
5104}
5105
Prabir Pradhan99987712020-11-10 18:43:05 -08005106std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5107 std::string dump;
5108
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005109 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5110 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005111
5112 std::string windowName = "None";
5113 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005114 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005115 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5116 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5117 : "token has capture without window";
5118 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005119 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005120
5121 return dump;
5122}
5123
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005124void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005125 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5126 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5127 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005128 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129
Tiger Huang721e26f2018-07-24 22:26:19 +08005130 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5131 dump += StringPrintf(INDENT "FocusedApplications:\n");
5132 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5133 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005134 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005135 const std::chrono::duration timeout =
5136 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005137 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005138 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005139 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005142 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005144
Vishnu Nairc519ff72021-01-21 08:23:08 -08005145 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005146 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005148 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005149 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005150 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5151 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005153 state.displayId, toString(state.down), toString(state.split),
5154 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005155 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005156 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005157 for (size_t i = 0; i < state.windows.size(); i++) {
5158 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005159 dump += StringPrintf(INDENT4
5160 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5161 i, touchedWindow.windowHandle->getName().c_str(),
5162 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005163 }
5164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 }
5168 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005169 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171
arthurhung6d4bed92021-03-17 11:59:33 +08005172 if (mDragState) {
5173 dump += StringPrintf(INDENT "DragState:\n");
5174 mDragState->dump(dump, INDENT2);
5175 }
5176
Arthur Hungb92218b2018-08-14 12:00:21 +08005177 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005178 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5179 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5180 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5181 const auto& displayInfo = it->second;
5182 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5183 displayInfo.logicalHeight);
5184 displayInfo.transform.dump(dump, "transform", INDENT4);
5185 } else {
5186 dump += INDENT2 "No DisplayInfo found!\n";
5187 }
5188
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005189 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005190 dump += INDENT2 "Windows:\n";
5191 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005192 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5193 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005195 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005196 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005197 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005198 "applicationInfo.name=%s, "
5199 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005200 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005201 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005202 windowInfo->displayId,
5203 windowInfo->inputConfig.string().c_str(),
5204 windowInfo->alpha, windowInfo->frameLeft,
5205 windowInfo->frameTop, windowInfo->frameRight,
5206 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005207 windowInfo->applicationInfo.name.c_str(),
5208 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005209 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005210 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005211 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005212 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005213 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005214 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005215 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005216 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005217 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005218 }
5219 } else {
5220 dump += INDENT2 "Windows: <none>\n";
5221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 }
5223 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005224 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 }
5226
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005227 if (!mGlobalMonitorsByDisplay.empty()) {
5228 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5229 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005230 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005233 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 }
5235
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005236 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237
5238 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005239 if (!mRecentQueue.empty()) {
5240 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005241 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005242 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005243 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005244 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 }
5246 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005247 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 }
5249
5250 // Dump event currently being dispatched.
5251 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005252 dump += INDENT "PendingEvent:\n";
5253 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005254 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005255 dump += StringPrintf(", age=%" PRId64 "ms\n",
5256 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005258 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 }
5260
5261 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005262 if (!mInboundQueue.empty()) {
5263 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005264 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005265 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005266 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005267 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 }
5269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005270 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 }
5272
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005273 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005274 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005275 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5276 const KeyReplacement& replacement = pair.first;
5277 int32_t newKeyCode = pair.second;
5278 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005279 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005280 }
5281 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005282 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005283 }
5284
Prabir Pradhancef936d2021-07-21 16:17:52 +00005285 if (!mCommandQueue.empty()) {
5286 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5287 } else {
5288 dump += INDENT "CommandQueue: <empty>\n";
5289 }
5290
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005291 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005292 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005293 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005294 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005295 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005296 connection->inputChannel->getFd().get(),
5297 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005298 connection->getWindowName().c_str(),
5299 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005300 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005302 if (!connection->outboundQueue.empty()) {
5303 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5304 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005305 dump += dumpQueue(connection->outboundQueue, currentTime);
5306
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 }
5310
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005311 if (!connection->waitQueue.empty()) {
5312 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5313 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005314 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005316 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 }
5318 }
5319 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005320 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 }
5322
5323 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005324 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5325 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005327 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 }
5329
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005330 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005331 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5332 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5333 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005334 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005335 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336}
5337
Michael Wright3dd60e22019-03-27 22:06:44 +00005338void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5339 const size_t numMonitors = monitors.size();
5340 for (size_t i = 0; i < numMonitors; i++) {
5341 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005342 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005343 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5344 dump += "\n";
5345 }
5346}
5347
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005348class LooperEventCallback : public LooperCallback {
5349public:
5350 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5351 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5352
5353private:
5354 std::function<int(int events)> mCallback;
5355};
5356
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005357Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005358 if (DEBUG_CHANNEL_CREATION) {
5359 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005362 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005363 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005364 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005365
5366 if (result) {
5367 return base::Error(result) << "Failed to open input channel pair with name " << name;
5368 }
5369
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005371 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005372 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005373 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005374 sp<Connection> connection =
5375 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005377 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5378 ALOGE("Created a new connection, but the token %p is already known", token.get());
5379 }
5380 mConnectionsByToken.emplace(token, connection);
5381
5382 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5383 this, std::placeholders::_1, token);
5384
5385 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 } // release lock
5387
5388 // Wake the looper because some connections have changed.
5389 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005390 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391}
5392
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005393Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005394 const std::string& name,
5395 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005396 std::shared_ptr<InputChannel> serverChannel;
5397 std::unique_ptr<InputChannel> clientChannel;
5398 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5399 if (result) {
5400 return base::Error(result) << "Failed to open input channel pair with name " << name;
5401 }
5402
Michael Wright3dd60e22019-03-27 22:06:44 +00005403 { // acquire lock
5404 std::scoped_lock _l(mLock);
5405
5406 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005407 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5408 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005409 }
5410
Garfield Tan15601662020-09-22 15:32:38 -07005411 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005412 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005413 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005414
5415 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5416 ALOGE("Created a new connection, but the token %p is already known", token.get());
5417 }
5418 mConnectionsByToken.emplace(token, connection);
5419 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5420 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005421
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005422 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005423
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005424 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005425 }
Garfield Tan15601662020-09-22 15:32:38 -07005426
Michael Wright3dd60e22019-03-27 22:06:44 +00005427 // Wake the looper because some connections have changed.
5428 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005429 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005430}
5431
Garfield Tan15601662020-09-22 15:32:38 -07005432status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005434 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
Garfield Tan15601662020-09-22 15:32:38 -07005436 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 if (status) {
5438 return status;
5439 }
5440 } // release lock
5441
5442 // Wake the poll loop because removing the connection may have changed the current
5443 // synchronization state.
5444 mLooper->wake();
5445 return OK;
5446}
5447
Garfield Tan15601662020-09-22 15:32:38 -07005448status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5449 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005450 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005451 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005452 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 return BAD_VALUE;
5454 }
5455
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005456 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005457
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005459 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 }
5461
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005462 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463
5464 nsecs_t currentTime = now();
5465 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5466
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005467 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 return OK;
5469}
5470
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005471void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005472 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5473 auto& [displayId, monitors] = *it;
5474 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5475 return monitor.inputChannel->getConnectionToken() == connectionToken;
5476 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005477
Michael Wright3dd60e22019-03-27 22:06:44 +00005478 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005479 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005480 } else {
5481 ++it;
5482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 }
5484}
5485
Michael Wright3dd60e22019-03-27 22:06:44 +00005486status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005487 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005488
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005489 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5490 if (!requestingChannel) {
5491 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5492 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005493 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005494
5495 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5496 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5497 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5498 " Ignoring.");
5499 return BAD_VALUE;
5500 }
5501
5502 TouchState& state = *statePtr;
5503
5504 // Send cancel events to all the input channels we're stealing from.
5505 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5506 "input channel stole pointer stream");
5507 options.deviceId = state.deviceId;
5508 options.displayId = state.displayId;
5509 std::string canceledWindows;
5510 for (const TouchedWindow& window : state.windows) {
5511 const std::shared_ptr<InputChannel> channel =
5512 getInputChannelLocked(window.windowHandle->getToken());
5513 if (channel != nullptr && channel->getConnectionToken() != token) {
5514 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5515 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5516 canceledWindows += channel->getName();
5517 }
5518 }
5519 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5520 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5521 canceledWindows.c_str());
5522
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005523 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005524 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005525 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005526 return OK;
5527}
5528
Prabir Pradhan99987712020-11-10 18:43:05 -08005529void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5530 { // acquire lock
5531 std::scoped_lock _l(mLock);
5532 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005533 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005534 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5535 windowHandle != nullptr ? windowHandle->getName().c_str()
5536 : "token without window");
5537 }
5538
Vishnu Nairc519ff72021-01-21 08:23:08 -08005539 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005540 if (focusedToken != windowToken) {
5541 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5542 enabled ? "enable" : "disable");
5543 return;
5544 }
5545
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005546 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005547 ALOGW("Ignoring request to %s Pointer Capture: "
5548 "window has %s requested pointer capture.",
5549 enabled ? "enable" : "disable", enabled ? "already" : "not");
5550 return;
5551 }
5552
Christine Franksb768bb42021-11-29 12:11:31 -08005553 if (enabled) {
5554 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5555 mIneligibleDisplaysForPointerCapture.end(),
5556 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5557 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5558 return;
5559 }
5560 }
5561
Prabir Pradhan99987712020-11-10 18:43:05 -08005562 setPointerCaptureLocked(enabled);
5563 } // release lock
5564
5565 // Wake the thread to process command entries.
5566 mLooper->wake();
5567}
5568
Christine Franksb768bb42021-11-29 12:11:31 -08005569void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5570 { // acquire lock
5571 std::scoped_lock _l(mLock);
5572 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5573 if (!isEligible) {
5574 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5575 }
5576 } // release lock
5577}
5578
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005579std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5580 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005581 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005582 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005583 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005584 }
5585 }
5586 }
5587 return std::nullopt;
5588}
5589
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005590sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005591 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005592 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005593 }
5594
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005595 for (const auto& [token, connection] : mConnectionsByToken) {
5596 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005597 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 }
5599 }
Robert Carr4e670e52018-08-15 13:26:12 -07005600
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005601 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602}
5603
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005604std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5605 sp<Connection> connection = getConnectionLocked(connectionToken);
5606 if (connection == nullptr) {
5607 return "<nullptr>";
5608 }
5609 return connection->getInputChannelName();
5610}
5611
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005612void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005613 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005614 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005615}
5616
Prabir Pradhancef936d2021-07-21 16:17:52 +00005617void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5618 const sp<Connection>& connection, uint32_t seq,
5619 bool handled, nsecs_t consumeTime) {
5620 // Handle post-event policy actions.
5621 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5622 if (dispatchEntryIt == connection->waitQueue.end()) {
5623 return;
5624 }
5625 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5626 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5627 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5628 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5629 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5630 }
5631 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5632 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5633 connection->inputChannel->getConnectionToken(),
5634 dispatchEntry->deliveryTime, consumeTime, finishTime);
5635 }
5636
5637 bool restartEvent;
5638 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5639 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5640 restartEvent =
5641 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5642 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5643 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5644 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5645 handled);
5646 } else {
5647 restartEvent = false;
5648 }
5649
5650 // Dequeue the event and start the next cycle.
5651 // Because the lock might have been released, it is possible that the
5652 // contents of the wait queue to have been drained, so we need to double-check
5653 // a few things.
5654 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5655 if (dispatchEntryIt != connection->waitQueue.end()) {
5656 dispatchEntry = *dispatchEntryIt;
5657 connection->waitQueue.erase(dispatchEntryIt);
5658 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5659 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5660 if (!connection->responsive) {
5661 connection->responsive = isConnectionResponsive(*connection);
5662 if (connection->responsive) {
5663 // The connection was unresponsive, and now it's responsive.
5664 processConnectionResponsiveLocked(*connection);
5665 }
5666 }
5667 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005668 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005669 connection->outboundQueue.push_front(dispatchEntry);
5670 traceOutboundQueueLength(*connection);
5671 } else {
5672 releaseDispatchEntry(dispatchEntry);
5673 }
5674 }
5675
5676 // Start the next dispatch cycle for this connection.
5677 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678}
5679
Prabir Pradhancef936d2021-07-21 16:17:52 +00005680void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5681 const sp<IBinder>& newToken) {
5682 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5683 scoped_unlock unlock(mLock);
5684 mPolicy->notifyFocusChanged(oldToken, newToken);
5685 };
5686 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687}
5688
Prabir Pradhancef936d2021-07-21 16:17:52 +00005689void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5690 auto command = [this, token, x, y]() REQUIRES(mLock) {
5691 scoped_unlock unlock(mLock);
5692 mPolicy->notifyDropWindow(token, x, y);
5693 };
5694 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005695}
5696
Prabir Pradhancef936d2021-07-21 16:17:52 +00005697void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5698 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5699 scoped_unlock unlock(mLock);
5700 mPolicy->notifyUntrustedTouch(obscuringPackage);
5701 };
5702 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005703}
5704
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005705void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5706 if (connection == nullptr) {
5707 LOG_ALWAYS_FATAL("Caller must check for nullness");
5708 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005709 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5710 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005711 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005712 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005713 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005714 return;
5715 }
5716 /**
5717 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5718 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5719 * has changed. This could cause newer entries to time out before the already dispatched
5720 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5721 * processes the events linearly. So providing information about the oldest entry seems to be
5722 * most useful.
5723 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005724 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5726 std::string reason =
5727 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005728 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005729 ns2ms(currentWait),
5730 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005731 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005732 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005733
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005734 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5735
5736 // Stop waking up for events on this connection, it is already unresponsive
5737 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005738}
5739
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005740void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5741 std::string reason =
5742 StringPrintf("%s does not have a focused window", application->getName().c_str());
5743 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005744
Prabir Pradhancef936d2021-07-21 16:17:52 +00005745 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5746 scoped_unlock unlock(mLock);
5747 mPolicy->notifyNoFocusedWindowAnr(application);
5748 };
5749 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005750}
5751
chaviw98318de2021-05-19 16:45:23 -05005752void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753 const std::string& reason) {
5754 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5755 updateLastAnrStateLocked(windowLabel, reason);
5756}
5757
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005758void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5759 const std::string& reason) {
5760 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005761 updateLastAnrStateLocked(windowLabel, reason);
5762}
5763
5764void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5765 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005767 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 struct tm tm;
5769 localtime_r(&t, &tm);
5770 char timestr[64];
5771 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005772 mLastAnrState.clear();
5773 mLastAnrState += INDENT "ANR:\n";
5774 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005775 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5776 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005777 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778}
5779
Prabir Pradhancef936d2021-07-21 16:17:52 +00005780void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5781 KeyEntry& entry) {
5782 const KeyEvent event = createKeyEvent(entry);
5783 nsecs_t delay = 0;
5784 { // release lock
5785 scoped_unlock unlock(mLock);
5786 android::base::Timer t;
5787 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5788 entry.policyFlags);
5789 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5790 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5791 std::to_string(t.duration().count()).c_str());
5792 }
5793 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794
5795 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005796 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005797 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005798 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005800 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5801 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803}
5804
Prabir Pradhancef936d2021-07-21 16:17:52 +00005805void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005806 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005807 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005808 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005809 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005810 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005811 };
5812 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005813}
5814
Prabir Pradhanedd96402022-02-15 01:46:16 -08005815void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5816 std::optional<int32_t> pid) {
5817 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005818 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005819 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005820 };
5821 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005822}
5823
5824/**
5825 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5826 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5827 * command entry to the command queue.
5828 */
5829void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5830 std::string reason) {
5831 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005832 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005833 if (connection.monitor) {
5834 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5835 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005836 pid = findMonitorPidByTokenLocked(connectionToken);
5837 } else {
5838 // The connection is a window
5839 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5840 reason.c_str());
5841 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5842 if (handle != nullptr) {
5843 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005844 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005845 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005846 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005847}
5848
5849/**
5850 * Tell the policy that a connection has become responsive so that it can stop ANR.
5851 */
5852void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5853 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005854 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005855 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005856 pid = findMonitorPidByTokenLocked(connectionToken);
5857 } else {
5858 // The connection is a window
5859 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5860 if (handle != nullptr) {
5861 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005862 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005863 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005864 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005865}
5866
Prabir Pradhancef936d2021-07-21 16:17:52 +00005867bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005868 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005869 KeyEntry& keyEntry, bool handled) {
5870 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005871 if (!handled) {
5872 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005873 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005874 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005875 return false;
5876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005878 // Get the fallback key state.
5879 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005880 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005882 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005883 connection->inputState.removeFallbackKey(originalKeyCode);
5884 }
5885
5886 if (handled || !dispatchEntry->hasForegroundTarget()) {
5887 // If the application handles the original key for which we previously
5888 // generated a fallback or if the window is not a foreground window,
5889 // then cancel the associated fallback key, if any.
5890 if (fallbackKeyCode != -1) {
5891 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005892 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5893 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5894 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5895 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5896 keyEntry.policyFlags);
5897 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005898 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005899 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900
5901 mLock.unlock();
5902
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005903 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005904 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905
5906 mLock.lock();
5907
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005908 // Cancel the fallback key.
5909 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005911 "application handled the original non-fallback key "
5912 "or is no longer a foreground target, "
5913 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 options.keyCode = fallbackKeyCode;
5915 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005917 connection->inputState.removeFallbackKey(originalKeyCode);
5918 }
5919 } else {
5920 // If the application did not handle a non-fallback key, first check
5921 // that we are in a good state to perform unhandled key event processing
5922 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005923 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005924 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005925 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5926 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5927 "since this is not an initial down. "
5928 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5929 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5930 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005931 return false;
5932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005934 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005935 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5936 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5937 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5938 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5939 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005940 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005941
5942 mLock.unlock();
5943
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005944 bool fallback =
5945 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005946 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005947
5948 mLock.lock();
5949
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005950 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005951 connection->inputState.removeFallbackKey(originalKeyCode);
5952 return false;
5953 }
5954
5955 // Latch the fallback keycode for this key on an initial down.
5956 // The fallback keycode cannot change at any other point in the lifecycle.
5957 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 fallbackKeyCode = event.getKeyCode();
5960 } else {
5961 fallbackKeyCode = AKEYCODE_UNKNOWN;
5962 }
5963 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5964 }
5965
5966 ALOG_ASSERT(fallbackKeyCode != -1);
5967
5968 // Cancel the fallback key if the policy decides not to send it anymore.
5969 // We will continue to dispatch the key to the policy but we will no
5970 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005971 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5972 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005973 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5974 if (fallback) {
5975 ALOGD("Unhandled key event: Policy requested to send key %d"
5976 "as a fallback for %d, but on the DOWN it had requested "
5977 "to send %d instead. Fallback canceled.",
5978 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5979 } else {
5980 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5981 "but on the DOWN it had requested to send %d. "
5982 "Fallback canceled.",
5983 originalKeyCode, fallbackKeyCode);
5984 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005986
5987 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5988 "canceling fallback, policy no longer desires it");
5989 options.keyCode = fallbackKeyCode;
5990 synthesizeCancelationEventsForConnectionLocked(connection, options);
5991
5992 fallback = false;
5993 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005994 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005995 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005996 }
5997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005999 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6000 {
6001 std::string msg;
6002 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6003 connection->inputState.getFallbackKeys();
6004 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6005 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6006 }
6007 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6008 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006011
6012 if (fallback) {
6013 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006014 keyEntry.eventTime = event.getEventTime();
6015 keyEntry.deviceId = event.getDeviceId();
6016 keyEntry.source = event.getSource();
6017 keyEntry.displayId = event.getDisplayId();
6018 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6019 keyEntry.keyCode = fallbackKeyCode;
6020 keyEntry.scanCode = event.getScanCode();
6021 keyEntry.metaState = event.getMetaState();
6022 keyEntry.repeatCount = event.getRepeatCount();
6023 keyEntry.downTime = event.getDownTime();
6024 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006025
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006026 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6027 ALOGD("Unhandled key event: Dispatching fallback key. "
6028 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6029 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6030 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006031 return true; // restart the event
6032 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006033 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6034 ALOGD("Unhandled key event: No fallback key.");
6035 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006036
6037 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 }
6040 }
6041 return false;
6042}
6043
Prabir Pradhancef936d2021-07-21 16:17:52 +00006044bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006045 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006046 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047 return false;
6048}
6049
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050void InputDispatcher::traceInboundQueueLengthLocked() {
6051 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006052 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
6054}
6055
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006056void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057 if (ATRACE_ENABLED()) {
6058 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006059 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6060 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 }
6062}
6063
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006064void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065 if (ATRACE_ENABLED()) {
6066 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006067 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6068 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 }
6070}
6071
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006072void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006073 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006075 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076 dumpDispatchStateLocked(dump);
6077
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006078 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006079 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006080 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 }
6082}
6083
6084void InputDispatcher::monitor() {
6085 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006086 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006088 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089}
6090
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006091/**
6092 * Wake up the dispatcher and wait until it processes all events and commands.
6093 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6094 * this method can be safely called from any thread, as long as you've ensured that
6095 * the work you are interested in completing has already been queued.
6096 */
6097bool InputDispatcher::waitForIdle() {
6098 /**
6099 * Timeout should represent the longest possible time that a device might spend processing
6100 * events and commands.
6101 */
6102 constexpr std::chrono::duration TIMEOUT = 100ms;
6103 std::unique_lock lock(mLock);
6104 mLooper->wake();
6105 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6106 return result == std::cv_status::no_timeout;
6107}
6108
Vishnu Naire798b472020-07-23 13:52:21 -07006109/**
6110 * Sets focus to the window identified by the token. This must be called
6111 * after updating any input window handles.
6112 *
6113 * Params:
6114 * request.token - input channel token used to identify the window that should gain focus.
6115 * request.focusedToken - the token that the caller expects currently to be focused. If the
6116 * specified token does not match the currently focused window, this request will be dropped.
6117 * If the specified focused token matches the currently focused window, the call will succeed.
6118 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6119 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6120 * when requesting the focus change. This determines which request gets
6121 * precedence if there is a focus change request from another source such as pointer down.
6122 */
Vishnu Nair958da932020-08-21 17:12:37 -07006123void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6124 { // acquire lock
6125 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006126 std::optional<FocusResolver::FocusChanges> changes =
6127 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6128 if (changes) {
6129 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006130 }
6131 } // release lock
6132 // Wake up poll loop since it may need to make new input dispatching choices.
6133 mLooper->wake();
6134}
6135
Vishnu Nairc519ff72021-01-21 08:23:08 -08006136void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6137 if (changes.oldFocus) {
6138 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006139 if (focusedInputChannel) {
6140 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6141 "focus left window");
6142 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006143 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006144 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006145 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006146 if (changes.newFocus) {
6147 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006148 }
6149
Prabir Pradhan99987712020-11-10 18:43:05 -08006150 // If a window has pointer capture, then it must have focus. We need to ensure that this
6151 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6152 // If the window loses focus before it loses pointer capture, then the window can be in a state
6153 // where it has pointer capture but not focus, violating the contract. Therefore we must
6154 // dispatch the pointer capture event before the focus event. Since focus events are added to
6155 // the front of the queue (above), we add the pointer capture event to the front of the queue
6156 // after the focus events are added. This ensures the pointer capture event ends up at the
6157 // front.
6158 disablePointerCaptureForcedLocked();
6159
Vishnu Nairc519ff72021-01-21 08:23:08 -08006160 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006161 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006162 }
6163}
Vishnu Nair958da932020-08-21 17:12:37 -07006164
Prabir Pradhan99987712020-11-10 18:43:05 -08006165void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006166 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006167 return;
6168 }
6169
6170 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6171
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006172 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006173 setPointerCaptureLocked(false);
6174 }
6175
6176 if (!mWindowTokenWithPointerCapture) {
6177 // No need to send capture changes because no window has capture.
6178 return;
6179 }
6180
6181 if (mPendingEvent != nullptr) {
6182 // Move the pending event to the front of the queue. This will give the chance
6183 // for the pending event to be dropped if it is a captured event.
6184 mInboundQueue.push_front(mPendingEvent);
6185 mPendingEvent = nullptr;
6186 }
6187
6188 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006189 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006190 mInboundQueue.push_front(std::move(entry));
6191}
6192
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006193void InputDispatcher::setPointerCaptureLocked(bool enable) {
6194 mCurrentPointerCaptureRequest.enable = enable;
6195 mCurrentPointerCaptureRequest.seq++;
6196 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006197 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006198 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006199 };
6200 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006201}
6202
Vishnu Nair599f1412021-06-21 10:39:58 -07006203void InputDispatcher::displayRemoved(int32_t displayId) {
6204 { // acquire lock
6205 std::scoped_lock _l(mLock);
6206 // Set an empty list to remove all handles from the specific display.
6207 setInputWindowsLocked(/* window handles */ {}, displayId);
6208 setFocusedApplicationLocked(displayId, nullptr);
6209 // Call focus resolver to clean up stale requests. This must be called after input windows
6210 // have been removed for the removed display.
6211 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006212 // Reset pointer capture eligibility, regardless of previous state.
6213 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006214 } // release lock
6215
6216 // Wake up poll loop since it may need to make new input dispatching choices.
6217 mLooper->wake();
6218}
6219
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006220void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6221 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006222 // The listener sends the windows as a flattened array. Separate the windows by display for
6223 // more convenient parsing.
6224 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006225 for (const auto& info : windowInfos) {
6226 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6227 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6228 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006229
6230 { // acquire lock
6231 std::scoped_lock _l(mLock);
6232 mDisplayInfos.clear();
6233 for (const auto& displayInfo : displayInfos) {
6234 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6235 }
6236
6237 for (const auto& [displayId, handles] : handlesPerDisplay) {
6238 setInputWindowsLocked(handles, displayId);
6239 }
6240 }
6241 // Wake up poll loop since it may need to make new input dispatching choices.
6242 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006243}
6244
Vishnu Nair062a8672021-09-03 16:07:44 -07006245bool InputDispatcher::shouldDropInput(
6246 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006247 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6248 (windowHandle->getInfo()->inputConfig.test(
6249 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006250 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006251 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6252 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006253 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006254 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006255 windowHandle->getInfo()->displayId);
6256 return true;
6257 }
6258 return false;
6259}
6260
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006261void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6262 const std::vector<gui::WindowInfo>& windowInfos,
6263 const std::vector<DisplayInfo>& displayInfos) {
6264 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6265}
6266
Arthur Hungdfd528e2021-12-08 13:23:04 +00006267void InputDispatcher::cancelCurrentTouch() {
6268 {
6269 std::scoped_lock _l(mLock);
6270 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6271 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6272 "cancel current touch");
6273 synthesizeCancelationEventsForAllConnectionsLocked(options);
6274
6275 mTouchStatesByDisplay.clear();
6276 mLastHoverWindowHandle.clear();
6277 }
6278 // Wake up poll loop since there might be work to do.
6279 mLooper->wake();
6280}
6281
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006282void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6283 std::scoped_lock _l(mLock);
6284 mMonitorDispatchingTimeout = timeout;
6285}
6286
Garfield Tane84e6f92019-08-29 17:28:41 -07006287} // namespace android::inputdispatcher