blob: f5aa45b66cb8e17c88075cff648fc2ee80268730 [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 Pradhan76bdecb2022-01-31 11:14:15 -0800512 if (!inputConfig.test(WindowInfo::InputConfig::TOUCH_MODAL) &&
513 !windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800514 return false;
515 }
516 return true;
517}
518
Prabir Pradhand65552b2021-10-07 11:23:50 -0700519bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
520 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
521 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
522 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
523}
524
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000525} // namespace
526
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527// --- InputDispatcher ---
528
Garfield Tan00f511d2019-06-12 16:55:40 -0700529InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
530 : mPolicy(policy),
531 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700532 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800533 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700534 mAppSwitchSawKeyDown(false),
535 mAppSwitchDueTime(LONG_LONG_MAX),
536 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800537 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700538 mDispatchEnabled(false),
539 mDispatchFrozen(false),
540 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800541 // mInTouchMode will be initialized by the WindowManager to the default device config.
542 // To avoid leaking stack in case that call never comes, and for tests,
543 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000544 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100545 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000546 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800547 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000548 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800549 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800551 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700553 mWindowInfoListener = new DispatcherWindowListener(*this);
554 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
555
Yi Kong9b14ac62018-07-17 13:48:38 -0700556 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557
558 policy->getDispatcherConfiguration(&mConfig);
559}
560
561InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000562 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563
Prabir Pradhancef936d2021-07-21 16:17:52 +0000564 resetKeyRepeatLocked();
565 releasePendingEventLocked();
566 drainInboundQueueLocked();
567 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000569 while (!mConnectionsByToken.empty()) {
570 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000571 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
572 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 }
574}
575
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700576status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700577 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700578 return ALREADY_EXISTS;
579 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700580 mThread = std::make_unique<InputThread>(
581 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
582 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700583}
584
585status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700586 if (mThread && mThread->isCallingThread()) {
587 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700588 return INVALID_OPERATION;
589 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700590 mThread.reset();
591 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700592}
593
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594void InputDispatcher::dispatchOnce() {
595 nsecs_t nextWakeupTime = LONG_LONG_MAX;
596 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800597 std::scoped_lock _l(mLock);
598 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599
600 // Run a dispatch loop if there are no pending commands.
601 // The dispatch loop might enqueue commands to run afterwards.
602 if (!haveCommandsLocked()) {
603 dispatchOnceInnerLocked(&nextWakeupTime);
604 }
605
606 // Run all pending commands if there are any.
607 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000608 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 nextWakeupTime = LONG_LONG_MIN;
610 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800611
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700612 // If we are still waiting for ack on some events,
613 // we might have to wake up earlier to check if an app is anr'ing.
614 const nsecs_t nextAnrCheck = processAnrsLocked();
615 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
616
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800617 // We are about to enter an infinitely long sleep, because we have no commands or
618 // pending or queued events
619 if (nextWakeupTime == LONG_LONG_MAX) {
620 mDispatcherEnteredIdle.notify_all();
621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 } // release lock
623
624 // Wait for callback or timeout or wake. (make sure we round up, not down)
625 nsecs_t currentTime = now();
626 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
627 mLooper->pollOnce(timeoutMillis);
628}
629
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700630/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500631 * Raise ANR if there is no focused window.
632 * Before the ANR is raised, do a final state check:
633 * 1. The currently focused application must be the same one we are waiting for.
634 * 2. Ensure we still don't have a focused window.
635 */
636void InputDispatcher::processNoFocusedWindowAnrLocked() {
637 // Check if the application that we are waiting for is still focused.
638 std::shared_ptr<InputApplicationHandle> focusedApplication =
639 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
640 if (focusedApplication == nullptr ||
641 focusedApplication->getApplicationToken() !=
642 mAwaitedFocusedApplication->getApplicationToken()) {
643 // Unexpected because we should have reset the ANR timer when focused application changed
644 ALOGE("Waited for a focused window, but focused application has already changed to %s",
645 focusedApplication->getName().c_str());
646 return; // The focused application has changed.
647 }
648
chaviw98318de2021-05-19 16:45:23 -0500649 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500650 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
651 if (focusedWindowHandle != nullptr) {
652 return; // We now have a focused window. No need for ANR.
653 }
654 onAnrLocked(mAwaitedFocusedApplication);
655}
656
657/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700658 * Check if any of the connections' wait queues have events that are too old.
659 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
660 * Return the time at which we should wake up next.
661 */
662nsecs_t InputDispatcher::processAnrsLocked() {
663 const nsecs_t currentTime = now();
664 nsecs_t nextAnrCheck = LONG_LONG_MAX;
665 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
666 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
667 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500668 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700669 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500670 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 return LONG_LONG_MIN;
672 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500673 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700674 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
675 }
676 }
677
678 // Check if any connection ANRs are due
679 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
680 if (currentTime < nextAnrCheck) { // most likely scenario
681 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
682 }
683
684 // If we reached here, we have an unresponsive connection.
685 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
686 if (connection == nullptr) {
687 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
688 return nextAnrCheck;
689 }
690 connection->responsive = false;
691 // Stop waking up for this unresponsive connection
692 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000693 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 return LONG_LONG_MIN;
695}
696
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800697std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
698 const sp<Connection>& connection) {
699 if (connection->monitor) {
700 return mMonitorDispatchingTimeout;
701 }
702 const sp<WindowInfoHandle> window =
703 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500705 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500707 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708}
709
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
711 nsecs_t currentTime = now();
712
Jeff Browndc5992e2014-04-11 01:27:26 -0700713 // Reset the key repeat timer whenever normal dispatch is suspended while the
714 // device is in a non-interactive state. This is to ensure that we abort a key
715 // repeat if the device is just coming out of sleep.
716 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 resetKeyRepeatLocked();
718 }
719
720 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
721 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100722 if (DEBUG_FOCUS) {
723 ALOGD("Dispatch frozen. Waiting some more.");
724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 return;
726 }
727
728 // Optimize latency of app switches.
729 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
730 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
731 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
732 if (mAppSwitchDueTime < *nextWakeupTime) {
733 *nextWakeupTime = mAppSwitchDueTime;
734 }
735
736 // Ready to start a new event.
737 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700738 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700739 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 if (isAppSwitchDue) {
741 // The inbound queue is empty so the app switch key we were waiting
742 // for will never arrive. Stop waiting for it.
743 resetPendingAppSwitchLocked(false);
744 isAppSwitchDue = false;
745 }
746
747 // Synthesize a key repeat if appropriate.
748 if (mKeyRepeatState.lastKeyEntry) {
749 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
750 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
751 } else {
752 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
753 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
754 }
755 }
756 }
757
758 // Nothing to do if there is no pending event.
759 if (!mPendingEvent) {
760 return;
761 }
762 } else {
763 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700764 mPendingEvent = mInboundQueue.front();
765 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 traceInboundQueueLengthLocked();
767 }
768
769 // Poke user activity for this event.
770 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700771 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 }
774
775 // Now we have an event to dispatch.
776 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700777 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700779 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 }
785
786 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700787 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700791 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700792 const ConfigurationChangedEntry& typedEntry =
793 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 break;
797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700799 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700800 const DeviceResetEntry& typedEntry =
801 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100807 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 std::shared_ptr<FocusEntry> typedEntry =
809 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100810 dispatchFocusLocked(currentTime, typedEntry);
811 done = true;
812 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
813 break;
814 }
815
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700816 case EventEntry::Type::TOUCH_MODE_CHANGED: {
817 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
818 dispatchTouchModeChangeLocked(currentTime, typedEntry);
819 done = true;
820 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
821 break;
822 }
823
Prabir Pradhan99987712020-11-10 18:43:05 -0800824 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
825 const auto typedEntry =
826 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
827 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
828 done = true;
829 break;
830 }
831
arthurhungb89ccb02020-12-30 16:19:01 +0800832 case EventEntry::Type::DRAG: {
833 std::shared_ptr<DragEntry> typedEntry =
834 std::static_pointer_cast<DragEntry>(mPendingEvent);
835 dispatchDragLocked(currentTime, typedEntry);
836 done = true;
837 break;
838 }
839
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700840 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700841 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700842 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700843 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 resetPendingAppSwitchLocked(true);
845 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700846 } else if (dropReason == DropReason::NOT_DROPPED) {
847 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700848 }
849 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700853 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
854 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 break;
858 }
859
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700860 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 std::shared_ptr<MotionEntry> motionEntry =
862 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700863 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
864 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700866 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700869 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
870 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700872 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
Chris Yef59a2f42020-10-16 12:55:26 -0700875
876 case EventEntry::Type::SENSOR: {
877 std::shared_ptr<SensorEntry> sensorEntry =
878 std::static_pointer_cast<SensorEntry>(mPendingEvent);
879 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
880 dropReason = DropReason::APP_SWITCH;
881 }
882 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
883 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
884 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
885 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
886 dropReason = DropReason::STALE;
887 }
888 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
889 done = true;
890 break;
891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 }
893
894 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700896 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
Michael Wright3a981722015-06-10 15:26:13 +0100898 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899
900 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
903}
904
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700905/**
906 * Return true if the events preceding this incoming motion event should be dropped
907 * Return false otherwise (the default behaviour)
908 */
909bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700910 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700911 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912
913 // Optimize case where the current application is unresponsive and the user
914 // decides to touch a window in a different application.
915 // If the application takes too long to catch up then we drop all events preceding
916 // the touch into the other window.
917 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700918 int32_t displayId = motionEntry.displayId;
919 int32_t x = static_cast<int32_t>(
920 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
921 int32_t y = static_cast<int32_t>(
922 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700923
924 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500925 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700926 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700927 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700928 touchedWindowHandle->getApplicationToken() !=
929 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931 ALOGI("Pruning input queue because user touched a different application while waiting "
932 "for %s",
933 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700934 return true;
935 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800937 // Alternatively, maybe there's a spy window that could handle this event.
938 const std::vector<sp<WindowInfoHandle>> touchedSpies =
939 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
940 for (const auto& windowHandle : touchedSpies) {
941 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000942 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800943 // This spy window could take more input. Drop all events preceding this
944 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800946 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 mAwaitedFocusedApplication->getName().c_str());
948 return true;
949 }
950 }
951 }
952
953 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
954 // yet been processed by some connections, the dispatcher will wait for these motion
955 // events to be processed before dispatching the key event. This is because these motion events
956 // may cause a new window to be launched, which the user might expect to receive focus.
957 // To prevent waiting forever for such events, just send the key to the currently focused window
958 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
959 ALOGD("Received a new pointer down event, stop waiting for events to process and "
960 "just send the pending key event to the focused window.");
961 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700962 }
963 return false;
964}
965
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700966bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968 mInboundQueue.push_back(std::move(newEntry));
969 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 traceInboundQueueLengthLocked();
971
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700972 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700973 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700974 // Optimize app switch latency.
975 // If the application takes too long to catch up then we drop all events preceding
976 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700979 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700981 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000983 if (DEBUG_APP_SWITCH) {
984 ALOGD("App switch is pending!");
985 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700986 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 mAppSwitchSawKeyDown = false;
988 needWake = true;
989 }
990 }
991 }
992 break;
993 }
994
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700995 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700996 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
997 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700998 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001002 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001003 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1004 break;
1005 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001006 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001007 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001008 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001009 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001010 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1011 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001012 // nothing to do
1013 break;
1014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016
1017 return needWake;
1018}
1019
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001021 // Do not store sensor event in recent queue to avoid flooding the queue.
1022 if (entry->type != EventEntry::Type::SENSOR) {
1023 mRecentQueue.push_back(entry);
1024 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001025 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001026 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 }
1028}
1029
chaviw98318de2021-05-19 16:45:23 -05001030sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1031 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001032 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001033 bool addOutsideTargets,
1034 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001035 if (addOutsideTargets && touchState == nullptr) {
1036 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001039 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001040 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001041 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001042 continue;
1043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001045 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001046 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001047 return windowHandle;
1048 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001049
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001050 if (addOutsideTargets &&
1051 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001052 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1053 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
1055 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001056 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057}
1058
Prabir Pradhand65552b2021-10-07 11:23:50 -07001059std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1060 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001061 // Traverse windows from front to back and gather the touched spy windows.
1062 std::vector<sp<WindowInfoHandle>> spyWindows;
1063 const auto& windowHandles = getWindowHandlesLocked(displayId);
1064 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1065 const WindowInfo& info = *windowHandle->getInfo();
1066
Prabir Pradhand65552b2021-10-07 11:23:50 -07001067 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001068 continue;
1069 }
1070 if (!info.isSpy()) {
1071 // The first touched non-spy window was found, so return the spy windows touched so far.
1072 return spyWindows;
1073 }
1074 spyWindows.push_back(windowHandle);
1075 }
1076 return spyWindows;
1077}
1078
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001079void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 const char* reason;
1081 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001083 if (DEBUG_INBOUND_EVENT_DETAILS) {
1084 ALOGD("Dropped event because policy consumed it.");
1085 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 reason = "inbound event was dropped because the policy consumed it";
1087 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::DISABLED:
1089 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 ALOGI("Dropped event because input dispatch is disabled.");
1091 }
1092 reason = "inbound event was dropped because input dispatch is disabled";
1093 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001094 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 ALOGI("Dropped event because of pending overdue app switch.");
1096 reason = "inbound event was dropped because of pending overdue app switch";
1097 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001098 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 ALOGI("Dropped event because the current application is not responding and the user "
1100 "has started interacting with a different application.");
1101 reason = "inbound event was dropped because the current application is not responding "
1102 "and the user has started interacting with a different application";
1103 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001104 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 ALOGI("Dropped event because it is stale.");
1106 reason = "inbound event was dropped because it is stale";
1107 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001108 case DropReason::NO_POINTER_CAPTURE:
1109 ALOGI("Dropped event because there is no window with Pointer Capture.");
1110 reason = "inbound event was dropped because there is no window with Pointer Capture";
1111 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001112 case DropReason::NOT_DROPPED: {
1113 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 }
1117
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001118 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001119 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1121 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001125 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1126 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1128 synthesizeCancelationEventsForAllConnectionsLocked(options);
1129 } else {
1130 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1131 synthesizeCancelationEventsForAllConnectionsLocked(options);
1132 }
1133 break;
1134 }
Chris Yef59a2f42020-10-16 12:55:26 -07001135 case EventEntry::Type::SENSOR: {
1136 break;
1137 }
arthurhungb89ccb02020-12-30 16:19:01 +08001138 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1139 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001140 break;
1141 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001142 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001143 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001144 case EventEntry::Type::CONFIGURATION_CHANGED:
1145 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001146 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001147 break;
1148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150}
1151
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001152static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1154 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155}
1156
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001157bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1158 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1159 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1160 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161}
1162
1163bool InputDispatcher::isAppSwitchPendingLocked() {
1164 return mAppSwitchDueTime != LONG_LONG_MAX;
1165}
1166
1167void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1168 mAppSwitchDueTime = LONG_LONG_MAX;
1169
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001170 if (DEBUG_APP_SWITCH) {
1171 if (handled) {
1172 ALOGD("App switch has arrived.");
1173 } else {
1174 ALOGD("App switch was abandoned.");
1175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177}
1178
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001180 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181}
1182
Prabir Pradhancef936d2021-07-21 16:17:52 +00001183bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001184 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 return false;
1186 }
1187
1188 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001189 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001190 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001191 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1192 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001193 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return true;
1195}
1196
Prabir Pradhancef936d2021-07-21 16:17:52 +00001197void InputDispatcher::postCommandLocked(Command&& command) {
1198 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199}
1200
1201void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001202 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001204 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 releaseInboundEventLocked(entry);
1206 }
1207 traceInboundQueueLengthLocked();
1208}
1209
1210void InputDispatcher::releasePendingEventLocked() {
1211 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001213 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 }
1215}
1216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001219 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001220 if (DEBUG_DISPATCH_CYCLE) {
1221 ALOGD("Injected inbound event was dropped.");
1222 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001226 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
1228 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229}
1230
1231void InputDispatcher::resetKeyRepeatLocked() {
1232 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001233 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 }
1235}
1236
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1238 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239
Michael Wright2e732952014-09-24 13:26:59 -07001240 uint32_t policyFlags = entry->policyFlags &
1241 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 std::shared_ptr<KeyEntry> newEntry =
1244 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1245 entry->source, entry->displayId, policyFlags, entry->action,
1246 entry->flags, entry->keyCode, entry->scanCode,
1247 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001249 newEntry->syntheticRepeat = true;
1250 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253}
1254
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001256 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001257 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1258 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260
1261 // Reset key repeating in case a keyboard device was added or removed or something.
1262 resetKeyRepeatLocked();
1263
1264 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001265 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1266 scoped_unlock unlock(mLock);
1267 mPolicy->notifyConfigurationChanged(eventTime);
1268 };
1269 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 return true;
1271}
1272
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1274 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001275 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1276 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1277 entry.deviceId);
1278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279
liushenxiang42232912021-05-21 20:24:09 +08001280 // Reset key repeating in case a keyboard device was disabled or enabled.
1281 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1282 resetKeyRepeatLocked();
1283 }
1284
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 synthesizeCancelationEventsForAllConnectionsLocked(options);
1288 return true;
1289}
1290
Vishnu Nairad321cd2020-08-20 16:40:21 -07001291void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001292 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001293 if (mPendingEvent != nullptr) {
1294 // Move the pending event to the front of the queue. This will give the chance
1295 // for the pending event to get dispatched to the newly focused window
1296 mInboundQueue.push_front(mPendingEvent);
1297 mPendingEvent = nullptr;
1298 }
1299
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 std::unique_ptr<FocusEntry> focusEntry =
1301 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1302 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001303
1304 // This event should go to the front of the queue, but behind all other focus events
1305 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001306 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001307 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308 [](const std::shared_ptr<EventEntry>& event) {
1309 return event->type == EventEntry::Type::FOCUS;
1310 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001311
1312 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001313 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001314}
1315
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001317 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001318 if (channel == nullptr) {
1319 return; // Window has gone away
1320 }
1321 InputTarget target;
1322 target.inputChannel = channel;
1323 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1324 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001325 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1326 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001327 std::string reason = std::string("reason=").append(entry->reason);
1328 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001329 dispatchEventLocked(currentTime, entry, {target});
1330}
1331
Prabir Pradhan99987712020-11-10 18:43:05 -08001332void InputDispatcher::dispatchPointerCaptureChangedLocked(
1333 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1334 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001335 dropReason = DropReason::NOT_DROPPED;
1336
Prabir Pradhan99987712020-11-10 18:43:05 -08001337 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001338 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001339
1340 if (entry->pointerCaptureRequest.enable) {
1341 // Enable Pointer Capture.
1342 if (haveWindowWithPointerCapture &&
1343 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1344 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1345 "to the window.");
1346 }
1347 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001348 // This can happen if a window requests capture and immediately releases capture.
1349 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001350 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001351 return;
1352 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001353 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1354 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1355 return;
1356 }
1357
Vishnu Nairc519ff72021-01-21 08:23:08 -08001358 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001359 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1360 mWindowTokenWithPointerCapture = token;
1361 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001362 // Disable Pointer Capture.
1363 // We do not check if the sequence number matches for requests to disable Pointer Capture
1364 // for two reasons:
1365 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1366 // to disable capture with the same sequence number: one generated by
1367 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1368 // Capture being disabled in InputReader.
1369 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1370 // actual Pointer Capture state that affects events being generated by input devices is
1371 // in InputReader.
1372 if (!haveWindowWithPointerCapture) {
1373 // Pointer capture was already forcefully disabled because of focus change.
1374 dropReason = DropReason::NOT_DROPPED;
1375 return;
1376 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001377 token = mWindowTokenWithPointerCapture;
1378 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001379 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001380 setPointerCaptureLocked(false);
1381 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001382 }
1383
1384 auto channel = getInputChannelLocked(token);
1385 if (channel == nullptr) {
1386 // Window has gone away, clean up Pointer Capture state.
1387 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001388 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001389 setPointerCaptureLocked(false);
1390 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 return;
1392 }
1393 InputTarget target;
1394 target.inputChannel = channel;
1395 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1396 entry->dispatchInProgress = true;
1397 dispatchEventLocked(currentTime, entry, {target});
1398
1399 dropReason = DropReason::NOT_DROPPED;
1400}
1401
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001402void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1403 const std::shared_ptr<TouchModeEntry>& entry) {
1404 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1405 getWindowHandlesLocked(mFocusedDisplayId);
1406 if (windowHandles.empty()) {
1407 return;
1408 }
1409 const std::vector<InputTarget> inputTargets =
1410 getInputTargetsFromWindowHandlesLocked(windowHandles);
1411 if (inputTargets.empty()) {
1412 return;
1413 }
1414 entry->dispatchInProgress = true;
1415 dispatchEventLocked(currentTime, entry, inputTargets);
1416}
1417
1418std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1419 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1420 std::vector<InputTarget> inputTargets;
1421 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1422 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1423 const sp<IBinder>& token = handle->getToken();
1424 if (token == nullptr) {
1425 continue;
1426 }
1427 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1428 if (channel == nullptr) {
1429 continue; // Window has gone away
1430 }
1431 InputTarget target;
1432 target.inputChannel = channel;
1433 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1434 inputTargets.push_back(target);
1435 }
1436 return inputTargets;
1437}
1438
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001439bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001442 if (!entry->dispatchInProgress) {
1443 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1444 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1445 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1446 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001447 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 // We have seen two identical key downs in a row which indicates that the device
1449 // driver is automatically generating key repeats itself. We take note of the
1450 // repeat here, but we disable our own next key repeat timer since it is clear that
1451 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001452 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1453 // Make sure we don't get key down from a different device. If a different
1454 // device Id has same key pressed down, the new device Id will replace the
1455 // current one to hold the key repeat with repeat count reset.
1456 // In the future when got a KEY_UP on the device id, drop it and do not
1457 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1459 resetKeyRepeatLocked();
1460 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1461 } else {
1462 // Not a repeat. Save key down state in case we do see a repeat later.
1463 resetKeyRepeatLocked();
1464 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1465 }
1466 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001467 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1468 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001469 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001470 if (DEBUG_INBOUND_EVENT_DETAILS) {
1471 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1472 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 resetKeyRepeatLocked();
1475 }
1476
1477 if (entry->repeatCount == 1) {
1478 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1479 } else {
1480 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1481 }
1482
1483 entry->dispatchInProgress = true;
1484
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 }
1487
1488 // Handle case where the policy asked us to try again later last time.
1489 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1490 if (currentTime < entry->interceptKeyWakeupTime) {
1491 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1492 *nextWakeupTime = entry->interceptKeyWakeupTime;
1493 }
1494 return false; // wait until next wakeup
1495 }
1496 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1497 entry->interceptKeyWakeupTime = 0;
1498 }
1499
1500 // Give the policy a chance to intercept the key.
1501 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1502 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001503 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001504 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001505
1506 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1507 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1508 };
1509 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 return false; // wait for the command to run
1511 } else {
1512 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1513 }
1514 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001515 if (*dropReason == DropReason::NOT_DROPPED) {
1516 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
1518 }
1519
1520 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001521 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001523 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1524 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001525 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 return true;
1527 }
1528
1529 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001530 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001532 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001533 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 return false;
1535 }
1536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001538 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 return true;
1540 }
1541
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001542 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001543 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544
1545 // Dispatch the key.
1546 dispatchEventLocked(currentTime, entry, inputTargets);
1547 return true;
1548}
1549
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001550void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001551 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1552 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1553 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1554 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1555 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1556 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1557 entry.metaState, entry.repeatCount, entry.downTime);
1558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559}
1560
Prabir Pradhancef936d2021-07-21 16:17:52 +00001561void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1562 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001563 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001564 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1565 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1566 "source=0x%x, sensorType=%s",
1567 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001568 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001569 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001570 auto command = [this, entry]() REQUIRES(mLock) {
1571 scoped_unlock unlock(mLock);
1572
1573 if (entry->accuracyChanged) {
1574 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1575 }
1576 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1577 entry->hwTimestamp, entry->values);
1578 };
1579 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001580}
1581
1582bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1584 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001585 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001586 }
Chris Yef59a2f42020-10-16 12:55:26 -07001587 { // acquire lock
1588 std::scoped_lock _l(mLock);
1589
1590 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1591 std::shared_ptr<EventEntry> entry = *it;
1592 if (entry->type == EventEntry::Type::SENSOR) {
1593 it = mInboundQueue.erase(it);
1594 releaseInboundEventLocked(entry);
1595 }
1596 }
1597 }
1598 return true;
1599}
1600
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001601bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001602 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001603 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001605 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 entry->dispatchInProgress = true;
1607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 }
1610
1611 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001612 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001613 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001614 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1615 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 return true;
1617 }
1618
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001619 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620
1621 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001622 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623
1624 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001625 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 if (isPointerEvent) {
1627 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001628 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001629 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001630 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 } else {
1632 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001633 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001634 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001636 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 return false;
1638 }
1639
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001640 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001641 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001642 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1643 return true;
1644 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001646 CancelationOptions::Mode mode(isPointerEvent
1647 ? CancelationOptions::CANCEL_POINTER_EVENTS
1648 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1649 CancelationOptions options(mode, "input event injection failed");
1650 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 return true;
1652 }
1653
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001654 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001655 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656
1657 // Dispatch the motion.
1658 if (conflictingPointerActions) {
1659 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001660 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 synthesizeCancelationEventsForAllConnectionsLocked(options);
1662 }
1663 dispatchEventLocked(currentTime, entry, inputTargets);
1664 return true;
1665}
1666
chaviw98318de2021-05-19 16:45:23 -05001667void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001668 bool isExiting, const MotionEntry& motionEntry) {
1669 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1670 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1671 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1672 PointerCoords pointerCoords;
1673 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1674 pointerCoords.transform(windowHandle->getInfo()->transform);
1675
1676 std::unique_ptr<DragEntry> dragEntry =
1677 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1678 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1679 pointerCoords.getY());
1680
1681 enqueueInboundEventLocked(std::move(dragEntry));
1682}
1683
1684void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1685 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1686 if (channel == nullptr) {
1687 return; // Window has gone away
1688 }
1689 InputTarget target;
1690 target.inputChannel = channel;
1691 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1692 entry->dispatchInProgress = true;
1693 dispatchEventLocked(currentTime, entry, {target});
1694}
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001697 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1698 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1699 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001700 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001701 "metaState=0x%x, buttonState=0x%x,"
1702 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1703 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001704 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1705 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1706 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001708 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1709 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1710 "x=%f, y=%f, pressure=%f, size=%f, "
1711 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1712 "orientation=%f",
1713 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1714 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1717 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1718 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1719 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1720 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1721 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1722 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725}
1726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001727void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1728 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001729 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001730 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001731 if (DEBUG_DISPATCH_CYCLE) {
1732 ALOGD("dispatchEventToCurrentInputTargets");
1733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001735 updateInteractionTokensLocked(*eventEntry, inputTargets);
1736
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1738
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001741 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001742 sp<Connection> connection =
1743 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001744 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001745 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001747 if (DEBUG_FOCUS) {
1748 ALOGD("Dropping event delivery to target with channel '%s' because it "
1749 "is no longer registered with the input dispatcher.",
1750 inputTarget.inputChannel->getName().c_str());
1751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 }
1753 }
1754}
1755
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001756void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1757 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1758 // If the policy decides to close the app, we will get a channel removal event via
1759 // unregisterInputChannel, and will clean up the connection that way. We are already not
1760 // sending new pointers to the connection when it blocked, but focused events will continue to
1761 // pile up.
1762 ALOGW("Canceling events for %s because it is unresponsive",
1763 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001764 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1766 "application not responding");
1767 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 }
1769}
1770
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001771void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001772 if (DEBUG_FOCUS) {
1773 ALOGD("Resetting ANR timeouts.");
1774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775
1776 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001777 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001778 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779}
1780
Tiger Huang721e26f2018-07-24 22:26:19 +08001781/**
1782 * Get the display id that the given event should go to. If this event specifies a valid display id,
1783 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1784 * Focused display is the display that the user most recently interacted with.
1785 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001786int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001787 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001788 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001789 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1791 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001792 break;
1793 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001794 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1796 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001797 break;
1798 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001799 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001800 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001801 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001802 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001803 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001804 case EventEntry::Type::SENSOR:
1805 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001806 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001807 return ADISPLAY_ID_NONE;
1808 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001809 }
1810 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1811}
1812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001813bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1814 const char* focusedWindowName) {
1815 if (mAnrTracker.empty()) {
1816 // already processed all events that we waited for
1817 mKeyIsWaitingForEventsTimeout = std::nullopt;
1818 return false;
1819 }
1820
1821 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1822 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001823 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001824 mKeyIsWaitingForEventsTimeout = currentTime +
1825 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1826 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001827 return true;
1828 }
1829
1830 // We still have pending events, and already started the timer
1831 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1832 return true; // Still waiting
1833 }
1834
1835 // Waited too long, and some connection still hasn't processed all motions
1836 // Just send the key to the focused window
1837 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1838 focusedWindowName);
1839 mKeyIsWaitingForEventsTimeout = std::nullopt;
1840 return false;
1841}
1842
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1844 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1845 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001846 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
Tiger Huang721e26f2018-07-24 22:26:19 +08001848 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001849 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001850 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001851 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1852
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 // If there is no currently focused window and no focused application
1854 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001855 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1856 ALOGI("Dropping %s event because there is no focused window or focused application in "
1857 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001858 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001859 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
1861
Vishnu Nair062a8672021-09-03 16:07:44 -07001862 // Drop key events if requested by input feature
1863 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1864 return InputEventInjectionResult::FAILED;
1865 }
1866
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1868 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1869 // start interacting with another application via touch (app switch). This code can be removed
1870 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1871 // an app is expected to have a focused window.
1872 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1873 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1874 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001875 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1876 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1877 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001878 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001879 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001880 ALOGW("Waiting because no window has focus but %s may eventually add a "
1881 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001882 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001883 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001885 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1886 // Already raised ANR. Drop the event
1887 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001888 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001889 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001890 } else {
1891 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 }
1894 }
1895
1896 // we have a valid, non-null focused window
1897 resetNoFocusedWindowTimeoutLocked();
1898
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001900 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001901 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 }
1903
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001904 if (focusedWindowHandle->getInfo()->inputConfig.test(
1905 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 }
1909
1910 // If the event is a key event, then we must wait for all previous events to
1911 // complete before delivering it because previous events may have the
1912 // side-effect of transferring focus to a different window and we want to
1913 // ensure that the following keys are sent to the new window.
1914 //
1915 // Suppose the user touches a button in a window then immediately presses "A".
1916 // If the button causes a pop-up window to appear then we want to ensure that
1917 // the "A" key is delivered to the new pop-up window. This is because users
1918 // often anticipate pending UI changes when typing on a keyboard.
1919 // To obtain this behavior, we must serialize key events with respect to all
1920 // prior input events.
1921 if (entry.type == EventEntry::Type::KEY) {
1922 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1923 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001924 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
1927
1928 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001929 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001930 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1931 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001934 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935}
1936
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001937/**
1938 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1939 * that are currently unresponsive.
1940 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001941std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1942 const std::vector<Monitor>& monitors) const {
1943 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001945 [this](const Monitor& monitor) REQUIRES(mLock) {
1946 sp<Connection> connection =
1947 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001948 if (connection == nullptr) {
1949 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001950 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 return false;
1952 }
1953 if (!connection->responsive) {
1954 ALOGW("Unresponsive monitor %s will not get the new gesture",
1955 connection->inputChannel->getName().c_str());
1956 return false;
1957 }
1958 return true;
1959 });
1960 return responsiveMonitors;
1961}
1962
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001963InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1964 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1965 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001966 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 enum InjectionPermission {
1968 INJECTION_PERMISSION_UNKNOWN,
1969 INJECTION_PERMISSION_GRANTED,
1970 INJECTION_PERMISSION_DENIED
1971 };
1972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 // For security reasons, we defer updating the touch state until we are sure that
1974 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001975 const int32_t displayId = entry.displayId;
1976 const int32_t action = entry.action;
1977 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978
1979 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001982 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1983 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001985 // Copy current touch state into tempTouchState.
1986 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1987 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001988 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001989 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001990 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1991 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08001992 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001993 }
1994
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001995 bool isSplit = tempTouchState.split;
1996 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1997 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1998 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001999
2000 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2001 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2002 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2003 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2004 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002005 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 bool wrongDevice = false;
2007 if (newGesture) {
2008 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002009 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002010 ALOGI("Dropping event because a pointer for a different device is already down "
2011 "in display %" PRId32,
2012 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002013 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002014 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 switchedDevice = false;
2016 wrongDevice = true;
2017 goto Failed;
2018 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002019 tempTouchState.reset();
2020 tempTouchState.down = down;
2021 tempTouchState.deviceId = entry.deviceId;
2022 tempTouchState.source = entry.source;
2023 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002025 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002026 ALOGI("Dropping move event because a pointer for a different device is already active "
2027 "in display %" PRId32,
2028 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002029 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002030 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002031 switchedDevice = false;
2032 wrongDevice = true;
2033 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 }
2035
2036 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2037 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2038
Garfield Tan00f511d2019-06-12 16:55:40 -07002039 int32_t x;
2040 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002041 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002042 // Always dispatch mouse events to cursor position.
2043 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002044 x = int32_t(entry.xCursorPosition);
2045 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002047 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2048 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002049 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002050 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002051 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002052 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002053 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002054
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002056 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002057 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2058 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002060 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002061 }
2062
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002063 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002064 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002065 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2066 // New window supports splitting, but we should never split mouse events.
2067 isSplit = !isFromMouse;
2068 } else if (isSplit) {
2069 // New window does not support splitting but we have already split events.
2070 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 newTouchedWindowHandle = nullptr;
2072 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002073 } else {
2074 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002075 // be delivered to a new window which supports split touch. Pointers from a mouse device
2076 // should never be split.
2077 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078 }
2079
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002080 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002082 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2083 newHoverWindowHandle = nullptr;
2084 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002087 }
2088
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002089 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002090 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002091 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002092 // Process the foreground window first so that it is the first to receive the event.
2093 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002094 }
2095
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002096 if (newTouchedWindows.empty()) {
2097 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2098 x, y, displayId);
2099 injectionResult = InputEventInjectionResult::FAILED;
2100 goto Failed;
2101 }
2102
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002103 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2104 const WindowInfo& info = *windowHandle->getInfo();
2105
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002106 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002107 ALOGI("Not sending touch event to %s because it is paused",
2108 windowHandle->getName().c_str());
2109 continue;
2110 }
2111
2112 // Ensure the window has a connection and the connection is responsive
2113 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2114 if (!isResponsive) {
2115 ALOGW("Not sending touch gesture to %s because it is not responsive",
2116 windowHandle->getName().c_str());
2117 continue;
2118 }
2119
2120 // Drop events that can't be trusted due to occlusion
2121 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2122 TouchOcclusionInfo occlusionInfo =
2123 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2124 if (!isTouchTrustedLocked(occlusionInfo)) {
2125 if (DEBUG_TOUCH_OCCLUSION) {
2126 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2127 for (const auto& log : occlusionInfo.debugInfo) {
2128 ALOGD("%s", log.c_str());
2129 }
2130 }
2131 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2132 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2133 ALOGW("Dropping untrusted touch event due to %s/%d",
2134 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2135 continue;
2136 }
2137 }
2138 }
2139
2140 // Drop touch events if requested by input feature
2141 if (shouldDropInput(entry, windowHandle)) {
2142 continue;
2143 }
2144
2145 // Set target flags.
2146 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2147
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002148 if (!info.isSpy()) {
2149 // There should only be one new foreground (non-spy) window at this location.
2150 targetFlags |= InputTarget::FLAG_FOREGROUND;
2151 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002152
2153 if (isSplit) {
2154 targetFlags |= InputTarget::FLAG_SPLIT;
2155 }
2156 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2157 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2158 } else if (isWindowObscuredLocked(windowHandle)) {
2159 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2160 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002161
2162 // Update the temporary touch state.
2163 BitSet32 pointerIds;
2164 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002165 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002166 pointerIds.markBit(pointerId);
2167 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002168
2169 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 } else {
2172 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2173
2174 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002175 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002176 if (DEBUG_FOCUS) {
2177 ALOGD("Dropping event because the pointer is not down or we previously "
2178 "dropped the pointer down event in display %" PRId32,
2179 displayId);
2180 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002181 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 goto Failed;
2183 }
2184
arthurhung6d4bed92021-03-17 11:59:33 +08002185 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002186
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002188 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002190 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2191 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192
Prabir Pradhand65552b2021-10-07 11:23:50 -07002193 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002194 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002195 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002196 newTouchedWindowHandle =
2197 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002198
2199 // Drop touch events if requested by input feature
2200 if (newTouchedWindowHandle != nullptr &&
2201 shouldDropInput(entry, newTouchedWindowHandle)) {
2202 newTouchedWindowHandle = nullptr;
2203 }
2204
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002205 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2206 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002207 if (DEBUG_FOCUS) {
2208 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2209 oldTouchedWindowHandle->getName().c_str(),
2210 newTouchedWindowHandle->getName().c_str(), displayId);
2211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2214 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2215 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216
2217 // Make a slippery entrance into the new window.
2218 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002219 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 }
2221
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002222 int32_t targetFlags =
2223 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 if (isSplit) {
2225 targetFlags |= InputTarget::FLAG_SPLIT;
2226 }
2227 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2228 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002229 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2230 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
2232
2233 BitSet32 pointerIds;
2234 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002235 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 }
2239 }
2240 }
2241
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002242 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 // Let the previous window know that the hover sequence is over, unless we already did
2245 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002246 if (mLastHoverWindowHandle != nullptr &&
2247 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2248 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002249 if (DEBUG_HOVER) {
2250 ALOGD("Sending hover exit event to window %s.",
2251 mLastHoverWindowHandle->getName().c_str());
2252 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002253 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2254 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 }
2256
Garfield Tandf26e862020-07-01 20:18:19 -07002257 // Let the new window know that the hover sequence is starting, unless we already did it
2258 // when dispatching it as is to newTouchedWindowHandle.
2259 if (newHoverWindowHandle != nullptr &&
2260 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2261 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002262 if (DEBUG_HOVER) {
2263 ALOGD("Sending hover enter event to window %s.",
2264 newHoverWindowHandle->getName().c_str());
2265 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002266 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2267 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2268 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270 }
2271
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002272 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2273 // of the touched windows we previously found if they became paused or unresponsive or were
2274 // removed.
2275 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2276 [](const TouchedWindow& touchedWindow) {
2277 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2278 touchedWindow.windowHandle->getInfo()->isSpy();
2279 })) {
2280 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2281 displayId);
2282 injectionResult = InputEventInjectionResult::FAILED;
2283 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
2285
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002286 // Check permission to inject into all touched foreground windows.
2287 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2288 [this, &entry](const TouchedWindow& touchedWindow) {
2289 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2290 !checkInjectionPermission(touchedWindow.windowHandle,
2291 entry.injectionState);
2292 })) {
2293 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2294 injectionPermission = INJECTION_PERMISSION_DENIED;
2295 goto Failed;
2296 }
2297 // Permission granted to inject into all touched foreground windows.
2298 injectionPermission = INJECTION_PERMISSION_GRANTED;
2299
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 // Check whether windows listening for outside touches are owned by the same UID. If it is
2301 // set the policy flag that we will not reveal coordinate information to this window.
2302 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002303 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002304 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002305 if (foregroundWindowHandle) {
2306 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002308 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002309 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2310 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2311 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002312 InputTarget::FLAG_ZERO_COORDS,
2313 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
2316 }
2317 }
2318 }
2319
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 // If this is the first pointer going down and the touched window has a wallpaper
2321 // then also add the touched wallpaper windows so they are locked in for the duration
2322 // of the touch gesture.
2323 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2324 // engine only supports touch events. We would need to add a mechanism similar
2325 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2326 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002327 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002328 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002329 if (foregroundWindowHandle &&
2330 foregroundWindowHandle->getInfo()->inputConfig.test(
2331 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002332 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002333 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002334 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2335 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002337 windowHandle->getInfo()->inputConfig.test(
2338 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002339 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 .addOrUpdateWindow(windowHandle,
2341 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2342 InputTarget::
2343 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2344 InputTarget::FLAG_DISPATCH_AS_IS,
2345 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347 }
2348 }
2349 }
2350
2351 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002352 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002354 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002356 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
2358
2359 // Drop the outside or hover touch windows since we will not care about them
2360 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002361 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362
2363Failed:
2364 // Check injection permission once and for all.
2365 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002366 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 injectionPermission = INJECTION_PERMISSION_GRANTED;
2368 } else {
2369 injectionPermission = INJECTION_PERMISSION_DENIED;
2370 }
2371 }
2372
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002373 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2374 return injectionResult;
2375 }
2376
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002378 if (!wrongDevice) {
2379 if (switchedDevice) {
2380 if (DEBUG_FOCUS) {
2381 ALOGD("Conflicting pointer actions: Switched to a different device.");
2382 }
2383 *outConflictingPointerActions = true;
2384 }
2385
2386 if (isHoverAction) {
2387 // Started hovering, therefore no longer down.
2388 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002389 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002390 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2391 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 *outConflictingPointerActions = true;
2394 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002395 tempTouchState.reset();
2396 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2397 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2398 tempTouchState.deviceId = entry.deviceId;
2399 tempTouchState.source = entry.source;
2400 tempTouchState.displayId = displayId;
2401 }
2402 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2403 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2404 // All pointers up or canceled.
2405 tempTouchState.reset();
2406 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2407 // First pointer went down.
2408 if (oldState && oldState->down) {
2409 if (DEBUG_FOCUS) {
2410 ALOGD("Conflicting pointer actions: Down received while already down.");
2411 }
2412 *outConflictingPointerActions = true;
2413 }
2414 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2415 // One pointer went up.
2416 if (isSplit) {
2417 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2418 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002420 for (size_t i = 0; i < tempTouchState.windows.size();) {
2421 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2422 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2423 touchedWindow.pointerIds.clearBit(pointerId);
2424 if (touchedWindow.pointerIds.isEmpty()) {
2425 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2426 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002429 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002431 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002432 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002433
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002434 // Save changes unless the action was scroll in which case the temporary touch
2435 // state was only valid for this one action.
2436 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2437 if (tempTouchState.displayId >= 0) {
2438 mTouchStatesByDisplay[displayId] = tempTouchState;
2439 } else {
2440 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002444 // Update hover state.
2445 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 }
2447
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 return injectionResult;
2449}
2450
arthurhung6d4bed92021-03-17 11:59:33 +08002451void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002452 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2453 // have an explicit reason to support it.
2454 constexpr bool isStylus = false;
2455
chaviw98318de2021-05-19 16:45:23 -05002456 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002457 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002458 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002459 if (dropWindow) {
2460 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002461 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002462 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002463 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002464 }
2465 mDragState.reset();
2466}
2467
2468void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2469 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002470 return;
2471 }
2472
arthurhung6d4bed92021-03-17 11:59:33 +08002473 if (!mDragState->isStartDrag) {
2474 mDragState->isStartDrag = true;
2475 mDragState->isStylusButtonDownAtStart =
2476 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2477 }
2478
arthurhungb89ccb02020-12-30 16:19:01 +08002479 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2480 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2481 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2482 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002483 // Handle the special case : stylus button no longer pressed.
2484 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2485 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2486 finishDragAndDrop(entry.displayId, x, y);
2487 return;
2488 }
2489
Prabir Pradhand65552b2021-10-07 11:23:50 -07002490 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2491 // we have an explicit reason to support it.
2492 constexpr bool isStylus = false;
2493
chaviw98318de2021-05-19 16:45:23 -05002494 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002495 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002496 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002497 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002498 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2499 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2500 if (mDragState->dragHoverWindowHandle != nullptr) {
2501 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2502 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002503 }
arthurhung6d4bed92021-03-17 11:59:33 +08002504 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002505 }
2506 // enqueue drag location if needed.
2507 if (hoverWindowHandle != nullptr) {
2508 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2509 }
arthurhung6d4bed92021-03-17 11:59:33 +08002510 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2511 finishDragAndDrop(entry.displayId, x, y);
2512 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002513 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002514 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002515 }
2516}
2517
chaviw98318de2021-05-19 16:45:23 -05002518void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002519 int32_t targetFlags, BitSet32 pointerIds,
2520 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002521 std::vector<InputTarget>::iterator it =
2522 std::find_if(inputTargets.begin(), inputTargets.end(),
2523 [&windowHandle](const InputTarget& inputTarget) {
2524 return inputTarget.inputChannel->getConnectionToken() ==
2525 windowHandle->getToken();
2526 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002527
chaviw98318de2021-05-19 16:45:23 -05002528 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002529
2530 if (it == inputTargets.end()) {
2531 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002532 std::shared_ptr<InputChannel> inputChannel =
2533 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002534 if (inputChannel == nullptr) {
2535 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2536 return;
2537 }
2538 inputTarget.inputChannel = inputChannel;
2539 inputTarget.flags = targetFlags;
2540 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002541 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2542 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002543 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002544 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002545 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002546 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002547 inputTargets.push_back(inputTarget);
2548 it = inputTargets.end() - 1;
2549 }
2550
2551 ALOG_ASSERT(it->flags == targetFlags);
2552 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2553
chaviw1ff3d1e2020-07-01 15:53:47 -07002554 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555}
2556
Michael Wright3dd60e22019-03-27 22:06:44 +00002557void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002558 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002559 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2560 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002561
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002562 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2563 InputTarget target;
2564 target.inputChannel = monitor.inputChannel;
2565 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2566 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2567 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002568 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002569 target.setDefaultPointerTransform(target.displayTransform);
2570 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 }
2572}
2573
chaviw98318de2021-05-19 16:45:23 -05002574bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 const InjectionState* injectionState) {
2576 if (injectionState &&
2577 (windowHandle == nullptr ||
2578 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2579 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002580 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002582 "owned by uid %d",
2583 injectionState->injectorPid, injectionState->injectorUid,
2584 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 } else {
2586 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 }
2589 return false;
2590 }
2591 return true;
2592}
2593
Robert Carrc9bf1d32020-04-13 17:21:08 -07002594/**
2595 * Indicate whether one window handle should be considered as obscuring
2596 * another window handle. We only check a few preconditions. Actually
2597 * checking the bounds is left to the caller.
2598 */
chaviw98318de2021-05-19 16:45:23 -05002599static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2600 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002601 // Compare by token so cloned layers aren't counted
2602 if (haveSameToken(windowHandle, otherHandle)) {
2603 return false;
2604 }
2605 auto info = windowHandle->getInfo();
2606 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002607 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002608 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002609 } else if (otherInfo->alpha == 0 &&
2610 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002611 // Those act as if they were invisible, so we don't need to flag them.
2612 // We do want to potentially flag touchable windows even if they have 0
2613 // opacity, since they can consume touches and alter the effects of the
2614 // user interaction (eg. apps that rely on
2615 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2616 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2617 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002618 } else if (info->ownerUid == otherInfo->ownerUid) {
2619 // If ownerUid is the same we don't generate occlusion events as there
2620 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002621 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002622 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002623 return false;
2624 } else if (otherInfo->displayId != info->displayId) {
2625 return false;
2626 }
2627 return true;
2628}
2629
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002630/**
2631 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2632 * untrusted, one should check:
2633 *
2634 * 1. If result.hasBlockingOcclusion is true.
2635 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2636 * BLOCK_UNTRUSTED.
2637 *
2638 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2639 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2640 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2641 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2642 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2643 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2644 *
2645 * If neither of those is true, then it means the touch can be allowed.
2646 */
2647InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002648 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2649 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002650 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002651 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002652 TouchOcclusionInfo info;
2653 info.hasBlockingOcclusion = false;
2654 info.obscuringOpacity = 0;
2655 info.obscuringUid = -1;
2656 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002657 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002658 if (windowHandle == otherHandle) {
2659 break; // All future windows are below us. Exit early.
2660 }
chaviw98318de2021-05-19 16:45:23 -05002661 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002662 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2663 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002664 if (DEBUG_TOUCH_OCCLUSION) {
2665 info.debugInfo.push_back(
2666 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2667 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002668 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2669 // we perform the checks below to see if the touch can be propagated or not based on the
2670 // window's touch occlusion mode
2671 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2672 info.hasBlockingOcclusion = true;
2673 info.obscuringUid = otherInfo->ownerUid;
2674 info.obscuringPackage = otherInfo->packageName;
2675 break;
2676 }
2677 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2678 uint32_t uid = otherInfo->ownerUid;
2679 float opacity =
2680 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2681 // Given windows A and B:
2682 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2683 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2684 opacityByUid[uid] = opacity;
2685 if (opacity > info.obscuringOpacity) {
2686 info.obscuringOpacity = opacity;
2687 info.obscuringUid = uid;
2688 info.obscuringPackage = otherInfo->packageName;
2689 }
2690 }
2691 }
2692 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002693 if (DEBUG_TOUCH_OCCLUSION) {
2694 info.debugInfo.push_back(
2695 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2696 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002697 return info;
2698}
2699
chaviw98318de2021-05-19 16:45:23 -05002700std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002701 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002702 return StringPrintf(INDENT2
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002703 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002704 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002705 "], touchableRegion=%s, window={%s}, inputConfig={%s}, inputFeatures={%s}, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002706 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002707 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2708 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2709 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2710 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2711 info->name.c_str(), info->inputConfig.string().c_str(),
2712 info->inputFeatures.string().c_str(), toString(info->token != nullptr),
2713 info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002714 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002715}
2716
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002717bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2718 if (occlusionInfo.hasBlockingOcclusion) {
2719 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2720 occlusionInfo.obscuringUid);
2721 return false;
2722 }
2723 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2724 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2725 "%.2f, maximum allowed = %.2f)",
2726 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2727 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2728 return false;
2729 }
2730 return true;
2731}
2732
chaviw98318de2021-05-19 16:45:23 -05002733bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002734 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002736 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2737 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002738 if (windowHandle == otherHandle) {
2739 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 }
chaviw98318de2021-05-19 16:45:23 -05002741 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002742 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002743 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 return true;
2745 }
2746 }
2747 return false;
2748}
2749
chaviw98318de2021-05-19 16:45:23 -05002750bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002751 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002752 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2753 const WindowInfo* windowInfo = windowHandle->getInfo();
2754 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002755 if (windowHandle == otherHandle) {
2756 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002757 }
chaviw98318de2021-05-19 16:45:23 -05002758 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002759 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002760 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002761 return true;
2762 }
2763 }
2764 return false;
2765}
2766
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002767std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002768 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002769 if (applicationHandle != nullptr) {
2770 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002771 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 } else {
2773 return applicationHandle->getName();
2774 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002775 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002776 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002778 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
2780}
2781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002782void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002783 if (!isUserActivityEvent(eventEntry)) {
2784 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002785 return;
2786 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002787 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002788 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002789 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002790 const WindowInfo* info = focusedWindowHandle->getInfo();
2791 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002792 if (DEBUG_DISPATCH_CYCLE) {
2793 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 return;
2796 }
2797 }
2798
2799 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002800 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002801 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002802 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2803 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 return;
2805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002807 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 eventType = USER_ACTIVITY_EVENT_TOUCH;
2809 }
2810 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002812 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002813 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2814 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 return;
2816 }
2817 eventType = USER_ACTIVITY_EVENT_BUTTON;
2818 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002820 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002821 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002822 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002823 break;
2824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
2826
Prabir Pradhancef936d2021-07-21 16:17:52 +00002827 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2828 REQUIRES(mLock) {
2829 scoped_unlock unlock(mLock);
2830 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2831 };
2832 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833}
2834
2835void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002837 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002838 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002839 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002841 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002842 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002843 ATRACE_NAME(message.c_str());
2844 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002845 if (DEBUG_DISPATCH_CYCLE) {
2846 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2847 "globalScaleFactor=%f, pointerIds=0x%x %s",
2848 connection->getInputChannelName().c_str(), inputTarget.flags,
2849 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2850 inputTarget.getPointerInfoString().c_str());
2851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852
2853 // Skip this event if the connection status is not normal.
2854 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002855 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002856 if (DEBUG_DISPATCH_CYCLE) {
2857 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002858 connection->getInputChannelName().c_str(),
2859 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 return;
2862 }
2863
2864 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002865 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2866 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2867 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002868 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002870 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002871 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002872 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002873 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 if (!splitMotionEntry) {
2875 return; // split event was dropped
2876 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002877 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2878 std::string reason = std::string("reason=pointer cancel on split window");
2879 android_log_event_list(LOGTAG_INPUT_CANCEL)
2880 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2881 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002882 if (DEBUG_FOCUS) {
2883 ALOGD("channel '%s' ~ Split motion event.",
2884 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002885 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002886 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002887 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2888 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 return;
2890 }
2891 }
2892
2893 // Not splitting. Enqueue dispatch entries for the event as is.
2894 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2895}
2896
2897void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002899 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002900 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002901 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002903 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002904 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002905 ATRACE_NAME(message.c_str());
2906 }
2907
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002908 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909
2910 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002911 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002913 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002915 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002917 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002919 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002921 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923
2924 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002925 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 startDispatchCycleLocked(currentTime, connection);
2927 }
2928}
2929
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002931 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002932 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002934 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2936 connection->getInputChannelName().c_str(),
2937 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002938 ATRACE_NAME(message.c_str());
2939 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002940 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 if (!(inputTargetFlags & dispatchMode)) {
2942 return;
2943 }
2944 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2945
2946 // This is a new event.
2947 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002948 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002949 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002951 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2952 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002956 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002957 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002958 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 dispatchEntry->resolvedAction = keyEntry.action;
2960 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2963 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002964 if (DEBUG_DISPATCH_CYCLE) {
2965 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2966 "event",
2967 connection->getInputChannelName().c_str());
2968 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 return; // skip the inconsistent event
2970 }
2971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002974 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002975 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002976 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2977 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2978 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2979 static_cast<int32_t>(IdGenerator::Source::OTHER);
2980 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2982 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2983 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2984 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2985 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2986 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2987 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2988 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2989 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2990 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2991 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002992 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002993 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 }
2995 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002996 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2997 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002998 if (DEBUG_DISPATCH_CYCLE) {
2999 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3000 "enter event",
3001 connection->getInputChannelName().c_str());
3002 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003003 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3004 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003008 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3010 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3011 }
3012 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3013 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3017 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003018 if (DEBUG_DISPATCH_CYCLE) {
3019 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3020 "event",
3021 connection->getInputChannelName().c_str());
3022 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003023 return; // skip the inconsistent event
3024 }
3025
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003026 dispatchEntry->resolvedEventId =
3027 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3028 ? mIdGenerator.nextId()
3029 : motionEntry.id;
3030 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3031 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3032 ") to MotionEvent(id=0x%" PRIx32 ").",
3033 motionEntry.id, dispatchEntry->resolvedEventId);
3034 ATRACE_NAME(message.c_str());
3035 }
3036
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003037 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3038 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3039 // Skip reporting pointer down outside focus to the policy.
3040 break;
3041 }
3042
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003043 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003044 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045
3046 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003048 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003049 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003050 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3051 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003052 break;
3053 }
Chris Yef59a2f42020-10-16 12:55:26 -07003054 case EventEntry::Type::SENSOR: {
3055 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3056 break;
3057 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003058 case EventEntry::Type::CONFIGURATION_CHANGED:
3059 case EventEntry::Type::DEVICE_RESET: {
3060 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003061 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003062 break;
3063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
3065
3066 // Remember that we are waiting for this dispatch to complete.
3067 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003068 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 }
3070
3071 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003072 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003073 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003074}
3075
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003076/**
3077 * This function is purely for debugging. It helps us understand where the user interaction
3078 * was taking place. For example, if user is touching launcher, we will see a log that user
3079 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3080 * We will see both launcher and wallpaper in that list.
3081 * Once the interaction with a particular set of connections starts, no new logs will be printed
3082 * until the set of interacted connections changes.
3083 *
3084 * The following items are skipped, to reduce the logspam:
3085 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3086 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3087 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3088 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3089 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003090 */
3091void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3092 const std::vector<InputTarget>& targets) {
3093 // Skip ACTION_UP events, and all events other than keys and motions
3094 if (entry.type == EventEntry::Type::KEY) {
3095 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3096 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3097 return;
3098 }
3099 } else if (entry.type == EventEntry::Type::MOTION) {
3100 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3101 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3102 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3103 return;
3104 }
3105 } else {
3106 return; // Not a key or a motion
3107 }
3108
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003109 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003110 std::vector<sp<Connection>> newConnections;
3111 for (const InputTarget& target : targets) {
3112 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3113 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3114 continue; // Skip windows that receive ACTION_OUTSIDE
3115 }
3116
3117 sp<IBinder> token = target.inputChannel->getConnectionToken();
3118 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003119 if (connection == nullptr) {
3120 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003121 }
3122 newConnectionTokens.insert(std::move(token));
3123 newConnections.emplace_back(connection);
3124 }
3125 if (newConnectionTokens == mInteractionConnectionTokens) {
3126 return; // no change
3127 }
3128 mInteractionConnectionTokens = newConnectionTokens;
3129
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003130 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003131 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003132 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003133 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003134 std::string message = "Interaction with: " + targetList;
3135 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003136 message += "<none>";
3137 }
3138 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3139}
3140
chaviwfd6d3512019-03-25 13:23:49 -07003141void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003142 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003143 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003144 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3145 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003146 return;
3147 }
3148
Vishnu Nairc519ff72021-01-21 08:23:08 -08003149 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003150 if (focusedToken == token) {
3151 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003152 return;
3153 }
3154
Prabir Pradhancef936d2021-07-21 16:17:52 +00003155 auto command = [this, token]() REQUIRES(mLock) {
3156 scoped_unlock unlock(mLock);
3157 mPolicy->onPointerDownOutsideFocus(token);
3158 };
3159 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160}
3161
3162void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003164 if (ATRACE_ENABLED()) {
3165 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003167 ATRACE_NAME(message.c_str());
3168 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003169 if (DEBUG_DISPATCH_CYCLE) {
3170 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003173 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003174 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003176 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003177 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
3179 // Publish the event.
3180 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003183 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003184 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3185 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 status = connection->inputPublisher
3189 .publishKeyEvent(dispatchEntry->seq,
3190 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3191 keyEntry.source, keyEntry.displayId,
3192 std::move(hmac), dispatchEntry->resolvedAction,
3193 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3194 keyEntry.scanCode, keyEntry.metaState,
3195 keyEntry.repeatCount, keyEntry.downTime,
3196 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003200 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003201 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205
chaviw82357092020-01-28 13:13:06 -08003206 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003207 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3209 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003210 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003211 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3212 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003213 // Don't apply window scale here since we don't want scale to affect raw
3214 // coordinates. The scale will be sent back to the client and applied
3215 // later when requesting relative coordinates.
3216 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3217 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 }
3219 usingCoords = scaledCoords;
3220 }
3221 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 // We don't want the dispatch target to know.
3223 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003224 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 scaledCoords[i].clear();
3226 }
3227 usingCoords = scaledCoords;
3228 }
3229 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003231 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232
3233 // Publish the motion event.
3234 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003235 .publishMotionEvent(dispatchEntry->seq,
3236 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 motionEntry.deviceId, motionEntry.source,
3238 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003239 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003242 motionEntry.edgeFlags, motionEntry.metaState,
3243 motionEntry.buttonState,
3244 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003245 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003246 motionEntry.xPrecision, motionEntry.yPrecision,
3247 motionEntry.xCursorPosition,
3248 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003249 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 motionEntry.downTime, motionEntry.eventTime,
3251 motionEntry.pointerCount,
3252 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 break;
3254 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003255
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003256 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003258 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003259 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003260 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003261 break;
3262 }
3263
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003264 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3265 const TouchModeEntry& touchModeEntry =
3266 static_cast<const TouchModeEntry&>(eventEntry);
3267 status = connection->inputPublisher
3268 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3269 touchModeEntry.inTouchMode);
3270
3271 break;
3272 }
3273
Prabir Pradhan99987712020-11-10 18:43:05 -08003274 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3275 const auto& captureEntry =
3276 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3277 status = connection->inputPublisher
3278 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003279 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003280 break;
3281 }
3282
arthurhungb89ccb02020-12-30 16:19:01 +08003283 case EventEntry::Type::DRAG: {
3284 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3285 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3286 dragEntry.id, dragEntry.x,
3287 dragEntry.y,
3288 dragEntry.isExiting);
3289 break;
3290 }
3291
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003292 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003293 case EventEntry::Type::DEVICE_RESET:
3294 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003295 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003296 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
3300
3301 // Check the result.
3302 if (status) {
3303 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003304 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 "This is unexpected because the wait queue is empty, so the pipe "
3307 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003308 "event to it, status=%s(%d)",
3309 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3310 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3312 } else {
3313 // Pipe is full and we are waiting for the app to finish process some events
3314 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003315 if (DEBUG_DISPATCH_CYCLE) {
3316 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3317 "waiting for the application to catch up",
3318 connection->getInputChannelName().c_str());
3319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
3321 } else {
3322 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003323 "status=%s(%d)",
3324 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3325 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3327 }
3328 return;
3329 }
3330
3331 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003332 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3333 connection->outboundQueue.end(),
3334 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003335 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003336 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003337 if (connection->responsive) {
3338 mAnrTracker.insert(dispatchEntry->timeoutTime,
3339 connection->inputChannel->getConnectionToken());
3340 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003341 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343}
3344
chaviw09c8d2d2020-08-24 15:48:26 -07003345std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3346 size_t size;
3347 switch (event.type) {
3348 case VerifiedInputEvent::Type::KEY: {
3349 size = sizeof(VerifiedKeyEvent);
3350 break;
3351 }
3352 case VerifiedInputEvent::Type::MOTION: {
3353 size = sizeof(VerifiedMotionEvent);
3354 break;
3355 }
3356 }
3357 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3358 return mHmacKeyManager.sign(start, size);
3359}
3360
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003361const std::array<uint8_t, 32> InputDispatcher::getSignature(
3362 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003363 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3364 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003365 // Only sign events up and down events as the purely move events
3366 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003367 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003368 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003369
3370 VerifiedMotionEvent verifiedEvent =
3371 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3372 verifiedEvent.actionMasked = actionMasked;
3373 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3374 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003375}
3376
3377const std::array<uint8_t, 32> InputDispatcher::getSignature(
3378 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3379 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3380 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3381 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003382 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003383}
3384
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003387 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003388 if (DEBUG_DISPATCH_CYCLE) {
3389 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3390 connection->getInputChannelName().c_str(), seq, toString(handled));
3391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003393 if (connection->status == Connection::Status::BROKEN ||
3394 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 return;
3396 }
3397
3398 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003399 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3400 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3401 };
3402 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403}
3404
3405void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 const sp<Connection>& connection,
3407 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003408 if (DEBUG_DISPATCH_CYCLE) {
3409 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3410 connection->getInputChannelName().c_str(), toString(notify));
3411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
3413 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003414 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003415 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003416 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003417 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418
3419 // The connection appears to be unrecoverably broken.
3420 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003421 if (connection->status == Connection::Status::NORMAL) {
3422 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
3424 if (notify) {
3425 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003426 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3427 connection->getInputChannelName().c_str());
3428
3429 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003430 scoped_unlock unlock(mLock);
3431 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3432 };
3433 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 }
3435 }
3436}
3437
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003438void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3439 while (!queue.empty()) {
3440 DispatchEntry* dispatchEntry = queue.front();
3441 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003442 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
3444}
3445
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003446void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003448 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450 delete dispatchEntry;
3451}
3452
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003453int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3454 std::scoped_lock _l(mLock);
3455 sp<Connection> connection = getConnectionLocked(connectionToken);
3456 if (connection == nullptr) {
3457 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3458 connectionToken.get(), events);
3459 return 0; // remove the callback
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003462 bool notify;
3463 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3464 if (!(events & ALOOPER_EVENT_INPUT)) {
3465 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3466 "events=0x%x",
3467 connection->getInputChannelName().c_str(), events);
3468 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 }
3470
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003471 nsecs_t currentTime = now();
3472 bool gotOne = false;
3473 status_t status = OK;
3474 for (;;) {
3475 Result<InputPublisher::ConsumerResponse> result =
3476 connection->inputPublisher.receiveConsumerResponse();
3477 if (!result.ok()) {
3478 status = result.error().code();
3479 break;
3480 }
3481
3482 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3483 const InputPublisher::Finished& finish =
3484 std::get<InputPublisher::Finished>(*result);
3485 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3486 finish.consumeTime);
3487 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003488 if (shouldReportMetricsForConnection(*connection)) {
3489 const InputPublisher::Timeline& timeline =
3490 std::get<InputPublisher::Timeline>(*result);
3491 mLatencyTracker
3492 .trackGraphicsLatency(timeline.inputEventId,
3493 connection->inputChannel->getConnectionToken(),
3494 std::move(timeline.graphicsTimeline));
3495 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003496 }
3497 gotOne = true;
3498 }
3499 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003500 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003501 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 return 1;
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 }
3505
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003506 notify = status != DEAD_OBJECT || !connection->monitor;
3507 if (notify) {
3508 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3509 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3510 status);
3511 }
3512 } else {
3513 // Monitor channels are never explicitly unregistered.
3514 // We do it automatically when the remote endpoint is closed so don't warn about them.
3515 const bool stillHaveWindowHandle =
3516 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3517 notify = !connection->monitor && stillHaveWindowHandle;
3518 if (notify) {
3519 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3520 connection->getInputChannelName().c_str(), events);
3521 }
3522 }
3523
3524 // Remove the channel.
3525 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3526 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527}
3528
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003531 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003532 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534}
3535
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003536void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003537 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003538 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003539 for (const Monitor& monitor : monitors) {
3540 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003541 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003542 }
3543}
3544
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003546 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003547 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003548 if (connection == nullptr) {
3549 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003551
3552 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553}
3554
3555void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3556 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003557 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 return;
3559 }
3560
3561 nsecs_t currentTime = now();
3562
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003563 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003564 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003566 if (cancelationEvents.empty()) {
3567 return;
3568 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003569 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3570 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3571 "with reality: %s, mode=%d.",
3572 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3573 options.mode);
3574 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003575
Arthur Hungb3307ee2021-10-14 10:57:37 +00003576 std::string reason = std::string("reason=").append(options.reason);
3577 android_log_event_list(LOGTAG_INPUT_CANCEL)
3578 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3579
Svet Ganov5d3bc372020-01-26 23:11:07 -08003580 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003581 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3583 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003584 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003585 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003586 target.globalScaleFactor = windowInfo->globalScaleFactor;
3587 }
3588 target.inputChannel = connection->inputChannel;
3589 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3590
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003591 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003592 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003593 switch (cancelationEventEntry->type) {
3594 case EventEntry::Type::KEY: {
3595 logOutboundKeyDetails("cancel - ",
3596 static_cast<const KeyEntry&>(*cancelationEventEntry));
3597 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003599 case EventEntry::Type::MOTION: {
3600 logOutboundMotionDetails("cancel - ",
3601 static_cast<const MotionEntry&>(*cancelationEventEntry));
3602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003604 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003605 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003606 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3607 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003608 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003609 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003610 break;
3611 }
3612 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003613 case EventEntry::Type::DEVICE_RESET:
3614 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003615 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003616 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003617 break;
3618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 }
3620
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003621 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3622 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003624
3625 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626}
3627
Svet Ganov5d3bc372020-01-26 23:11:07 -08003628void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3629 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003630 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631 return;
3632 }
3633
3634 nsecs_t currentTime = now();
3635
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003636 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003637 connection->inputState.synthesizePointerDownEvents(currentTime);
3638
3639 if (downEvents.empty()) {
3640 return;
3641 }
3642
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003643 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003644 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3645 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003646 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003647
3648 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003649 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003650 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3651 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003652 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003653 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654 target.globalScaleFactor = windowInfo->globalScaleFactor;
3655 }
3656 target.inputChannel = connection->inputChannel;
3657 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3658
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003659 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003660 switch (downEventEntry->type) {
3661 case EventEntry::Type::MOTION: {
3662 logOutboundMotionDetails("down - ",
3663 static_cast<const MotionEntry&>(*downEventEntry));
3664 break;
3665 }
3666
3667 case EventEntry::Type::KEY:
3668 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003669 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003671 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003672 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003673 case EventEntry::Type::SENSOR:
3674 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003675 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003676 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003677 break;
3678 }
3679 }
3680
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003681 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3682 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003683 }
3684
3685 startDispatchCycleLocked(currentTime, connection);
3686}
3687
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003688std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3689 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 ALOG_ASSERT(pointerIds.value != 0);
3691
3692 uint32_t splitPointerIndexMap[MAX_POINTERS];
3693 PointerProperties splitPointerProperties[MAX_POINTERS];
3694 PointerCoords splitPointerCoords[MAX_POINTERS];
3695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003696 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 uint32_t splitPointerCount = 0;
3698
3699 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003700 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003702 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 uint32_t pointerId = uint32_t(pointerProperties.id);
3704 if (pointerIds.hasBit(pointerId)) {
3705 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3706 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3707 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003708 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 splitPointerCount += 1;
3710 }
3711 }
3712
3713 if (splitPointerCount != pointerIds.count()) {
3714 // This is bad. We are missing some of the pointers that we expected to deliver.
3715 // Most likely this indicates that we received an ACTION_MOVE events that has
3716 // different pointer ids than we expected based on the previous ACTION_DOWN
3717 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3718 // in this way.
3719 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003720 "we expected there to be %d pointers. This probably means we received "
3721 "a broken sequence of pointer ids from the input device.",
3722 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003723 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 }
3725
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003726 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003728 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3729 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3731 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003732 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 uint32_t pointerId = uint32_t(pointerProperties.id);
3734 if (pointerIds.hasBit(pointerId)) {
3735 if (pointerIds.count() == 1) {
3736 // The first/last pointer went down/up.
3737 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003738 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003739 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3740 ? AMOTION_EVENT_ACTION_CANCEL
3741 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 } else {
3743 // A secondary pointer went down/up.
3744 uint32_t splitPointerIndex = 0;
3745 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3746 splitPointerIndex += 1;
3747 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003748 action = maskedAction |
3749 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 }
3751 } else {
3752 // An unrelated pointer changed.
3753 action = AMOTION_EVENT_ACTION_MOVE;
3754 }
3755 }
3756
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003757 int32_t newId = mIdGenerator.nextId();
3758 if (ATRACE_ENABLED()) {
3759 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3760 ") to MotionEvent(id=0x%" PRIx32 ").",
3761 originalMotionEntry.id, newId);
3762 ATRACE_NAME(message.c_str());
3763 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003764 std::unique_ptr<MotionEntry> splitMotionEntry =
3765 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3766 originalMotionEntry.deviceId, originalMotionEntry.source,
3767 originalMotionEntry.displayId,
3768 originalMotionEntry.policyFlags, action,
3769 originalMotionEntry.actionButton,
3770 originalMotionEntry.flags, originalMotionEntry.metaState,
3771 originalMotionEntry.buttonState,
3772 originalMotionEntry.classification,
3773 originalMotionEntry.edgeFlags,
3774 originalMotionEntry.xPrecision,
3775 originalMotionEntry.yPrecision,
3776 originalMotionEntry.xCursorPosition,
3777 originalMotionEntry.yCursorPosition,
3778 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003779 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003781 if (originalMotionEntry.injectionState) {
3782 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 splitMotionEntry->injectionState->refCount += 1;
3784 }
3785
3786 return splitMotionEntry;
3787}
3788
3789void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003790 if (DEBUG_INBOUND_EVENT_DETAILS) {
3791 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
Antonio Kantekf16f2832021-09-28 04:39:20 +00003794 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003796 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003798 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3799 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3800 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 } // release lock
3802
3803 if (needWake) {
3804 mLooper->wake();
3805 }
3806}
3807
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003808/**
3809 * If one of the meta shortcuts is detected, process them here:
3810 * Meta + Backspace -> generate BACK
3811 * Meta + Enter -> generate HOME
3812 * This will potentially overwrite keyCode and metaState.
3813 */
3814void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003815 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003816 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3817 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3818 if (keyCode == AKEYCODE_DEL) {
3819 newKeyCode = AKEYCODE_BACK;
3820 } else if (keyCode == AKEYCODE_ENTER) {
3821 newKeyCode = AKEYCODE_HOME;
3822 }
3823 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003824 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003825 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003826 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003827 keyCode = newKeyCode;
3828 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3829 }
3830 } else if (action == AKEY_EVENT_ACTION_UP) {
3831 // In order to maintain a consistent stream of up and down events, check to see if the key
3832 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3833 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003834 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003835 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003836 auto replacementIt = mReplacedKeys.find(replacement);
3837 if (replacementIt != mReplacedKeys.end()) {
3838 keyCode = replacementIt->second;
3839 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003840 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3841 }
3842 }
3843}
3844
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003846 if (DEBUG_INBOUND_EVENT_DETAILS) {
3847 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3848 "policyFlags=0x%x, action=0x%x, "
3849 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3850 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3851 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3852 args->downTime);
3853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 if (!validateKeyEvent(args->action)) {
3855 return;
3856 }
3857
3858 uint32_t policyFlags = args->policyFlags;
3859 int32_t flags = args->flags;
3860 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003861 // InputDispatcher tracks and generates key repeats on behalf of
3862 // whatever notifies it, so repeatCount should always be set to 0
3863 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3865 policyFlags |= POLICY_FLAG_VIRTUAL;
3866 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 if (policyFlags & POLICY_FLAG_FUNCTION) {
3869 metaState |= AMETA_FUNCTION_ON;
3870 }
3871
3872 policyFlags |= POLICY_FLAG_TRUSTED;
3873
Michael Wright78f24442014-08-06 15:55:28 -07003874 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003875 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003876
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003878 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003879 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3880 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881
Michael Wright2b3c3302018-03-02 17:19:13 +00003882 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003884 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3885 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888
Antonio Kantekf16f2832021-09-28 04:39:20 +00003889 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 { // acquire lock
3891 mLock.lock();
3892
3893 if (shouldSendKeyToInputFilterLocked(args)) {
3894 mLock.unlock();
3895
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003896 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3898 return; // event was consumed by the filter
3899 }
3900
3901 mLock.lock();
3902 }
3903
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003904 std::unique_ptr<KeyEntry> newEntry =
3905 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3906 args->displayId, policyFlags, args->action, flags,
3907 keyCode, args->scanCode, metaState, repeatCount,
3908 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003910 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 mLock.unlock();
3912 } // release lock
3913
3914 if (needWake) {
3915 mLooper->wake();
3916 }
3917}
3918
3919bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3920 return mInputFilterEnabled;
3921}
3922
3923void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003924 if (DEBUG_INBOUND_EVENT_DETAILS) {
3925 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3926 "displayId=%" PRId32 ", policyFlags=0x%x, "
3927 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3928 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3929 "yCursorPosition=%f, downTime=%" PRId64,
3930 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3931 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3932 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3933 args->xCursorPosition, args->yCursorPosition, args->downTime);
3934 for (uint32_t i = 0; i < args->pointerCount; i++) {
3935 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3936 "x=%f, y=%f, pressure=%f, size=%f, "
3937 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3938 "orientation=%f",
3939 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3940 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3941 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3942 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3943 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3944 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3945 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3946 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3948 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003951 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3952 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 return;
3954 }
3955
3956 uint32_t policyFlags = args->policyFlags;
3957 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003958
3959 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003960 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003961 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3962 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003963 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
Antonio Kantekf16f2832021-09-28 04:39:20 +00003966 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 { // acquire lock
3968 mLock.lock();
3969
3970 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003971 ui::Transform displayTransform;
3972 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3973 displayTransform = it->second.transform;
3974 }
3975
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 mLock.unlock();
3977
3978 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003979 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3980 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003981 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003982 displayTransform, args->xPrecision, args->yPrecision,
3983 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003984 args->downTime, args->eventTime, args->pointerCount,
3985 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
3987 policyFlags |= POLICY_FLAG_FILTERED;
3988 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3989 return; // event was consumed by the filter
3990 }
3991
3992 mLock.lock();
3993 }
3994
3995 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003996 std::unique_ptr<MotionEntry> newEntry =
3997 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3998 args->source, args->displayId, policyFlags,
3999 args->action, args->actionButton, args->flags,
4000 args->metaState, args->buttonState,
4001 args->classification, args->edgeFlags,
4002 args->xPrecision, args->yPrecision,
4003 args->xCursorPosition, args->yCursorPosition,
4004 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004005 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004007 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4008 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4009 !mInputFilterEnabled) {
4010 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4011 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4012 }
4013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004014 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 mLock.unlock();
4016 } // release lock
4017
4018 if (needWake) {
4019 mLooper->wake();
4020 }
4021}
4022
Chris Yef59a2f42020-10-16 12:55:26 -07004023void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004024 if (DEBUG_INBOUND_EVENT_DETAILS) {
4025 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4026 " sensorType=%s",
4027 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004028 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004029 }
Chris Yef59a2f42020-10-16 12:55:26 -07004030
Antonio Kantekf16f2832021-09-28 04:39:20 +00004031 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004032 { // acquire lock
4033 mLock.lock();
4034
4035 // Just enqueue a new sensor event.
4036 std::unique_ptr<SensorEntry> newEntry =
4037 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4038 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4039 args->sensorType, args->accuracy,
4040 args->accuracyChanged, args->values);
4041
4042 needWake = enqueueInboundEventLocked(std::move(newEntry));
4043 mLock.unlock();
4044 } // release lock
4045
4046 if (needWake) {
4047 mLooper->wake();
4048 }
4049}
4050
Chris Yefb552902021-02-03 17:18:37 -08004051void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004052 if (DEBUG_INBOUND_EVENT_DETAILS) {
4053 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4054 args->deviceId, args->isOn);
4055 }
Chris Yefb552902021-02-03 17:18:37 -08004056 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4057}
4058
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004060 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061}
4062
4063void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004064 if (DEBUG_INBOUND_EVENT_DETAILS) {
4065 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4066 "switchMask=0x%08x",
4067 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
4070 uint32_t policyFlags = args->policyFlags;
4071 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004072 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073}
4074
4075void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004076 if (DEBUG_INBOUND_EVENT_DETAILS) {
4077 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4078 args->deviceId);
4079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
Antonio Kantekf16f2832021-09-28 04:39:20 +00004081 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004083 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004085 std::unique_ptr<DeviceResetEntry> newEntry =
4086 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4087 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 } // release lock
4089
4090 if (needWake) {
4091 mLooper->wake();
4092 }
4093}
4094
Prabir Pradhan7e186182020-11-10 13:56:45 -08004095void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004096 if (DEBUG_INBOUND_EVENT_DETAILS) {
4097 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004098 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004099 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004100
Antonio Kantekf16f2832021-09-28 04:39:20 +00004101 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004102 { // acquire lock
4103 std::scoped_lock _l(mLock);
4104 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004105 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004106 needWake = enqueueInboundEventLocked(std::move(entry));
4107 } // release lock
4108
4109 if (needWake) {
4110 mLooper->wake();
4111 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004112}
4113
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004114InputEventInjectionResult InputDispatcher::injectInputEvent(
4115 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4116 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 if (DEBUG_INBOUND_EVENT_DETAILS) {
4118 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4119 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4120 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4121 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004122 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123
4124 policyFlags |= POLICY_FLAG_INJECTED;
4125 if (hasInjectionPermission(injectorPid, injectorUid)) {
4126 policyFlags |= POLICY_FLAG_TRUSTED;
4127 }
4128
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004129 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004130 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4131 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4132 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4133 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4134 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004135 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004136 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 }
4139
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004140 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004143 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4144 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004146 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004149 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004150 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4151 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4152 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004153 int32_t keyCode = incomingKey.getKeyCode();
4154 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004155 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004157 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004158 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004159 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4160 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4161 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4164 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004165 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166
4167 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4168 android::base::Timer t;
4169 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4170 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4171 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4172 std::to_string(t.duration().count()).c_str());
4173 }
4174 }
4175
4176 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004177 std::unique_ptr<KeyEntry> injectedEntry =
4178 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004179 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004180 incomingKey.getDisplayId(), policyFlags, action,
4181 flags, keyCode, incomingKey.getScanCode(), metaState,
4182 incomingKey.getRepeatCount(),
4183 incomingKey.getDownTime());
4184 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
4187
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004189 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004190 const int32_t action = motionEvent.getAction();
4191 const bool isPointerEvent =
4192 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4193 // If a pointer event has no displayId specified, inject it to the default display.
4194 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4195 ? ADISPLAY_ID_DEFAULT
4196 : event->getDisplayId();
4197 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004198 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004199 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004200 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004202 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004203 }
4204
4205 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004206 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 android::base::Timer t;
4208 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4209 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4210 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4211 std::to_string(t.duration().count()).c_str());
4212 }
4213 }
4214
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004215 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4216 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4217 }
4218
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004219 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4221 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004222 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004223 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4224 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004225 displayId, policyFlags, action, actionButton,
4226 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 motionEvent.getButtonState(),
4228 motionEvent.getClassification(),
4229 motionEvent.getEdgeFlags(),
4230 motionEvent.getXPrecision(),
4231 motionEvent.getYPrecision(),
4232 motionEvent.getRawXCursorPosition(),
4233 motionEvent.getRawYCursorPosition(),
4234 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004235 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004236 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004237 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004238 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 sampleEventTimes += 1;
4240 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004241 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4243 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004244 displayId, policyFlags, action, actionButton,
4245 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 motionEvent.getButtonState(),
4247 motionEvent.getClassification(),
4248 motionEvent.getEdgeFlags(),
4249 motionEvent.getXPrecision(),
4250 motionEvent.getYPrecision(),
4251 motionEvent.getRawXCursorPosition(),
4252 motionEvent.getRawYCursorPosition(),
4253 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004254 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004255 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004256 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4257 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004258 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 }
4260 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004264 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004265 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267
4268 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 injectionState->injectionIsAsync = true;
4271 }
4272
4273 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004274 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
4276 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004277 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004279 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 }
4281
4282 mLock.unlock();
4283
4284 if (needWake) {
4285 mLooper->wake();
4286 }
4287
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004288 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004290 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004292 if (syncMode == InputEventInjectionSync::NONE) {
4293 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 } else {
4295 for (;;) {
4296 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 break;
4299 }
4300
4301 nsecs_t remainingTimeout = endTime - now();
4302 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004303 if (DEBUG_INJECTION) {
4304 ALOGD("injectInputEvent - Timed out waiting for injection result "
4305 "to become available.");
4306 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 break;
4309 }
4310
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004311 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 }
4313
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4315 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 if (DEBUG_INJECTION) {
4318 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4319 injectionState->pendingForegroundDispatches);
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 nsecs_t remainingTimeout = endTime - now();
4322 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004323 if (DEBUG_INJECTION) {
4324 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4325 "dispatches to finish.");
4326 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004327 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 break;
4329 }
4330
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004331 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 }
4333 }
4334 }
4335
4336 injectionState->release();
4337 } // release lock
4338
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004339 if (DEBUG_INJECTION) {
4340 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4341 injectionResult, injectorPid, injectorUid);
4342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
4344 return injectionResult;
4345}
4346
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004347std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004348 std::array<uint8_t, 32> calculatedHmac;
4349 std::unique_ptr<VerifiedInputEvent> result;
4350 switch (event.getType()) {
4351 case AINPUT_EVENT_TYPE_KEY: {
4352 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4353 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4354 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004355 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004356 break;
4357 }
4358 case AINPUT_EVENT_TYPE_MOTION: {
4359 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4360 VerifiedMotionEvent verifiedMotionEvent =
4361 verifiedMotionEventFromMotionEvent(motionEvent);
4362 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004363 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004364 break;
4365 }
4366 default: {
4367 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4368 return nullptr;
4369 }
4370 }
4371 if (calculatedHmac == INVALID_HMAC) {
4372 return nullptr;
4373 }
4374 if (calculatedHmac != event.getHmac()) {
4375 return nullptr;
4376 }
4377 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004378}
4379
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 return injectorUid == 0 ||
4382 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383}
4384
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004385void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004387 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004389 if (DEBUG_INJECTION) {
4390 ALOGD("Setting input event injection result to %d. "
4391 "injectorPid=%d, injectorUid=%d",
4392 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004395 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 // Log the outcome since the injector did not wait for the injection result.
4397 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004398 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 ALOGV("Asynchronous input event injection succeeded.");
4400 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004402 ALOGW("Asynchronous input event injection failed.");
4403 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 ALOGW("Asynchronous input event injection permission denied.");
4406 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 ALOGW("Asynchronous input event injection timed out.");
4409 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004410 case InputEventInjectionResult::PENDING:
4411 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4412 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414 }
4415
4416 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004417 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 }
4419}
4420
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004421void InputDispatcher::transformMotionEntryForInjectionLocked(
4422 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004423 // Input injection works in the logical display coordinate space, but the input pipeline works
4424 // display space, so we need to transform the injected events accordingly.
4425 const auto it = mDisplayInfos.find(entry.displayId);
4426 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004427 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004428
4429 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4430 PointerCoords& pc = entry.pointerCoords[i];
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004431 // Make a copy of the injected coords. We cannot change them in place because some of them
4432 // are interdependent (for example, X coordinate might depend on the Y coordinate).
4433 PointerCoords injectedCoords = entry.pointerCoords[i];
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004434
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004435 BitSet64 bits(injectedCoords.bits);
4436 while (!bits.isEmpty()) {
4437 const auto axis = static_cast<int32_t>(bits.clearFirstMarkedBit());
4438 const float value =
4439 MotionEvent::calculateTransformedAxisValue(axis, entry.source,
4440 transformToDisplay, injectedCoords);
4441 pc.setAxisValue(axis, value);
4442 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004443 }
4444}
4445
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004446void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4447 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 if (injectionState) {
4449 injectionState->pendingForegroundDispatches += 1;
4450 }
4451}
4452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004453void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4454 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 if (injectionState) {
4456 injectionState->pendingForegroundDispatches -= 1;
4457
4458 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004459 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 }
4461 }
4462}
4463
chaviw98318de2021-05-19 16:45:23 -05004464const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004465 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004466 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004467 auto it = mWindowHandlesByDisplay.find(displayId);
4468 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004469}
4470
chaviw98318de2021-05-19 16:45:23 -05004471sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004472 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004473 if (windowHandleToken == nullptr) {
4474 return nullptr;
4475 }
4476
Arthur Hungb92218b2018-08-14 12:00:21 +08004477 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004478 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4479 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004480 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004481 return windowHandle;
4482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 }
4484 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004485 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486}
4487
chaviw98318de2021-05-19 16:45:23 -05004488sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4489 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004490 if (windowHandleToken == nullptr) {
4491 return nullptr;
4492 }
4493
chaviw98318de2021-05-19 16:45:23 -05004494 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004495 if (windowHandle->getToken() == windowHandleToken) {
4496 return windowHandle;
4497 }
4498 }
4499 return nullptr;
4500}
4501
chaviw98318de2021-05-19 16:45:23 -05004502sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4503 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004504 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004505 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4506 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004507 if (handle->getId() == windowHandle->getId() &&
4508 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004509 if (windowHandle->getInfo()->displayId != it.first) {
4510 ALOGE("Found window %s in display %" PRId32
4511 ", but it should belong to display %" PRId32,
4512 windowHandle->getName().c_str(), it.first,
4513 windowHandle->getInfo()->displayId);
4514 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004515 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 }
4518 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004519 return nullptr;
4520}
4521
chaviw98318de2021-05-19 16:45:23 -05004522sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004523 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4524 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525}
4526
chaviw98318de2021-05-19 16:45:23 -05004527bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004528 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4529 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004530 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004531 if (connection != nullptr && noInputChannel) {
4532 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4533 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4534 return false;
4535 }
4536
4537 if (connection == nullptr) {
4538 if (!noInputChannel) {
4539 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4540 }
4541 return false;
4542 }
4543 if (!connection->responsive) {
4544 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4545 return false;
4546 }
4547 return true;
4548}
4549
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004550std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4551 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004552 auto connectionIt = mConnectionsByToken.find(token);
4553 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004554 return nullptr;
4555 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004556 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004557}
4558
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004559void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004560 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4561 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004562 // Remove all handles on a display if there are no windows left.
4563 mWindowHandlesByDisplay.erase(displayId);
4564 return;
4565 }
4566
4567 // Since we compare the pointer of input window handles across window updates, we need
4568 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004569 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4570 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4571 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004572 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004573 }
4574
chaviw98318de2021-05-19 16:45:23 -05004575 std::vector<sp<WindowInfoHandle>> newHandles;
4576 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004577 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004578 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004579 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004580 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004581 const bool canReceiveInput =
4582 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4583 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004584 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004585 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004586 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004587 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004588 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004589 }
4590
4591 if (info->displayId != displayId) {
4592 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4593 handle->getName().c_str(), displayId, info->displayId);
4594 continue;
4595 }
4596
Robert Carredd13602020-04-13 17:24:34 -07004597 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4598 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004599 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004600 oldHandle->updateFrom(handle);
4601 newHandles.push_back(oldHandle);
4602 } else {
4603 newHandles.push_back(handle);
4604 }
4605 }
4606
4607 // Insert or replace
4608 mWindowHandlesByDisplay[displayId] = newHandles;
4609}
4610
Arthur Hung72d8dc32020-03-28 00:48:39 +00004611void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004612 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004613 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004614 { // acquire lock
4615 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004616 for (const auto& [displayId, handles] : handlesPerDisplay) {
4617 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004618 }
4619 }
4620 // Wake up poll loop since it may need to make new input dispatching choices.
4621 mLooper->wake();
4622}
4623
Arthur Hungb92218b2018-08-14 12:00:21 +08004624/**
4625 * Called from InputManagerService, update window handle list by displayId that can receive input.
4626 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4627 * If set an empty list, remove all handles from the specific display.
4628 * For focused handle, check if need to change and send a cancel event to previous one.
4629 * For removed handle, check if need to send a cancel event if already in touch.
4630 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004631void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004632 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004633 if (DEBUG_FOCUS) {
4634 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004635 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004636 windowList += iwh->getName() + " ";
4637 }
4638 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640
Prabir Pradhand65552b2021-10-07 11:23:50 -07004641 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004642 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004643 const WindowInfo& info = *window->getInfo();
4644
4645 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4646 const bool noInputWindow = info.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004647 if (noInputWindow && window->getToken() != nullptr) {
4648 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4649 window->getName().c_str());
4650 window->releaseChannel();
4651 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004652
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004653 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004654 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4655 !info.inputConfig.test(
4656 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004657 "%s has feature SPY, but is not a trusted overlay.",
4658 window->getName().c_str());
4659
Prabir Pradhand65552b2021-10-07 11:23:50 -07004660 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004661 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4662 !info.inputConfig.test(
4663 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004664 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4665 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004666 }
4667
Arthur Hung72d8dc32020-03-28 00:48:39 +00004668 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004669 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004671 // Save the old windows' orientation by ID before it gets updated.
4672 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004673 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004674 oldWindowOrientations.emplace(handle->getId(),
4675 handle->getInfo()->transform.getOrientation());
4676 }
4677
chaviw98318de2021-05-19 16:45:23 -05004678 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004679
chaviw98318de2021-05-19 16:45:23 -05004680 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004681 if (mLastHoverWindowHandle &&
4682 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4683 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004684 mLastHoverWindowHandle = nullptr;
4685 }
4686
Vishnu Nairc519ff72021-01-21 08:23:08 -08004687 std::optional<FocusResolver::FocusChanges> changes =
4688 mFocusResolver.setInputWindows(displayId, windowHandles);
4689 if (changes) {
4690 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004693 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4694 mTouchStatesByDisplay.find(displayId);
4695 if (stateIt != mTouchStatesByDisplay.end()) {
4696 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 for (size_t i = 0; i < state.windows.size();) {
4698 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004699 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004700 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004701 ALOGD("Touched window was removed: %s in display %" PRId32,
4702 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004703 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004704 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004705 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4706 if (touchedInputChannel != nullptr) {
4707 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4708 "touched window was removed");
4709 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004710 // Since we are about to drop the touch, cancel the events for the wallpaper as
4711 // well.
4712 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004713 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4714 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004715 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4716 if (wallpaper != nullptr) {
4717 sp<Connection> wallpaperConnection =
4718 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004719 if (wallpaperConnection != nullptr) {
4720 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4721 options);
4722 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004723 }
4724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004726 state.windows.erase(state.windows.begin() + i);
4727 } else {
4728 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 }
4730 }
arthurhungb89ccb02020-12-30 16:19:01 +08004731
arthurhung6d4bed92021-03-17 11:59:33 +08004732 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004733 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004734 if (mDragState &&
4735 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004736 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004737 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004738 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004739 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004740
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004741 // Determine if the orientation of any of the input windows have changed, and cancel all
4742 // pointer events if necessary.
4743 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4744 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4745 if (newWindowHandle != nullptr &&
4746 newWindowHandle->getInfo()->transform.getOrientation() !=
4747 oldWindowOrientations[oldWindowHandle->getId()]) {
4748 std::shared_ptr<InputChannel> inputChannel =
4749 getInputChannelLocked(newWindowHandle->getToken());
4750 if (inputChannel != nullptr) {
4751 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4752 "touched window's orientation changed");
4753 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004754 }
4755 }
4756 }
4757
Arthur Hung72d8dc32020-03-28 00:48:39 +00004758 // Release information for windows that are no longer present.
4759 // This ensures that unused input channels are released promptly.
4760 // Otherwise, they might stick around until the window handle is destroyed
4761 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004762 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004763 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004764 if (DEBUG_FOCUS) {
4765 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004766 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004767 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004768 }
chaviw291d88a2019-02-14 10:33:58 -08004769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770}
4771
4772void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004773 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004774 if (DEBUG_FOCUS) {
4775 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4776 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4777 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004778 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004779 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004780 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 } // release lock
4782
4783 // Wake up poll loop since it may need to make new input dispatching choices.
4784 mLooper->wake();
4785}
4786
Vishnu Nair599f1412021-06-21 10:39:58 -07004787void InputDispatcher::setFocusedApplicationLocked(
4788 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4789 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4790 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4791
4792 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4793 return; // This application is already focused. No need to wake up or change anything.
4794 }
4795
4796 // Set the new application handle.
4797 if (inputApplicationHandle != nullptr) {
4798 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4799 } else {
4800 mFocusedApplicationHandlesByDisplay.erase(displayId);
4801 }
4802
4803 // No matter what the old focused application was, stop waiting on it because it is
4804 // no longer focused.
4805 resetNoFocusedWindowTimeoutLocked();
4806}
4807
Tiger Huang721e26f2018-07-24 22:26:19 +08004808/**
4809 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4810 * the display not specified.
4811 *
4812 * We track any unreleased events for each window. If a window loses the ability to receive the
4813 * released event, we will send a cancel event to it. So when the focused display is changed, we
4814 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4815 * display. The display-specified events won't be affected.
4816 */
4817void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004818 if (DEBUG_FOCUS) {
4819 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4820 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004821 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004822 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004823
4824 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004825 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004826 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004827 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004828 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004829 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004830 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 CancelationOptions
4832 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4833 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004834 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004835 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4836 }
4837 }
4838 mFocusedDisplayId = displayId;
4839
Chris Ye3c2d6f52020-08-09 10:39:48 -07004840 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004841 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004842 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004843
Vishnu Nairad321cd2020-08-20 16:40:21 -07004844 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004845 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004846 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004847 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004848 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004849 }
4850 }
4851 }
4852
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004853 if (DEBUG_FOCUS) {
4854 logDispatchStateLocked();
4855 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004856 } // release lock
4857
4858 // Wake up poll loop since it may need to make new input dispatching choices.
4859 mLooper->wake();
4860}
4861
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004863 if (DEBUG_FOCUS) {
4864 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866
4867 bool changed;
4868 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004869 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870
4871 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4872 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 }
4875
4876 if (mDispatchEnabled && !enabled) {
4877 resetAndDropEverythingLocked("dispatcher is being disabled");
4878 }
4879
4880 mDispatchEnabled = enabled;
4881 mDispatchFrozen = frozen;
4882 changed = true;
4883 } else {
4884 changed = false;
4885 }
4886
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004887 if (DEBUG_FOCUS) {
4888 logDispatchStateLocked();
4889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 } // release lock
4891
4892 if (changed) {
4893 // Wake up poll loop since it may need to make new input dispatching choices.
4894 mLooper->wake();
4895 }
4896}
4897
4898void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004899 if (DEBUG_FOCUS) {
4900 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902
4903 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004904 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
4906 if (mInputFilterEnabled == enabled) {
4907 return;
4908 }
4909
4910 mInputFilterEnabled = enabled;
4911 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4912 } // release lock
4913
4914 // Wake up poll loop since there might be work to do to drop everything.
4915 mLooper->wake();
4916}
4917
Antonio Kantekea47acb2021-12-23 12:41:25 -08004918bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4919 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004920 bool needWake = false;
4921 {
4922 std::scoped_lock lock(mLock);
4923 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004924 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004925 }
4926 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004927 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4928 "hasPermission=%s)",
4929 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4930 }
4931 if (!hasPermission) {
4932 const sp<IBinder> focusedToken =
4933 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4934
Antonio Kantek019eb662022-02-08 13:41:52 -08004935 // TODO(b/218541064): if no window is currently focused, then we need to check the last
Antonio Kantekea47acb2021-12-23 12:41:25 -08004936 // interacted window (within 1 second timeout). We should allow touch mode change
4937 // if the last interacted window owner's pid/uid match the calling ones.
4938 if (focusedToken == nullptr) {
4939 return false;
4940 }
4941 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4942 if (windowHandle == nullptr) {
4943 return false;
4944 }
4945 const WindowInfo* windowInfo = windowHandle->getInfo();
4946 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4947 return false;
4948 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004949 }
4950
4951 // TODO(b/198499018): Store touch mode per display.
4952 mInTouchMode = inTouchMode;
4953
Antonio Kantekf16f2832021-09-28 04:39:20 +00004954 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4955 needWake = enqueueInboundEventLocked(std::move(entry));
4956 } // release lock
4957
4958 if (needWake) {
4959 mLooper->wake();
4960 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004961 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004962}
4963
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004964void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4965 if (opacity < 0 || opacity > 1) {
4966 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4967 return;
4968 }
4969
4970 std::scoped_lock lock(mLock);
4971 mMaximumObscuringOpacityForTouch = opacity;
4972}
4973
4974void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4975 std::scoped_lock lock(mLock);
4976 mBlockUntrustedTouchesMode = mode;
4977}
4978
Arthur Hungabbb9d82021-09-01 14:52:30 +00004979std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4980 const sp<IBinder>& token) {
4981 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4982 for (TouchedWindow& w : state.windows) {
4983 if (w.windowHandle->getToken() == token) {
4984 return std::make_pair(&state, &w);
4985 }
4986 }
4987 }
4988 return std::make_pair(nullptr, nullptr);
4989}
4990
arthurhungb89ccb02020-12-30 16:19:01 +08004991bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4992 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004993 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004994 if (DEBUG_FOCUS) {
4995 ALOGD("Trivial transfer to same window.");
4996 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004997 return true;
4998 }
4999
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005001 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002
Arthur Hungabbb9d82021-09-01 14:52:30 +00005003 // Find the target touch state and touched window by fromToken.
5004 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5005 if (state == nullptr || touchedWindow == nullptr) {
5006 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 return false;
5008 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005009
5010 const int32_t displayId = state->displayId;
5011 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5012 if (toWindowHandle == nullptr) {
5013 ALOGW("Cannot transfer focus because to window not found.");
5014 return false;
5015 }
5016
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005017 if (DEBUG_FOCUS) {
5018 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005019 touchedWindow->windowHandle->getName().c_str(),
5020 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 }
5022
Arthur Hungabbb9d82021-09-01 14:52:30 +00005023 // Erase old window.
5024 int32_t oldTargetFlags = touchedWindow->targetFlags;
5025 BitSet32 pointerIds = touchedWindow->pointerIds;
5026 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027
Arthur Hungabbb9d82021-09-01 14:52:30 +00005028 // Add new window.
5029 int32_t newTargetFlags = oldTargetFlags &
5030 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5031 InputTarget::FLAG_DISPATCH_AS_IS);
5032 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033
Arthur Hungabbb9d82021-09-01 14:52:30 +00005034 // Store the dragging window.
5035 if (isDragDrop) {
5036 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 }
5038
Arthur Hungabbb9d82021-09-01 14:52:30 +00005039 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005040 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5041 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005042 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005043 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005044 CancelationOptions
5045 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5046 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005048 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049 }
5050
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005051 if (DEBUG_FOCUS) {
5052 logDispatchStateLocked();
5053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005054 } // release lock
5055
5056 // Wake up poll loop since it may need to make new input dispatching choices.
5057 mLooper->wake();
5058 return true;
5059}
5060
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005061// Binder call
5062bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5063 sp<IBinder> fromToken;
5064 { // acquire lock
5065 std::scoped_lock _l(mLock);
5066
Arthur Hungabbb9d82021-09-01 14:52:30 +00005067 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5068 [](const auto& pair) { return pair.second.windows.size() == 1; });
5069 if (it == mTouchStatesByDisplay.end()) {
5070 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5071 return false;
5072 }
5073 const int32_t displayId = it->first;
5074 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005075 if (toWindowHandle == nullptr) {
5076 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5077 return false;
5078 }
5079
Arthur Hungabbb9d82021-09-01 14:52:30 +00005080 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005081 const TouchedWindow& touchedWindow = state.windows[0];
5082 fromToken = touchedWindow.windowHandle->getToken();
5083 } // release lock
5084
5085 return transferTouchFocus(fromToken, destChannelToken);
5086}
5087
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005089 if (DEBUG_FOCUS) {
5090 ALOGD("Resetting and dropping all events (%s).", reason);
5091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092
5093 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5094 synthesizeCancelationEventsForAllConnectionsLocked(options);
5095
5096 resetKeyRepeatLocked();
5097 releasePendingEventLocked();
5098 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005101 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005102 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005104 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105}
5106
5107void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005108 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 dumpDispatchStateLocked(dump);
5110
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005111 std::istringstream stream(dump);
5112 std::string line;
5113
5114 while (std::getline(stream, line, '\n')) {
5115 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 }
5117}
5118
Prabir Pradhan99987712020-11-10 18:43:05 -08005119std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5120 std::string dump;
5121
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005122 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5123 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005124
5125 std::string windowName = "None";
5126 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005127 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005128 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5129 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5130 : "token has capture without window";
5131 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005132 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005133
5134 return dump;
5135}
5136
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005137void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005138 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5139 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5140 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005141 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142
Tiger Huang721e26f2018-07-24 22:26:19 +08005143 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5144 dump += StringPrintf(INDENT "FocusedApplications:\n");
5145 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5146 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005147 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005148 const std::chrono::duration timeout =
5149 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005150 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005151 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005152 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005155 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005157
Vishnu Nairc519ff72021-01-21 08:23:08 -08005158 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005159 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005161 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005162 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005163 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5164 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005165 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005166 state.displayId, toString(state.down), toString(state.split),
5167 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005168 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005169 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005170 for (size_t i = 0; i < state.windows.size(); i++) {
5171 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005172 dump += StringPrintf(INDENT4
5173 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5174 i, touchedWindow.windowHandle->getName().c_str(),
5175 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005176 }
5177 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005178 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 }
5181 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005182 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 }
5184
arthurhung6d4bed92021-03-17 11:59:33 +08005185 if (mDragState) {
5186 dump += StringPrintf(INDENT "DragState:\n");
5187 mDragState->dump(dump, INDENT2);
5188 }
5189
Arthur Hungb92218b2018-08-14 12:00:21 +08005190 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005191 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5192 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5193 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5194 const auto& displayInfo = it->second;
5195 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5196 displayInfo.logicalHeight);
5197 displayInfo.transform.dump(dump, "transform", INDENT4);
5198 } else {
5199 dump += INDENT2 "No DisplayInfo found!\n";
5200 }
5201
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005202 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005203 dump += INDENT2 "Windows:\n";
5204 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005205 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5206 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005208 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005209 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005210 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005211 "applicationInfo.name=%s, "
5212 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005213 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005214 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005215 windowInfo->displayId,
5216 windowInfo->inputConfig.string().c_str(),
5217 windowInfo->alpha, windowInfo->frameLeft,
5218 windowInfo->frameTop, windowInfo->frameRight,
5219 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005220 windowInfo->applicationInfo.name.c_str(),
5221 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005222 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005223 dump += StringPrintf(", inputFeatures=%s",
5224 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005225 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005226 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005227 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005228 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005229 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005230 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005231 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005232 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005233 }
5234 } else {
5235 dump += INDENT2 "Windows: <none>\n";
5236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 }
5238 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005239 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 }
5241
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005242 if (!mGlobalMonitorsByDisplay.empty()) {
5243 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5244 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005245 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005248 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 }
5250
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005251 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252
5253 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005254 if (!mRecentQueue.empty()) {
5255 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005256 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005257 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005258 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005259 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 }
5261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005262 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
5264
5265 // Dump event currently being dispatched.
5266 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005267 dump += INDENT "PendingEvent:\n";
5268 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005269 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005270 dump += StringPrintf(", age=%" PRId64 "ms\n",
5271 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005273 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 }
5275
5276 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005277 if (!mInboundQueue.empty()) {
5278 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005279 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005280 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005281 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005282 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 }
5284 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005285 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 }
5287
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005288 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005290 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5291 const KeyReplacement& replacement = pair.first;
5292 int32_t newKeyCode = pair.second;
5293 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005294 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005295 }
5296 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005297 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005298 }
5299
Prabir Pradhancef936d2021-07-21 16:17:52 +00005300 if (!mCommandQueue.empty()) {
5301 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5302 } else {
5303 dump += INDENT "CommandQueue: <empty>\n";
5304 }
5305
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005306 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005307 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005308 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005309 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005310 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005311 connection->inputChannel->getFd().get(),
5312 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005313 connection->getWindowName().c_str(),
5314 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005315 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005317 if (!connection->outboundQueue.empty()) {
5318 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5319 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005320 dump += dumpQueue(connection->outboundQueue, currentTime);
5321
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005323 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005326 if (!connection->waitQueue.empty()) {
5327 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5328 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005329 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005331 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 }
5333 }
5334 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005335 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 }
5337
5338 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005339 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5340 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005342 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 }
5344
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005345 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005346 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5347 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5348 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005349 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005350 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351}
5352
Michael Wright3dd60e22019-03-27 22:06:44 +00005353void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5354 const size_t numMonitors = monitors.size();
5355 for (size_t i = 0; i < numMonitors; i++) {
5356 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005357 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005358 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5359 dump += "\n";
5360 }
5361}
5362
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005363class LooperEventCallback : public LooperCallback {
5364public:
5365 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5366 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5367
5368private:
5369 std::function<int(int events)> mCallback;
5370};
5371
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005372Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005373 if (DEBUG_CHANNEL_CREATION) {
5374 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005377 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005378 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005379 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005380
5381 if (result) {
5382 return base::Error(result) << "Failed to open input channel pair with name " << name;
5383 }
5384
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005386 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005387 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005388 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005389 sp<Connection> connection =
5390 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005392 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5393 ALOGE("Created a new connection, but the token %p is already known", token.get());
5394 }
5395 mConnectionsByToken.emplace(token, connection);
5396
5397 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5398 this, std::placeholders::_1, token);
5399
5400 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 } // release lock
5402
5403 // Wake the looper because some connections have changed.
5404 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005405 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406}
5407
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005408Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005409 const std::string& name,
5410 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005411 std::shared_ptr<InputChannel> serverChannel;
5412 std::unique_ptr<InputChannel> clientChannel;
5413 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5414 if (result) {
5415 return base::Error(result) << "Failed to open input channel pair with name " << name;
5416 }
5417
Michael Wright3dd60e22019-03-27 22:06:44 +00005418 { // acquire lock
5419 std::scoped_lock _l(mLock);
5420
5421 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005422 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5423 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005424 }
5425
Garfield Tan15601662020-09-22 15:32:38 -07005426 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005427 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005428 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005429
5430 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5431 ALOGE("Created a new connection, but the token %p is already known", token.get());
5432 }
5433 mConnectionsByToken.emplace(token, connection);
5434 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5435 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005436
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005437 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005438
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005439 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005440 }
Garfield Tan15601662020-09-22 15:32:38 -07005441
Michael Wright3dd60e22019-03-27 22:06:44 +00005442 // Wake the looper because some connections have changed.
5443 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005444 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005445}
5446
Garfield Tan15601662020-09-22 15:32:38 -07005447status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005449 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450
Garfield Tan15601662020-09-22 15:32:38 -07005451 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 if (status) {
5453 return status;
5454 }
5455 } // release lock
5456
5457 // Wake the poll loop because removing the connection may have changed the current
5458 // synchronization state.
5459 mLooper->wake();
5460 return OK;
5461}
5462
Garfield Tan15601662020-09-22 15:32:38 -07005463status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5464 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005465 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005466 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005467 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 return BAD_VALUE;
5469 }
5470
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005471 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005472
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005474 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 }
5476
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005477 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478
5479 nsecs_t currentTime = now();
5480 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5481
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005482 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 return OK;
5484}
5485
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005486void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005487 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5488 auto& [displayId, monitors] = *it;
5489 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5490 return monitor.inputChannel->getConnectionToken() == connectionToken;
5491 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005492
Michael Wright3dd60e22019-03-27 22:06:44 +00005493 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005494 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005495 } else {
5496 ++it;
5497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 }
5499}
5500
Michael Wright3dd60e22019-03-27 22:06:44 +00005501status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005502 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005503
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005504 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5505 if (!requestingChannel) {
5506 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5507 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005508 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005509
5510 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5511 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5512 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5513 " Ignoring.");
5514 return BAD_VALUE;
5515 }
5516
5517 TouchState& state = *statePtr;
5518
5519 // Send cancel events to all the input channels we're stealing from.
5520 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5521 "input channel stole pointer stream");
5522 options.deviceId = state.deviceId;
5523 options.displayId = state.displayId;
5524 std::string canceledWindows;
5525 for (const TouchedWindow& window : state.windows) {
5526 const std::shared_ptr<InputChannel> channel =
5527 getInputChannelLocked(window.windowHandle->getToken());
5528 if (channel != nullptr && channel->getConnectionToken() != token) {
5529 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5530 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5531 canceledWindows += channel->getName();
5532 }
5533 }
5534 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5535 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5536 canceledWindows.c_str());
5537
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005538 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005539 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005540 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005541 return OK;
5542}
5543
Prabir Pradhan99987712020-11-10 18:43:05 -08005544void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5545 { // acquire lock
5546 std::scoped_lock _l(mLock);
5547 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005548 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005549 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5550 windowHandle != nullptr ? windowHandle->getName().c_str()
5551 : "token without window");
5552 }
5553
Vishnu Nairc519ff72021-01-21 08:23:08 -08005554 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005555 if (focusedToken != windowToken) {
5556 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5557 enabled ? "enable" : "disable");
5558 return;
5559 }
5560
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005561 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005562 ALOGW("Ignoring request to %s Pointer Capture: "
5563 "window has %s requested pointer capture.",
5564 enabled ? "enable" : "disable", enabled ? "already" : "not");
5565 return;
5566 }
5567
Christine Franksb768bb42021-11-29 12:11:31 -08005568 if (enabled) {
5569 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5570 mIneligibleDisplaysForPointerCapture.end(),
5571 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5572 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5573 return;
5574 }
5575 }
5576
Prabir Pradhan99987712020-11-10 18:43:05 -08005577 setPointerCaptureLocked(enabled);
5578 } // release lock
5579
5580 // Wake the thread to process command entries.
5581 mLooper->wake();
5582}
5583
Christine Franksb768bb42021-11-29 12:11:31 -08005584void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5585 { // acquire lock
5586 std::scoped_lock _l(mLock);
5587 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5588 if (!isEligible) {
5589 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5590 }
5591 } // release lock
5592}
5593
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005594std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5595 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005596 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005597 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005598 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005599 }
5600 }
5601 }
5602 return std::nullopt;
5603}
5604
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005605sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005606 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005607 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005608 }
5609
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005610 for (const auto& [token, connection] : mConnectionsByToken) {
5611 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005612 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
5614 }
Robert Carr4e670e52018-08-15 13:26:12 -07005615
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005616 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617}
5618
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005619std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5620 sp<Connection> connection = getConnectionLocked(connectionToken);
5621 if (connection == nullptr) {
5622 return "<nullptr>";
5623 }
5624 return connection->getInputChannelName();
5625}
5626
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005627void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005628 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005629 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005630}
5631
Prabir Pradhancef936d2021-07-21 16:17:52 +00005632void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5633 const sp<Connection>& connection, uint32_t seq,
5634 bool handled, nsecs_t consumeTime) {
5635 // Handle post-event policy actions.
5636 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5637 if (dispatchEntryIt == connection->waitQueue.end()) {
5638 return;
5639 }
5640 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5641 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5642 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5643 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5644 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5645 }
5646 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5647 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5648 connection->inputChannel->getConnectionToken(),
5649 dispatchEntry->deliveryTime, consumeTime, finishTime);
5650 }
5651
5652 bool restartEvent;
5653 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5654 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5655 restartEvent =
5656 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5657 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5658 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5659 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5660 handled);
5661 } else {
5662 restartEvent = false;
5663 }
5664
5665 // Dequeue the event and start the next cycle.
5666 // Because the lock might have been released, it is possible that the
5667 // contents of the wait queue to have been drained, so we need to double-check
5668 // a few things.
5669 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5670 if (dispatchEntryIt != connection->waitQueue.end()) {
5671 dispatchEntry = *dispatchEntryIt;
5672 connection->waitQueue.erase(dispatchEntryIt);
5673 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5674 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5675 if (!connection->responsive) {
5676 connection->responsive = isConnectionResponsive(*connection);
5677 if (connection->responsive) {
5678 // The connection was unresponsive, and now it's responsive.
5679 processConnectionResponsiveLocked(*connection);
5680 }
5681 }
5682 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005683 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005684 connection->outboundQueue.push_front(dispatchEntry);
5685 traceOutboundQueueLength(*connection);
5686 } else {
5687 releaseDispatchEntry(dispatchEntry);
5688 }
5689 }
5690
5691 // Start the next dispatch cycle for this connection.
5692 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693}
5694
Prabir Pradhancef936d2021-07-21 16:17:52 +00005695void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5696 const sp<IBinder>& newToken) {
5697 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5698 scoped_unlock unlock(mLock);
5699 mPolicy->notifyFocusChanged(oldToken, newToken);
5700 };
5701 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702}
5703
Prabir Pradhancef936d2021-07-21 16:17:52 +00005704void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5705 auto command = [this, token, x, y]() REQUIRES(mLock) {
5706 scoped_unlock unlock(mLock);
5707 mPolicy->notifyDropWindow(token, x, y);
5708 };
5709 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005710}
5711
Prabir Pradhancef936d2021-07-21 16:17:52 +00005712void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5713 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5714 scoped_unlock unlock(mLock);
5715 mPolicy->notifyUntrustedTouch(obscuringPackage);
5716 };
5717 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005718}
5719
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005720void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5721 if (connection == nullptr) {
5722 LOG_ALWAYS_FATAL("Caller must check for nullness");
5723 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005724 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5725 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005726 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005727 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005728 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005729 return;
5730 }
5731 /**
5732 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5733 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5734 * has changed. This could cause newer entries to time out before the already dispatched
5735 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5736 * processes the events linearly. So providing information about the oldest entry seems to be
5737 * most useful.
5738 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005739 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005740 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5741 std::string reason =
5742 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005743 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005744 ns2ms(currentWait),
5745 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005746 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005747 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005748
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005749 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5750
5751 // Stop waking up for events on this connection, it is already unresponsive
5752 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753}
5754
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005755void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5756 std::string reason =
5757 StringPrintf("%s does not have a focused window", application->getName().c_str());
5758 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005759
Prabir Pradhancef936d2021-07-21 16:17:52 +00005760 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5761 scoped_unlock unlock(mLock);
5762 mPolicy->notifyNoFocusedWindowAnr(application);
5763 };
5764 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005765}
5766
chaviw98318de2021-05-19 16:45:23 -05005767void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005768 const std::string& reason) {
5769 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5770 updateLastAnrStateLocked(windowLabel, reason);
5771}
5772
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005773void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5774 const std::string& reason) {
5775 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005776 updateLastAnrStateLocked(windowLabel, reason);
5777}
5778
5779void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5780 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005782 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 struct tm tm;
5784 localtime_r(&t, &tm);
5785 char timestr[64];
5786 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005787 mLastAnrState.clear();
5788 mLastAnrState += INDENT "ANR:\n";
5789 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005790 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5791 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005792 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793}
5794
Prabir Pradhancef936d2021-07-21 16:17:52 +00005795void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5796 KeyEntry& entry) {
5797 const KeyEvent event = createKeyEvent(entry);
5798 nsecs_t delay = 0;
5799 { // release lock
5800 scoped_unlock unlock(mLock);
5801 android::base::Timer t;
5802 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5803 entry.policyFlags);
5804 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5805 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5806 std::to_string(t.duration().count()).c_str());
5807 }
5808 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809
5810 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005811 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005812 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005813 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005815 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5816 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818}
5819
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005820void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005821 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5822 scoped_unlock unlock(mLock);
5823 mPolicy->notifyMonitorUnresponsive(pid, reason);
5824 };
5825 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005826}
5827
Prabir Pradhancef936d2021-07-21 16:17:52 +00005828void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005829 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005830 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5831 scoped_unlock unlock(mLock);
5832 mPolicy->notifyWindowUnresponsive(token, reason);
5833 };
5834 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005835}
5836
5837void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005838 auto command = [this, pid]() REQUIRES(mLock) {
5839 scoped_unlock unlock(mLock);
5840 mPolicy->notifyMonitorResponsive(pid);
5841 };
5842 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005843}
5844
Prabir Pradhancef936d2021-07-21 16:17:52 +00005845void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5846 auto command = [this, connectionToken]() REQUIRES(mLock) {
5847 scoped_unlock unlock(mLock);
5848 mPolicy->notifyWindowResponsive(connectionToken);
5849 };
5850 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005851}
5852
5853/**
5854 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5855 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5856 * command entry to the command queue.
5857 */
5858void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5859 std::string reason) {
5860 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5861 if (connection.monitor) {
5862 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5863 reason.c_str());
5864 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5865 if (!pid.has_value()) {
5866 ALOGE("Could not find unresponsive monitor for connection %s",
5867 connection.inputChannel->getName().c_str());
5868 return;
5869 }
5870 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5871 return;
5872 }
5873 // If not a monitor, must be a window
5874 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5875 reason.c_str());
5876 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5877}
5878
5879/**
5880 * Tell the policy that a connection has become responsive so that it can stop ANR.
5881 */
5882void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5883 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5884 if (connection.monitor) {
5885 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5886 if (!pid.has_value()) {
5887 ALOGE("Could not find responsive monitor for connection %s",
5888 connection.inputChannel->getName().c_str());
5889 return;
5890 }
5891 sendMonitorResponsiveCommandLocked(pid.value());
5892 return;
5893 }
5894 // If not a monitor, must be a window
5895 sendWindowResponsiveCommandLocked(connectionToken);
5896}
5897
Prabir Pradhancef936d2021-07-21 16:17:52 +00005898bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005899 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005900 KeyEntry& keyEntry, bool handled) {
5901 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005902 if (!handled) {
5903 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005904 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005905 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005906 return false;
5907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005909 // Get the fallback key state.
5910 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005912 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005913 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005914 connection->inputState.removeFallbackKey(originalKeyCode);
5915 }
5916
5917 if (handled || !dispatchEntry->hasForegroundTarget()) {
5918 // If the application handles the original key for which we previously
5919 // generated a fallback or if the window is not a foreground window,
5920 // then cancel the associated fallback key, if any.
5921 if (fallbackKeyCode != -1) {
5922 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005923 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5924 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5925 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5926 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5927 keyEntry.policyFlags);
5928 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005929 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005930 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931
5932 mLock.unlock();
5933
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005934 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005935 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936
5937 mLock.lock();
5938
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005939 // Cancel the fallback key.
5940 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005942 "application handled the original non-fallback key "
5943 "or is no longer a foreground target, "
5944 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 options.keyCode = fallbackKeyCode;
5946 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 connection->inputState.removeFallbackKey(originalKeyCode);
5949 }
5950 } else {
5951 // If the application did not handle a non-fallback key, first check
5952 // that we are in a good state to perform unhandled key event processing
5953 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005954 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005956 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5957 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5958 "since this is not an initial down. "
5959 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5960 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5961 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005962 return false;
5963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005965 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005966 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5967 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5968 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5969 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5970 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005972
5973 mLock.unlock();
5974
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005975 bool fallback =
5976 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005977 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005978
5979 mLock.lock();
5980
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005981 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005982 connection->inputState.removeFallbackKey(originalKeyCode);
5983 return false;
5984 }
5985
5986 // Latch the fallback keycode for this key on an initial down.
5987 // The fallback keycode cannot change at any other point in the lifecycle.
5988 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005990 fallbackKeyCode = event.getKeyCode();
5991 } else {
5992 fallbackKeyCode = AKEYCODE_UNKNOWN;
5993 }
5994 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5995 }
5996
5997 ALOG_ASSERT(fallbackKeyCode != -1);
5998
5999 // Cancel the fallback key if the policy decides not to send it anymore.
6000 // We will continue to dispatch the key to the policy but we will no
6001 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006002 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6003 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006004 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6005 if (fallback) {
6006 ALOGD("Unhandled key event: Policy requested to send key %d"
6007 "as a fallback for %d, but on the DOWN it had requested "
6008 "to send %d instead. Fallback canceled.",
6009 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6010 } else {
6011 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6012 "but on the DOWN it had requested to send %d. "
6013 "Fallback canceled.",
6014 originalKeyCode, fallbackKeyCode);
6015 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006016 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006017
6018 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6019 "canceling fallback, policy no longer desires it");
6020 options.keyCode = fallbackKeyCode;
6021 synthesizeCancelationEventsForConnectionLocked(connection, options);
6022
6023 fallback = false;
6024 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006025 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006026 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006027 }
6028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006030 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6031 {
6032 std::string msg;
6033 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6034 connection->inputState.getFallbackKeys();
6035 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6036 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6037 }
6038 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6039 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006041 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042
6043 if (fallback) {
6044 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006045 keyEntry.eventTime = event.getEventTime();
6046 keyEntry.deviceId = event.getDeviceId();
6047 keyEntry.source = event.getSource();
6048 keyEntry.displayId = event.getDisplayId();
6049 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6050 keyEntry.keyCode = fallbackKeyCode;
6051 keyEntry.scanCode = event.getScanCode();
6052 keyEntry.metaState = event.getMetaState();
6053 keyEntry.repeatCount = event.getRepeatCount();
6054 keyEntry.downTime = event.getDownTime();
6055 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006057 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6058 ALOGD("Unhandled key event: Dispatching fallback key. "
6059 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6060 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6061 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006062 return true; // restart the event
6063 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006064 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6065 ALOGD("Unhandled key event: No fallback key.");
6066 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006067
6068 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006069 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070 }
6071 }
6072 return false;
6073}
6074
Prabir Pradhancef936d2021-07-21 16:17:52 +00006075bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006076 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006077 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078 return false;
6079}
6080
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081void InputDispatcher::traceInboundQueueLengthLocked() {
6082 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006083 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006084 }
6085}
6086
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006087void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 if (ATRACE_ENABLED()) {
6089 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006090 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6091 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 }
6093}
6094
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006095void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 if (ATRACE_ENABLED()) {
6097 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006098 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6099 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100 }
6101}
6102
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006103void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006104 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006106 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 dumpDispatchStateLocked(dump);
6108
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006109 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006110 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006111 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112 }
6113}
6114
6115void InputDispatcher::monitor() {
6116 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006117 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006119 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120}
6121
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006122/**
6123 * Wake up the dispatcher and wait until it processes all events and commands.
6124 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6125 * this method can be safely called from any thread, as long as you've ensured that
6126 * the work you are interested in completing has already been queued.
6127 */
6128bool InputDispatcher::waitForIdle() {
6129 /**
6130 * Timeout should represent the longest possible time that a device might spend processing
6131 * events and commands.
6132 */
6133 constexpr std::chrono::duration TIMEOUT = 100ms;
6134 std::unique_lock lock(mLock);
6135 mLooper->wake();
6136 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6137 return result == std::cv_status::no_timeout;
6138}
6139
Vishnu Naire798b472020-07-23 13:52:21 -07006140/**
6141 * Sets focus to the window identified by the token. This must be called
6142 * after updating any input window handles.
6143 *
6144 * Params:
6145 * request.token - input channel token used to identify the window that should gain focus.
6146 * request.focusedToken - the token that the caller expects currently to be focused. If the
6147 * specified token does not match the currently focused window, this request will be dropped.
6148 * If the specified focused token matches the currently focused window, the call will succeed.
6149 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6150 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6151 * when requesting the focus change. This determines which request gets
6152 * precedence if there is a focus change request from another source such as pointer down.
6153 */
Vishnu Nair958da932020-08-21 17:12:37 -07006154void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6155 { // acquire lock
6156 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006157 std::optional<FocusResolver::FocusChanges> changes =
6158 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6159 if (changes) {
6160 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006161 }
6162 } // release lock
6163 // Wake up poll loop since it may need to make new input dispatching choices.
6164 mLooper->wake();
6165}
6166
Vishnu Nairc519ff72021-01-21 08:23:08 -08006167void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6168 if (changes.oldFocus) {
6169 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006170 if (focusedInputChannel) {
6171 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6172 "focus left window");
6173 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006174 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006175 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006176 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006177 if (changes.newFocus) {
6178 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006179 }
6180
Prabir Pradhan99987712020-11-10 18:43:05 -08006181 // If a window has pointer capture, then it must have focus. We need to ensure that this
6182 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6183 // If the window loses focus before it loses pointer capture, then the window can be in a state
6184 // where it has pointer capture but not focus, violating the contract. Therefore we must
6185 // dispatch the pointer capture event before the focus event. Since focus events are added to
6186 // the front of the queue (above), we add the pointer capture event to the front of the queue
6187 // after the focus events are added. This ensures the pointer capture event ends up at the
6188 // front.
6189 disablePointerCaptureForcedLocked();
6190
Vishnu Nairc519ff72021-01-21 08:23:08 -08006191 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006192 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006193 }
6194}
Vishnu Nair958da932020-08-21 17:12:37 -07006195
Prabir Pradhan99987712020-11-10 18:43:05 -08006196void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006197 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006198 return;
6199 }
6200
6201 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6202
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006203 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006204 setPointerCaptureLocked(false);
6205 }
6206
6207 if (!mWindowTokenWithPointerCapture) {
6208 // No need to send capture changes because no window has capture.
6209 return;
6210 }
6211
6212 if (mPendingEvent != nullptr) {
6213 // Move the pending event to the front of the queue. This will give the chance
6214 // for the pending event to be dropped if it is a captured event.
6215 mInboundQueue.push_front(mPendingEvent);
6216 mPendingEvent = nullptr;
6217 }
6218
6219 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006220 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006221 mInboundQueue.push_front(std::move(entry));
6222}
6223
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006224void InputDispatcher::setPointerCaptureLocked(bool enable) {
6225 mCurrentPointerCaptureRequest.enable = enable;
6226 mCurrentPointerCaptureRequest.seq++;
6227 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006228 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006229 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230 };
6231 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006232}
6233
Vishnu Nair599f1412021-06-21 10:39:58 -07006234void InputDispatcher::displayRemoved(int32_t displayId) {
6235 { // acquire lock
6236 std::scoped_lock _l(mLock);
6237 // Set an empty list to remove all handles from the specific display.
6238 setInputWindowsLocked(/* window handles */ {}, displayId);
6239 setFocusedApplicationLocked(displayId, nullptr);
6240 // Call focus resolver to clean up stale requests. This must be called after input windows
6241 // have been removed for the removed display.
6242 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006243 // Reset pointer capture eligibility, regardless of previous state.
6244 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006245 } // release lock
6246
6247 // Wake up poll loop since it may need to make new input dispatching choices.
6248 mLooper->wake();
6249}
6250
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006251void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6252 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006253 // The listener sends the windows as a flattened array. Separate the windows by display for
6254 // more convenient parsing.
6255 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006256 for (const auto& info : windowInfos) {
6257 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6258 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6259 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006260
6261 { // acquire lock
6262 std::scoped_lock _l(mLock);
6263 mDisplayInfos.clear();
6264 for (const auto& displayInfo : displayInfos) {
6265 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6266 }
6267
6268 for (const auto& [displayId, handles] : handlesPerDisplay) {
6269 setInputWindowsLocked(handles, displayId);
6270 }
6271 }
6272 // Wake up poll loop since it may need to make new input dispatching choices.
6273 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006274}
6275
Vishnu Nair062a8672021-09-03 16:07:44 -07006276bool InputDispatcher::shouldDropInput(
6277 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6278 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6279 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6280 isWindowObscuredLocked(windowHandle))) {
6281 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6282 "%" PRId32 ".",
6283 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6284 windowHandle->getInfo()->inputFeatures.string().c_str(),
6285 windowHandle->getInfo()->displayId);
6286 return true;
6287 }
6288 return false;
6289}
6290
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006291void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6292 const std::vector<gui::WindowInfo>& windowInfos,
6293 const std::vector<DisplayInfo>& displayInfos) {
6294 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6295}
6296
Arthur Hungdfd528e2021-12-08 13:23:04 +00006297void InputDispatcher::cancelCurrentTouch() {
6298 {
6299 std::scoped_lock _l(mLock);
6300 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6301 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6302 "cancel current touch");
6303 synthesizeCancelationEventsForAllConnectionsLocked(options);
6304
6305 mTouchStatesByDisplay.clear();
6306 mLastHoverWindowHandle.clear();
6307 }
6308 // Wake up poll loop since there might be work to do.
6309 mLooper->wake();
6310}
6311
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006312void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6313 std::scoped_lock _l(mLock);
6314 mMonitorDispatchingTimeout = timeout;
6315}
6316
Garfield Tane84e6f92019-08-29 17:28:41 -07006317} // namespace android::inputdispatcher