blob: d982b3775966b880c99baf00b66e9c8fdbd7b359 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000031#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010033#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
Michael Wright44753b12020-07-08 13:48:11 +010036#include <cerrno>
37#include <cinttypes>
38#include <climits>
39#include <cstddef>
40#include <ctime>
41#include <queue>
42#include <sstream>
43
44#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070045#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010046
Michael Wrightd02c5b62014-02-10 15:10:22 -080047#define INDENT " "
48#define INDENT2 " "
49#define INDENT3 " "
50#define INDENT4 " "
51
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000053using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080054using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070055using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050056using android::gui::FocusRequest;
57using android::gui::TouchOcclusionMode;
58using android::gui::WindowInfo;
59using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100061using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::InputEventInjectionResult;
63using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Garfield Tane84e6f92019-08-29 17:28:41 -070065namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Prabir Pradhancef936d2021-07-21 16:17:52 +000067namespace {
68
Prabir Pradhan61a5d242021-07-26 16:41:09 +000069// Log detailed debug messages about each inbound event notification to the dispatcher.
70constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
71
72// Log detailed debug messages about each outbound event processed by the dispatcher.
73constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
74
75// Log debug messages about the dispatch cycle.
76constexpr bool DEBUG_DISPATCH_CYCLE = false;
77
78// Log debug messages about channel creation
79constexpr bool DEBUG_CHANNEL_CREATION = false;
80
81// Log debug messages about input event injection.
82constexpr bool DEBUG_INJECTION = false;
83
84// Log debug messages about input focus tracking.
85constexpr bool DEBUG_FOCUS = false;
86
Antonio Kantekf16f2832021-09-28 04:39:20 +000087// Log debug messages about touch mode event
88constexpr bool DEBUG_TOUCH_MODE = false;
89
Prabir Pradhan61a5d242021-07-26 16:41:09 +000090// Log debug messages about touch occlusion
Prabir Pradhan61a5d242021-07-26 16:41:09 +000091constexpr bool DEBUG_TOUCH_OCCLUSION = true;
92
93// Log debug messages about the app switch latency optimization.
94constexpr bool DEBUG_APP_SWITCH = false;
95
96// Log debug messages about hover events.
97constexpr bool DEBUG_HOVER = false;
98
Prabir Pradhancef936d2021-07-21 16:17:52 +000099// Temporarily releases a held mutex for the lifetime of the instance.
100// Named to match std::scoped_lock
101class scoped_unlock {
102public:
103 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
104 ~scoped_unlock() { mMutex.lock(); }
105
106private:
107 std::mutex& mMutex;
108};
109
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110// Default input dispatching timeout if there is no focused application or paused window
111// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800112const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
113 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
114 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
116// Amount of time to allow for all pending events to be processed when an app switch
117// key is on the way. This is used to preempt input dispatch and drop input events
118// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
121// Amount of time to allow for an event to be dispatched (measured since its eventTime)
122// before considering it stale and dropping it.
Vadim Tryshev78548252022-01-27 19:32:46 +0000123const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL // 10sec
124 * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000127constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
128
129// Log a warning when an interception call takes longer than this to process.
130constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700132// Additional key latency in case a connection is still processing some motion events.
133// This will help with the case when a user touched a button that opens a new window,
134// and gives us the chance to dispatch the key to this new window.
135constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000138constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
139
Antonio Kantekea47acb2021-12-23 12:41:25 -0800140// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000141constexpr int LOGTAG_INPUT_INTERACTION = 62000;
142constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000143constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000144
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000145inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146 return systemTime(SYSTEM_TIME_MONOTONIC);
147}
148
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000149inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 return value ? "true" : "false";
151}
152
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000153inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000154 if (binder == nullptr) {
155 return "<null>";
156 }
157 return StringPrintf("%p", binder.get());
158}
159
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000160inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
162 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163}
164
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000165bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AKEY_EVENT_ACTION_DOWN:
168 case AKEY_EVENT_ACTION_UP:
169 return true;
170 default:
171 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 }
173}
174
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000175bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 ALOGE("Key event has invalid action code 0x%x", action);
178 return false;
179 }
180 return true;
181}
182
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000183bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 case AMOTION_EVENT_ACTION_DOWN:
186 case AMOTION_EVENT_ACTION_UP:
187 case AMOTION_EVENT_ACTION_CANCEL:
188 case AMOTION_EVENT_ACTION_MOVE:
189 case AMOTION_EVENT_ACTION_OUTSIDE:
190 case AMOTION_EVENT_ACTION_HOVER_ENTER:
191 case AMOTION_EVENT_ACTION_HOVER_MOVE:
192 case AMOTION_EVENT_ACTION_HOVER_EXIT:
193 case AMOTION_EVENT_ACTION_SCROLL:
194 return true;
195 case AMOTION_EVENT_ACTION_POINTER_DOWN:
196 case AMOTION_EVENT_ACTION_POINTER_UP: {
197 int32_t index = getMotionEventActionPointerIndex(action);
198 return index >= 0 && index < pointerCount;
199 }
200 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
201 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
202 return actionButton != 0;
203 default:
204 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
206}
207
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000208int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500209 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
210}
211
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000212bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
213 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700214 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 ALOGE("Motion event has invalid action code 0x%x", action);
216 return false;
217 }
218 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800219 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700220 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return false;
222 }
223 BitSet32 pointerIdBits;
224 for (size_t i = 0; i < pointerCount; i++) {
225 int32_t id = pointerProperties[i].id;
226 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700227 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
228 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 return false;
230 }
231 if (pointerIdBits.hasBit(id)) {
232 ALOGE("Motion event has duplicate pointer id %d", id);
233 return false;
234 }
235 pointerIdBits.markBit(id);
236 }
237 return true;
238}
239
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000240std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000242 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243 }
244
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000245 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 bool first = true;
247 Region::const_iterator cur = region.begin();
248 Region::const_iterator const tail = region.end();
249 while (cur != tail) {
250 if (first) {
251 first = false;
252 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800253 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800255 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 cur++;
257 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259}
260
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000261std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500262 constexpr size_t maxEntries = 50; // max events to print
263 constexpr size_t skipBegin = maxEntries / 2;
264 const size_t skipEnd = queue.size() - maxEntries / 2;
265 // skip from maxEntries / 2 ... size() - maxEntries/2
266 // only print from 0 .. skipBegin and then from skipEnd .. size()
267
268 std::string dump;
269 for (size_t i = 0; i < queue.size(); i++) {
270 const DispatchEntry& entry = *queue[i];
271 if (i >= skipBegin && i < skipEnd) {
272 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
273 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
274 continue;
275 }
276 dump.append(INDENT4);
277 dump += entry.eventEntry->getDescription();
278 dump += StringPrintf(", seq=%" PRIu32
279 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
280 entry.seq, entry.targetFlags, entry.resolvedAction,
281 ns2ms(currentTime - entry.eventEntry->eventTime));
282 if (entry.deliveryTime != 0) {
283 // This entry was delivered, so add information on how long we've been waiting
284 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
285 }
286 dump.append("\n");
287 }
288 return dump;
289}
290
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700291/**
292 * Find the entry in std::unordered_map by key, and return it.
293 * If the entry is not found, return a default constructed entry.
294 *
295 * Useful when the entries are vectors, since an empty vector will be returned
296 * if the entry is not found.
297 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
298 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700299template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000300V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700301 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700302 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800303}
304
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000305bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000317bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321 return first->applicationInfo.token != nullptr &&
322 first->applicationInfo.token == second->applicationInfo.token;
323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800326 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
327}
328
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000329std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
330 std::shared_ptr<EventEntry> eventEntry,
331 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700332 if (inputTarget.useDefaultPointerTransform()) {
333 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700334 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700335 inputTarget.displayTransform,
336 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000337 }
338
339 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
340 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700342 std::vector<PointerCoords> pointerCoords;
343 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344
345 // Use the first pointer information to normalize all other pointers. This could be any pointer
346 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 // uses the transform for the normalized pointer.
348 const ui::Transform& firstPointerTransform =
349 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
350 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000351
352 // Iterate through all pointers in the event to normalize against the first.
353 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
354 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
355 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700356 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700359 // First, apply the current pointer's transform to update the coordinates into
360 // window space.
361 pointerCoords[pointerIndex].transform(currTransform);
362 // Next, apply the inverse transform of the normalized coordinates so the
363 // current coordinates are transformed into the normalized coordinate space.
364 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365 }
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::unique_ptr<MotionEntry> combinedMotionEntry =
368 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
369 motionEntry.deviceId, motionEntry.source,
370 motionEntry.displayId, motionEntry.policyFlags,
371 motionEntry.action, motionEntry.actionButton,
372 motionEntry.flags, motionEntry.metaState,
373 motionEntry.buttonState, motionEntry.classification,
374 motionEntry.edgeFlags, motionEntry.xPrecision,
375 motionEntry.yPrecision, motionEntry.xCursorPosition,
376 motionEntry.yCursorPosition, motionEntry.downTime,
377 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000378 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379
380 if (motionEntry.injectionState) {
381 combinedMotionEntry->injectionState = motionEntry.injectionState;
382 combinedMotionEntry->injectionState->refCount += 1;
383 }
384
385 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700386 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700387 firstPointerTransform, inputTarget.displayTransform,
388 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 return dispatchEntry;
390}
391
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000392status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
393 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700394 std::unique_ptr<InputChannel> uniqueServerChannel;
395 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
396
397 serverChannel = std::move(uniqueServerChannel);
398 return result;
399}
400
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500401template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000402bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500403 if (lhs == nullptr && rhs == nullptr) {
404 return true;
405 }
406 if (lhs == nullptr || rhs == nullptr) {
407 return false;
408 }
409 return *lhs == *rhs;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000413 KeyEvent event;
414 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
415 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
416 entry.repeatCount, entry.downTime, entry.eventTime);
417 return event;
418}
419
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000420bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000421 // Do not keep track of gesture monitors. They receive every event and would disproportionately
422 // affect the statistics.
423 if (connection.monitor) {
424 return false;
425 }
426 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
427 if (!connection.responsive) {
428 return false;
429 }
430 return true;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000434 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
435 const int32_t& inputEventId = eventEntry.id;
436 if (inputEventId != dispatchEntry.resolvedEventId) {
437 // Event was transmuted
438 return false;
439 }
440 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
441 return false;
442 }
443 // Only track latency for events that originated from hardware
444 if (eventEntry.isSynthesized()) {
445 return false;
446 }
447 const EventEntry::Type& inputEventEntryType = eventEntry.type;
448 if (inputEventEntryType == EventEntry::Type::KEY) {
449 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
450 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
451 return false;
452 }
453 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
454 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
455 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
456 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
457 return false;
458 }
459 } else {
460 // Not a key or a motion
461 return false;
462 }
463 if (!shouldReportMetricsForConnection(connection)) {
464 return false;
465 }
466 return true;
467}
468
Prabir Pradhancef936d2021-07-21 16:17:52 +0000469/**
470 * Connection is responsive if it has no events in the waitQueue that are older than the
471 * current time.
472 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000473bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000474 const nsecs_t currentTime = now();
475 for (const DispatchEntry* entry : connection.waitQueue) {
476 if (entry->timeoutTime < currentTime) {
477 return false;
478 }
479 }
480 return true;
481}
482
Antonio Kantekf16f2832021-09-28 04:39:20 +0000483// Returns true if the event type passed as argument represents a user activity.
484bool isUserActivityEvent(const EventEntry& eventEntry) {
485 switch (eventEntry.type) {
486 case EventEntry::Type::FOCUS:
487 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
488 case EventEntry::Type::DRAG:
489 case EventEntry::Type::TOUCH_MODE_CHANGED:
490 case EventEntry::Type::SENSOR:
491 case EventEntry::Type::CONFIGURATION_CHANGED:
492 return false;
493 case EventEntry::Type::DEVICE_RESET:
494 case EventEntry::Type::KEY:
495 case EventEntry::Type::MOTION:
496 return true;
497 }
498}
499
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800500// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700501bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
502 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800503 const auto inputConfig = windowInfo.inputConfig;
504 if (windowInfo.displayId != displayId ||
505 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800506 return false;
507 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700508 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800509 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800510 return false;
511 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800512 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800513 return false;
514 }
515 return true;
516}
517
Prabir Pradhand65552b2021-10-07 11:23:50 -0700518bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
519 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
520 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
521 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
522}
523
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000524} // namespace
525
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526// --- InputDispatcher ---
527
Garfield Tan00f511d2019-06-12 16:55:40 -0700528InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
529 : mPolicy(policy),
530 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700531 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800532 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700533 mAppSwitchSawKeyDown(false),
534 mAppSwitchDueTime(LONG_LONG_MAX),
535 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800536 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700537 mDispatchEnabled(false),
538 mDispatchFrozen(false),
539 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800540 // mInTouchMode will be initialized by the WindowManager to the default device config.
541 // To avoid leaking stack in case that call never comes, and for tests,
542 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000543 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100544 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000545 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800546 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000547 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800548 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800550 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700552 mWindowInfoListener = new DispatcherWindowListener(*this);
553 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
554
Yi Kong9b14ac62018-07-17 13:48:38 -0700555 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556
557 policy->getDispatcherConfiguration(&mConfig);
558}
559
560InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000561 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562
Prabir Pradhancef936d2021-07-21 16:17:52 +0000563 resetKeyRepeatLocked();
564 releasePendingEventLocked();
565 drainInboundQueueLocked();
566 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000568 while (!mConnectionsByToken.empty()) {
569 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000570 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
571 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 }
573}
574
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700575status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700576 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700577 return ALREADY_EXISTS;
578 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700579 mThread = std::make_unique<InputThread>(
580 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
581 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700582}
583
584status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700585 if (mThread && mThread->isCallingThread()) {
586 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700587 return INVALID_OPERATION;
588 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700589 mThread.reset();
590 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591}
592
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593void InputDispatcher::dispatchOnce() {
594 nsecs_t nextWakeupTime = LONG_LONG_MAX;
595 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800596 std::scoped_lock _l(mLock);
597 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598
599 // Run a dispatch loop if there are no pending commands.
600 // The dispatch loop might enqueue commands to run afterwards.
601 if (!haveCommandsLocked()) {
602 dispatchOnceInnerLocked(&nextWakeupTime);
603 }
604
605 // Run all pending commands if there are any.
606 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000607 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 nextWakeupTime = LONG_LONG_MIN;
609 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800610
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700611 // If we are still waiting for ack on some events,
612 // we might have to wake up earlier to check if an app is anr'ing.
613 const nsecs_t nextAnrCheck = processAnrsLocked();
614 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
615
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800616 // We are about to enter an infinitely long sleep, because we have no commands or
617 // pending or queued events
618 if (nextWakeupTime == LONG_LONG_MAX) {
619 mDispatcherEnteredIdle.notify_all();
620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 } // release lock
622
623 // Wait for callback or timeout or wake. (make sure we round up, not down)
624 nsecs_t currentTime = now();
625 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
626 mLooper->pollOnce(timeoutMillis);
627}
628
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700629/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500630 * Raise ANR if there is no focused window.
631 * Before the ANR is raised, do a final state check:
632 * 1. The currently focused application must be the same one we are waiting for.
633 * 2. Ensure we still don't have a focused window.
634 */
635void InputDispatcher::processNoFocusedWindowAnrLocked() {
636 // Check if the application that we are waiting for is still focused.
637 std::shared_ptr<InputApplicationHandle> focusedApplication =
638 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
639 if (focusedApplication == nullptr ||
640 focusedApplication->getApplicationToken() !=
641 mAwaitedFocusedApplication->getApplicationToken()) {
642 // Unexpected because we should have reset the ANR timer when focused application changed
643 ALOGE("Waited for a focused window, but focused application has already changed to %s",
644 focusedApplication->getName().c_str());
645 return; // The focused application has changed.
646 }
647
chaviw98318de2021-05-19 16:45:23 -0500648 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500649 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
650 if (focusedWindowHandle != nullptr) {
651 return; // We now have a focused window. No need for ANR.
652 }
653 onAnrLocked(mAwaitedFocusedApplication);
654}
655
656/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700657 * Check if any of the connections' wait queues have events that are too old.
658 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
659 * Return the time at which we should wake up next.
660 */
661nsecs_t InputDispatcher::processAnrsLocked() {
662 const nsecs_t currentTime = now();
663 nsecs_t nextAnrCheck = LONG_LONG_MAX;
664 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
665 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
666 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500667 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700668 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500669 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700670 return LONG_LONG_MIN;
671 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500672 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
674 }
675 }
676
677 // Check if any connection ANRs are due
678 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
679 if (currentTime < nextAnrCheck) { // most likely scenario
680 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
681 }
682
683 // If we reached here, we have an unresponsive connection.
684 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
685 if (connection == nullptr) {
686 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
687 return nextAnrCheck;
688 }
689 connection->responsive = false;
690 // Stop waking up for this unresponsive connection
691 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000692 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700693 return LONG_LONG_MIN;
694}
695
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800696std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
697 const sp<Connection>& connection) {
698 if (connection->monitor) {
699 return mMonitorDispatchingTimeout;
700 }
701 const sp<WindowInfoHandle> window =
702 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700703 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500704 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500706 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707}
708
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
710 nsecs_t currentTime = now();
711
Jeff Browndc5992e2014-04-11 01:27:26 -0700712 // Reset the key repeat timer whenever normal dispatch is suspended while the
713 // device is in a non-interactive state. This is to ensure that we abort a key
714 // repeat if the device is just coming out of sleep.
715 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 resetKeyRepeatLocked();
717 }
718
719 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
720 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100721 if (DEBUG_FOCUS) {
722 ALOGD("Dispatch frozen. Waiting some more.");
723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 return;
725 }
726
727 // Optimize latency of app switches.
728 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
729 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
730 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
731 if (mAppSwitchDueTime < *nextWakeupTime) {
732 *nextWakeupTime = mAppSwitchDueTime;
733 }
734
735 // Ready to start a new event.
736 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700738 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 if (isAppSwitchDue) {
740 // The inbound queue is empty so the app switch key we were waiting
741 // for will never arrive. Stop waiting for it.
742 resetPendingAppSwitchLocked(false);
743 isAppSwitchDue = false;
744 }
745
746 // Synthesize a key repeat if appropriate.
747 if (mKeyRepeatState.lastKeyEntry) {
748 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
749 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
750 } else {
751 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
752 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
753 }
754 }
755 }
756
757 // Nothing to do if there is no pending event.
758 if (!mPendingEvent) {
759 return;
760 }
761 } else {
762 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700763 mPendingEvent = mInboundQueue.front();
764 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 traceInboundQueueLengthLocked();
766 }
767
768 // Poke user activity for this event.
769 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700770 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 }
773
774 // Now we have an event to dispatch.
775 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700776 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700782 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 }
784
785 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700786 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
788
789 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700790 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700791 const ConfigurationChangedEntry& typedEntry =
792 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700793 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 break;
796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700798 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 const DeviceResetEntry& typedEntry =
800 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 break;
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100806 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 std::shared_ptr<FocusEntry> typedEntry =
808 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100809 dispatchFocusLocked(currentTime, typedEntry);
810 done = true;
811 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
812 break;
813 }
814
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700815 case EventEntry::Type::TOUCH_MODE_CHANGED: {
816 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
817 dispatchTouchModeChangeLocked(currentTime, typedEntry);
818 done = true;
819 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
820 break;
821 }
822
Prabir Pradhan99987712020-11-10 18:43:05 -0800823 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
824 const auto typedEntry =
825 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
826 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
827 done = true;
828 break;
829 }
830
arthurhungb89ccb02020-12-30 16:19:01 +0800831 case EventEntry::Type::DRAG: {
832 std::shared_ptr<DragEntry> typedEntry =
833 std::static_pointer_cast<DragEntry>(mPendingEvent);
834 dispatchDragLocked(currentTime, typedEntry);
835 done = true;
836 break;
837 }
838
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700839 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700840 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700842 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 resetPendingAppSwitchLocked(true);
844 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700845 } else if (dropReason == DropReason::NOT_DROPPED) {
846 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700847 }
848 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700850 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700852 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
853 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700855 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 break;
857 }
858
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700859 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700860 std::shared_ptr<MotionEntry> motionEntry =
861 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700862 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
863 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700865 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
869 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Chris Yef59a2f42020-10-16 12:55:26 -0700874
875 case EventEntry::Type::SENSOR: {
876 std::shared_ptr<SensorEntry> sensorEntry =
877 std::static_pointer_cast<SensorEntry>(mPendingEvent);
878 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
879 dropReason = DropReason::APP_SWITCH;
880 }
881 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
882 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
883 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
884 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
885 dropReason = DropReason::STALE;
886 }
887 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
888 done = true;
889 break;
890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892
893 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700895 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Michael Wright3a981722015-06-10 15:26:13 +0100897 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898
899 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902}
903
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700904/**
905 * Return true if the events preceding this incoming motion event should be dropped
906 * Return false otherwise (the default behaviour)
907 */
908bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700909 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700910 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700911
912 // Optimize case where the current application is unresponsive and the user
913 // decides to touch a window in a different application.
914 // If the application takes too long to catch up then we drop all events preceding
915 // the touch into the other window.
916 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700917 int32_t displayId = motionEntry.displayId;
918 int32_t x = static_cast<int32_t>(
919 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
920 int32_t y = static_cast<int32_t>(
921 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700922
923 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500924 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700925 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 touchedWindowHandle->getApplicationToken() !=
928 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700930 ALOGI("Pruning input queue because user touched a different application while waiting "
931 "for %s",
932 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700933 return true;
934 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800936 // Alternatively, maybe there's a spy window that could handle this event.
937 const std::vector<sp<WindowInfoHandle>> touchedSpies =
938 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
939 for (const auto& windowHandle : touchedSpies) {
940 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000941 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800942 // This spy window could take more input. Drop all events preceding this
943 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800945 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 mAwaitedFocusedApplication->getName().c_str());
947 return true;
948 }
949 }
950 }
951
952 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
953 // yet been processed by some connections, the dispatcher will wait for these motion
954 // events to be processed before dispatching the key event. This is because these motion events
955 // may cause a new window to be launched, which the user might expect to receive focus.
956 // To prevent waiting forever for such events, just send the key to the currently focused window
957 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
958 ALOGD("Received a new pointer down event, stop waiting for events to process and "
959 "just send the pending key event to the focused window.");
960 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 }
962 return false;
963}
964
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700966 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 mInboundQueue.push_back(std::move(newEntry));
968 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 traceInboundQueueLengthLocked();
970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700971 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700972 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 // Optimize app switch latency.
974 // If the application takes too long to catch up then we drop all events preceding
975 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700978 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700980 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000982 if (DEBUG_APP_SWITCH) {
983 ALOGD("App switch is pending!");
984 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700985 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 mAppSwitchSawKeyDown = false;
987 needWake = true;
988 }
989 }
990 }
991 break;
992 }
993
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700994 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700995 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
996 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700997 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001002 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1003 break;
1004 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001005 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001006 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001007 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001008 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001009 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1010 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001011 // nothing to do
1012 break;
1013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 return needWake;
1017}
1018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001019void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001020 // Do not store sensor event in recent queue to avoid flooding the queue.
1021 if (entry->type != EventEntry::Type::SENSOR) {
1022 mRecentQueue.push_back(entry);
1023 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001024 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001025 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027}
1028
chaviw98318de2021-05-19 16:45:23 -05001029sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1030 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001031 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001032 bool addOutsideTargets,
1033 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001034 if (addOutsideTargets && touchState == nullptr) {
1035 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001038 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001039 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001040 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001041 continue;
1042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001044 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001045 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001046 return windowHandle;
1047 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001048
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001049 if (addOutsideTargets &&
1050 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001051 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1052 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
1054 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001055 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056}
1057
Prabir Pradhand65552b2021-10-07 11:23:50 -07001058std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1059 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001060 // Traverse windows from front to back and gather the touched spy windows.
1061 std::vector<sp<WindowInfoHandle>> spyWindows;
1062 const auto& windowHandles = getWindowHandlesLocked(displayId);
1063 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1064 const WindowInfo& info = *windowHandle->getInfo();
1065
Prabir Pradhand65552b2021-10-07 11:23:50 -07001066 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001067 continue;
1068 }
1069 if (!info.isSpy()) {
1070 // The first touched non-spy window was found, so return the spy windows touched so far.
1071 return spyWindows;
1072 }
1073 spyWindows.push_back(windowHandle);
1074 }
1075 return spyWindows;
1076}
1077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 const char* reason;
1080 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001082 if (DEBUG_INBOUND_EVENT_DETAILS) {
1083 ALOGD("Dropped event because policy consumed it.");
1084 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 reason = "inbound event was dropped because the policy consumed it";
1086 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001087 case DropReason::DISABLED:
1088 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because input dispatch is disabled.");
1090 }
1091 reason = "inbound event was dropped because input dispatch is disabled";
1092 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001093 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 ALOGI("Dropped event because of pending overdue app switch.");
1095 reason = "inbound event was dropped because of pending overdue app switch";
1096 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 ALOGI("Dropped event because the current application is not responding and the user "
1099 "has started interacting with a different application.");
1100 reason = "inbound event was dropped because the current application is not responding "
1101 "and the user has started interacting with a different application";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because it is stale.");
1105 reason = "inbound event was dropped because it is stale";
1106 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001107 case DropReason::NO_POINTER_CAPTURE:
1108 ALOGI("Dropped event because there is no window with Pointer Capture.");
1109 reason = "inbound event was dropped because there is no window with Pointer Capture";
1110 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001111 case DropReason::NOT_DROPPED: {
1112 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
1116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001117 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001118 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1120 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001123 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1125 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1127 synthesizeCancelationEventsForAllConnectionsLocked(options);
1128 } else {
1129 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1130 synthesizeCancelationEventsForAllConnectionsLocked(options);
1131 }
1132 break;
1133 }
Chris Yef59a2f42020-10-16 12:55:26 -07001134 case EventEntry::Type::SENSOR: {
1135 break;
1136 }
arthurhungb89ccb02020-12-30 16:19:01 +08001137 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1138 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 break;
1140 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001141 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001142 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001143 case EventEntry::Type::CONFIGURATION_CHANGED:
1144 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001145 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001146 break;
1147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149}
1150
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001151static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1153 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154}
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1157 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1158 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1159 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160}
1161
1162bool InputDispatcher::isAppSwitchPendingLocked() {
1163 return mAppSwitchDueTime != LONG_LONG_MAX;
1164}
1165
1166void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1167 mAppSwitchDueTime = LONG_LONG_MAX;
1168
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001169 if (DEBUG_APP_SWITCH) {
1170 if (handled) {
1171 ALOGD("App switch has arrived.");
1172 } else {
1173 ALOGD("App switch was abandoned.");
1174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001179 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180}
1181
Prabir Pradhancef936d2021-07-21 16:17:52 +00001182bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001183 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 return false;
1185 }
1186
1187 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001188 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001189 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001190 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1191 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 return true;
1194}
1195
Prabir Pradhancef936d2021-07-21 16:17:52 +00001196void InputDispatcher::postCommandLocked(Command&& command) {
1197 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198}
1199
1200void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001201 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 releaseInboundEventLocked(entry);
1205 }
1206 traceInboundQueueLengthLocked();
1207}
1208
1209void InputDispatcher::releasePendingEventLocked() {
1210 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001212 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214}
1215
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001216void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001218 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001219 if (DEBUG_DISPATCH_CYCLE) {
1220 ALOGD("Injected inbound event was dropped.");
1221 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001225 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
1227 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228}
1229
1230void InputDispatcher::resetKeyRepeatLocked() {
1231 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001232 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234}
1235
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1237 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238
Michael Wright2e732952014-09-24 13:26:59 -07001239 uint32_t policyFlags = entry->policyFlags &
1240 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 std::shared_ptr<KeyEntry> newEntry =
1243 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1244 entry->source, entry->displayId, policyFlags, entry->action,
1245 entry->flags, entry->keyCode, entry->scanCode,
1246 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 newEntry->syntheticRepeat = true;
1249 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252}
1253
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001256 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1257 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259
1260 // Reset key repeating in case a keyboard device was added or removed or something.
1261 resetKeyRepeatLocked();
1262
1263 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001264 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1265 scoped_unlock unlock(mLock);
1266 mPolicy->notifyConfigurationChanged(eventTime);
1267 };
1268 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 return true;
1270}
1271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1273 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001274 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1275 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1276 entry.deviceId);
1277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278
liushenxiang42232912021-05-21 20:24:09 +08001279 // Reset key repeating in case a keyboard device was disabled or enabled.
1280 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1281 resetKeyRepeatLocked();
1282 }
1283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 synthesizeCancelationEventsForAllConnectionsLocked(options);
1287 return true;
1288}
1289
Vishnu Nairad321cd2020-08-20 16:40:21 -07001290void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001291 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001292 if (mPendingEvent != nullptr) {
1293 // Move the pending event to the front of the queue. This will give the chance
1294 // for the pending event to get dispatched to the newly focused window
1295 mInboundQueue.push_front(mPendingEvent);
1296 mPendingEvent = nullptr;
1297 }
1298
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 std::unique_ptr<FocusEntry> focusEntry =
1300 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1301 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001302
1303 // This event should go to the front of the queue, but behind all other focus events
1304 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001306 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 [](const std::shared_ptr<EventEntry>& event) {
1308 return event->type == EventEntry::Type::FOCUS;
1309 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001310
1311 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001312 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001313}
1314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001316 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001317 if (channel == nullptr) {
1318 return; // Window has gone away
1319 }
1320 InputTarget target;
1321 target.inputChannel = channel;
1322 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1323 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001324 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1325 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001326 std::string reason = std::string("reason=").append(entry->reason);
1327 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001328 dispatchEventLocked(currentTime, entry, {target});
1329}
1330
Prabir Pradhan99987712020-11-10 18:43:05 -08001331void InputDispatcher::dispatchPointerCaptureChangedLocked(
1332 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1333 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001334 dropReason = DropReason::NOT_DROPPED;
1335
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001337 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001338
1339 if (entry->pointerCaptureRequest.enable) {
1340 // Enable Pointer Capture.
1341 if (haveWindowWithPointerCapture &&
1342 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1343 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1344 "to the window.");
1345 }
1346 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001347 // This can happen if a window requests capture and immediately releases capture.
1348 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001349 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001350 return;
1351 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001352 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1353 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1354 return;
1355 }
1356
Vishnu Nairc519ff72021-01-21 08:23:08 -08001357 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001358 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1359 mWindowTokenWithPointerCapture = token;
1360 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001361 // Disable Pointer Capture.
1362 // We do not check if the sequence number matches for requests to disable Pointer Capture
1363 // for two reasons:
1364 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1365 // to disable capture with the same sequence number: one generated by
1366 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1367 // Capture being disabled in InputReader.
1368 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1369 // actual Pointer Capture state that affects events being generated by input devices is
1370 // in InputReader.
1371 if (!haveWindowWithPointerCapture) {
1372 // Pointer capture was already forcefully disabled because of focus change.
1373 dropReason = DropReason::NOT_DROPPED;
1374 return;
1375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 token = mWindowTokenWithPointerCapture;
1377 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001378 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001379 setPointerCaptureLocked(false);
1380 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001381 }
1382
1383 auto channel = getInputChannelLocked(token);
1384 if (channel == nullptr) {
1385 // Window has gone away, clean up Pointer Capture state.
1386 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001387 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001388 setPointerCaptureLocked(false);
1389 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 return;
1391 }
1392 InputTarget target;
1393 target.inputChannel = channel;
1394 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1395 entry->dispatchInProgress = true;
1396 dispatchEventLocked(currentTime, entry, {target});
1397
1398 dropReason = DropReason::NOT_DROPPED;
1399}
1400
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001401void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1402 const std::shared_ptr<TouchModeEntry>& entry) {
1403 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1404 getWindowHandlesLocked(mFocusedDisplayId);
1405 if (windowHandles.empty()) {
1406 return;
1407 }
1408 const std::vector<InputTarget> inputTargets =
1409 getInputTargetsFromWindowHandlesLocked(windowHandles);
1410 if (inputTargets.empty()) {
1411 return;
1412 }
1413 entry->dispatchInProgress = true;
1414 dispatchEventLocked(currentTime, entry, inputTargets);
1415}
1416
1417std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1418 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1419 std::vector<InputTarget> inputTargets;
1420 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1421 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1422 const sp<IBinder>& token = handle->getToken();
1423 if (token == nullptr) {
1424 continue;
1425 }
1426 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1427 if (channel == nullptr) {
1428 continue; // Window has gone away
1429 }
1430 InputTarget target;
1431 target.inputChannel = channel;
1432 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1433 inputTargets.push_back(target);
1434 }
1435 return inputTargets;
1436}
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001441 if (!entry->dispatchInProgress) {
1442 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1443 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1444 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1445 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001446 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 // We have seen two identical key downs in a row which indicates that the device
1448 // driver is automatically generating key repeats itself. We take note of the
1449 // repeat here, but we disable our own next key repeat timer since it is clear that
1450 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001451 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1452 // Make sure we don't get key down from a different device. If a different
1453 // device Id has same key pressed down, the new device Id will replace the
1454 // current one to hold the key repeat with repeat count reset.
1455 // In the future when got a KEY_UP on the device id, drop it and do not
1456 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1458 resetKeyRepeatLocked();
1459 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1460 } else {
1461 // Not a repeat. Save key down state in case we do see a repeat later.
1462 resetKeyRepeatLocked();
1463 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1464 }
1465 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001466 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1467 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001468 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001469 if (DEBUG_INBOUND_EVENT_DETAILS) {
1470 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1471 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 resetKeyRepeatLocked();
1474 }
1475
1476 if (entry->repeatCount == 1) {
1477 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1478 } else {
1479 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1480 }
1481
1482 entry->dispatchInProgress = true;
1483
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001484 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 }
1486
1487 // Handle case where the policy asked us to try again later last time.
1488 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1489 if (currentTime < entry->interceptKeyWakeupTime) {
1490 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1491 *nextWakeupTime = entry->interceptKeyWakeupTime;
1492 }
1493 return false; // wait until next wakeup
1494 }
1495 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1496 entry->interceptKeyWakeupTime = 0;
1497 }
1498
1499 // Give the policy a chance to intercept the key.
1500 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1501 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001502 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001503 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001504
1505 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1506 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1507 };
1508 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 return false; // wait for the command to run
1510 } else {
1511 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1512 }
1513 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001514 if (*dropReason == DropReason::NOT_DROPPED) {
1515 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 }
1517 }
1518
1519 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001520 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001522 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1523 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001524 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 return true;
1526 }
1527
1528 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001529 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001530 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001531 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 return false;
1534 }
1535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001536 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001537 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 return true;
1539 }
1540
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001541 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001542 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
1544 // Dispatch the key.
1545 dispatchEventLocked(currentTime, entry, inputTargets);
1546 return true;
1547}
1548
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001550 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1551 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1552 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1553 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1554 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1555 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1556 entry.metaState, entry.repeatCount, entry.downTime);
1557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558}
1559
Prabir Pradhancef936d2021-07-21 16:17:52 +00001560void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1561 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001562 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001563 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1564 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1565 "source=0x%x, sensorType=%s",
1566 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001567 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001568 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001569 auto command = [this, entry]() REQUIRES(mLock) {
1570 scoped_unlock unlock(mLock);
1571
1572 if (entry->accuracyChanged) {
1573 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1574 }
1575 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1576 entry->hwTimestamp, entry->values);
1577 };
1578 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001579}
1580
1581bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001582 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1583 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001584 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001585 }
Chris Yef59a2f42020-10-16 12:55:26 -07001586 { // acquire lock
1587 std::scoped_lock _l(mLock);
1588
1589 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1590 std::shared_ptr<EventEntry> entry = *it;
1591 if (entry->type == EventEntry::Type::SENSOR) {
1592 it = mInboundQueue.erase(it);
1593 releaseInboundEventLocked(entry);
1594 }
1595 }
1596 }
1597 return true;
1598}
1599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001600bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001601 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001602 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001604 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 entry->dispatchInProgress = true;
1606
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 }
1609
1610 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001611 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001612 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001613 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1614 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 return true;
1616 }
1617
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001618 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619
1620 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001621 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
1623 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001624 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 if (isPointerEvent) {
1626 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001628 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001629 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 } else {
1631 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001632 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001635 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 return false;
1637 }
1638
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001639 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001641 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1642 return true;
1643 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001644 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001645 CancelationOptions::Mode mode(isPointerEvent
1646 ? CancelationOptions::CANCEL_POINTER_EVENTS
1647 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1648 CancelationOptions options(mode, "input event injection failed");
1649 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 return true;
1651 }
1652
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001653 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
1656 // Dispatch the motion.
1657 if (conflictingPointerActions) {
1658 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 synthesizeCancelationEventsForAllConnectionsLocked(options);
1661 }
1662 dispatchEventLocked(currentTime, entry, inputTargets);
1663 return true;
1664}
1665
chaviw98318de2021-05-19 16:45:23 -05001666void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001667 bool isExiting, const MotionEntry& motionEntry) {
1668 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1669 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1670 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1671 PointerCoords pointerCoords;
1672 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1673 pointerCoords.transform(windowHandle->getInfo()->transform);
1674
1675 std::unique_ptr<DragEntry> dragEntry =
1676 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1677 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1678 pointerCoords.getY());
1679
1680 enqueueInboundEventLocked(std::move(dragEntry));
1681}
1682
1683void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1684 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1685 if (channel == nullptr) {
1686 return; // Window has gone away
1687 }
1688 InputTarget target;
1689 target.inputChannel = channel;
1690 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1691 entry->dispatchInProgress = true;
1692 dispatchEventLocked(currentTime, entry, {target});
1693}
1694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001695void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001696 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1697 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1698 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001699 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001700 "metaState=0x%x, buttonState=0x%x,"
1701 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1702 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001703 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1704 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1705 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001707 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1708 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1709 "x=%f, y=%f, pressure=%f, size=%f, "
1710 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1711 "orientation=%f",
1712 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1713 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1714 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1717 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1718 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1719 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1720 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1721 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724}
1725
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001726void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1727 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001730 if (DEBUG_DISPATCH_CYCLE) {
1731 ALOGD("dispatchEventToCurrentInputTargets");
1732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001734 updateInteractionTokensLocked(*eventEntry, inputTargets);
1735
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1737
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001738 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001740 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001741 sp<Connection> connection =
1742 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001743 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001744 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001746 if (DEBUG_FOCUS) {
1747 ALOGD("Dropping event delivery to target with channel '%s' because it "
1748 "is no longer registered with the input dispatcher.",
1749 inputTarget.inputChannel->getName().c_str());
1750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 }
1752 }
1753}
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1756 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1757 // If the policy decides to close the app, we will get a channel removal event via
1758 // unregisterInputChannel, and will clean up the connection that way. We are already not
1759 // sending new pointers to the connection when it blocked, but focused events will continue to
1760 // pile up.
1761 ALOGW("Canceling events for %s because it is unresponsive",
1762 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001763 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001764 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1765 "application not responding");
1766 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768}
1769
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001771 if (DEBUG_FOCUS) {
1772 ALOGD("Resetting ANR timeouts.");
1773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
1775 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001776 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001777 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778}
1779
Tiger Huang721e26f2018-07-24 22:26:19 +08001780/**
1781 * Get the display id that the given event should go to. If this event specifies a valid display id,
1782 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1783 * Focused display is the display that the user most recently interacted with.
1784 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001785int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001786 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001787 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001788 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1790 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 break;
1792 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001793 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001794 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1795 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001796 break;
1797 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001798 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001799 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001800 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001801 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001802 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001803 case EventEntry::Type::SENSOR:
1804 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001805 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 return ADISPLAY_ID_NONE;
1807 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001808 }
1809 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1810}
1811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1813 const char* focusedWindowName) {
1814 if (mAnrTracker.empty()) {
1815 // already processed all events that we waited for
1816 mKeyIsWaitingForEventsTimeout = std::nullopt;
1817 return false;
1818 }
1819
1820 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1821 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001822 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001823 mKeyIsWaitingForEventsTimeout = currentTime +
1824 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1825 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001826 return true;
1827 }
1828
1829 // We still have pending events, and already started the timer
1830 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1831 return true; // Still waiting
1832 }
1833
1834 // Waited too long, and some connection still hasn't processed all motions
1835 // Just send the key to the focused window
1836 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1837 focusedWindowName);
1838 mKeyIsWaitingForEventsTimeout = std::nullopt;
1839 return false;
1840}
1841
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1843 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1844 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
Tiger Huang721e26f2018-07-24 22:26:19 +08001847 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001848 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001849 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001850 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1851
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 // If there is no currently focused window and no focused application
1853 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1855 ALOGI("Dropping %s event because there is no focused window or focused application in "
1856 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001857 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 }
1860
Vishnu Nair062a8672021-09-03 16:07:44 -07001861 // Drop key events if requested by input feature
1862 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1863 return InputEventInjectionResult::FAILED;
1864 }
1865
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001866 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1867 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1868 // start interacting with another application via touch (app switch). This code can be removed
1869 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1870 // an app is expected to have a focused window.
1871 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1872 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1873 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001874 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1875 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1876 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001877 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001878 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 ALOGW("Waiting because no window has focus but %s may eventually add a "
1880 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001881 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001883 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1885 // Already raised ANR. Drop the event
1886 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001887 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889 } else {
1890 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001891 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 }
1893 }
1894
1895 // we have a valid, non-null focused window
1896 resetNoFocusedWindowTimeoutLocked();
1897
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001899 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
1902
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001903 if (focusedWindowHandle->getInfo()->inputConfig.test(
1904 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001905 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 }
1908
1909 // If the event is a key event, then we must wait for all previous events to
1910 // complete before delivering it because previous events may have the
1911 // side-effect of transferring focus to a different window and we want to
1912 // ensure that the following keys are sent to the new window.
1913 //
1914 // Suppose the user touches a button in a window then immediately presses "A".
1915 // If the button causes a pop-up window to appear then we want to ensure that
1916 // the "A" key is delivered to the new pop-up window. This is because users
1917 // often anticipate pending UI changes when typing on a keyboard.
1918 // To obtain this behavior, we must serialize key events with respect to all
1919 // prior input events.
1920 if (entry.type == EventEntry::Type::KEY) {
1921 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1922 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001923 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926
1927 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001928 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001929 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1930 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931
1932 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934}
1935
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936/**
1937 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1938 * that are currently unresponsive.
1939 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001940std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1941 const std::vector<Monitor>& monitors) const {
1942 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001944 [this](const Monitor& monitor) REQUIRES(mLock) {
1945 sp<Connection> connection =
1946 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001947 if (connection == nullptr) {
1948 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001949 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950 return false;
1951 }
1952 if (!connection->responsive) {
1953 ALOGW("Unresponsive monitor %s will not get the new gesture",
1954 connection->inputChannel->getName().c_str());
1955 return false;
1956 }
1957 return true;
1958 });
1959 return responsiveMonitors;
1960}
1961
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1963 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1964 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001965 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 enum InjectionPermission {
1967 INJECTION_PERMISSION_UNKNOWN,
1968 INJECTION_PERMISSION_GRANTED,
1969 INJECTION_PERMISSION_DENIED
1970 };
1971
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 // For security reasons, we defer updating the touch state until we are sure that
1973 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001974 const int32_t displayId = entry.displayId;
1975 const int32_t action = entry.action;
1976 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
1978 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001981 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1982 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001984 // Copy current touch state into tempTouchState.
1985 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1986 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001987 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001989 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1990 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08001991 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001992 }
1993
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001994 bool isSplit = tempTouchState.split;
1995 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1996 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1997 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001998
1999 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2000 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2001 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2002 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2003 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002004 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 bool wrongDevice = false;
2006 if (newGesture) {
2007 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002009 ALOGI("Dropping event because a pointer for a different device is already down "
2010 "in display %" PRId32,
2011 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002012 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 switchedDevice = false;
2015 wrongDevice = true;
2016 goto Failed;
2017 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002018 tempTouchState.reset();
2019 tempTouchState.down = down;
2020 tempTouchState.deviceId = entry.deviceId;
2021 tempTouchState.source = entry.source;
2022 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002024 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002025 ALOGI("Dropping move event because a pointer for a different device is already active "
2026 "in display %" PRId32,
2027 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002028 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002029 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002030 switchedDevice = false;
2031 wrongDevice = true;
2032 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034
2035 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2036 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2037
Garfield Tan00f511d2019-06-12 16:55:40 -07002038 int32_t x;
2039 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002040 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002041 // Always dispatch mouse events to cursor position.
2042 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002043 x = int32_t(entry.xCursorPosition);
2044 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002045 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002046 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2047 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002048 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002049 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002050 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002051 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002052 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002053
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002055 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002056 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2057 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002060 }
2061
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002062 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002064 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2065 // New window supports splitting, but we should never split mouse events.
2066 isSplit = !isFromMouse;
2067 } else if (isSplit) {
2068 // New window does not support splitting but we have already split events.
2069 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002070 newTouchedWindowHandle = nullptr;
2071 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002072 } else {
2073 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002074 // be delivered to a new window which supports split touch. Pointers from a mouse device
2075 // should never be split.
2076 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002077 }
2078
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002079 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002080 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002081 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2082 newHoverWindowHandle = nullptr;
2083 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002086 }
2087
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002088 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002089 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002090 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002091 // Process the foreground window first so that it is the first to receive the event.
2092 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002093 }
2094
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002095 if (newTouchedWindows.empty()) {
2096 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2097 x, y, displayId);
2098 injectionResult = InputEventInjectionResult::FAILED;
2099 goto Failed;
2100 }
2101
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002102 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2103 const WindowInfo& info = *windowHandle->getInfo();
2104
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002105 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002106 ALOGI("Not sending touch event to %s because it is paused",
2107 windowHandle->getName().c_str());
2108 continue;
2109 }
2110
2111 // Ensure the window has a connection and the connection is responsive
2112 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2113 if (!isResponsive) {
2114 ALOGW("Not sending touch gesture to %s because it is not responsive",
2115 windowHandle->getName().c_str());
2116 continue;
2117 }
2118
2119 // Drop events that can't be trusted due to occlusion
2120 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2121 TouchOcclusionInfo occlusionInfo =
2122 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2123 if (!isTouchTrustedLocked(occlusionInfo)) {
2124 if (DEBUG_TOUCH_OCCLUSION) {
2125 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2126 for (const auto& log : occlusionInfo.debugInfo) {
2127 ALOGD("%s", log.c_str());
2128 }
2129 }
2130 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2131 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2132 ALOGW("Dropping untrusted touch event due to %s/%d",
2133 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2134 continue;
2135 }
2136 }
2137 }
2138
2139 // Drop touch events if requested by input feature
2140 if (shouldDropInput(entry, windowHandle)) {
2141 continue;
2142 }
2143
2144 // Set target flags.
2145 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2146
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002147 if (!info.isSpy()) {
2148 // There should only be one new foreground (non-spy) window at this location.
2149 targetFlags |= InputTarget::FLAG_FOREGROUND;
2150 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002151
2152 if (isSplit) {
2153 targetFlags |= InputTarget::FLAG_SPLIT;
2154 }
2155 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2156 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2157 } else if (isWindowObscuredLocked(windowHandle)) {
2158 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2159 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002160
2161 // Update the temporary touch state.
2162 BitSet32 pointerIds;
2163 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002165 pointerIds.markBit(pointerId);
2166 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002167
2168 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 } else {
2171 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2172
2173 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002175 if (DEBUG_FOCUS) {
2176 ALOGD("Dropping event because the pointer is not down or we previously "
2177 "dropped the pointer down event in display %" PRId32,
2178 displayId);
2179 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002180 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 goto Failed;
2182 }
2183
arthurhung6d4bed92021-03-17 11:59:33 +08002184 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002185
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002187 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002189 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2190 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191
Prabir Pradhand65552b2021-10-07 11:23:50 -07002192 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002193 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002195 newTouchedWindowHandle =
2196 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002197
2198 // Drop touch events if requested by input feature
2199 if (newTouchedWindowHandle != nullptr &&
2200 shouldDropInput(entry, newTouchedWindowHandle)) {
2201 newTouchedWindowHandle = nullptr;
2202 }
2203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002204 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2205 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002206 if (DEBUG_FOCUS) {
2207 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2208 oldTouchedWindowHandle->getName().c_str(),
2209 newTouchedWindowHandle->getName().c_str(), displayId);
2210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2213 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2214 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215
2216 // Make a slippery entrance into the new window.
2217 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002218 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 int32_t targetFlags =
2222 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 if (isSplit) {
2224 targetFlags |= InputTarget::FLAG_SPLIT;
2225 }
2226 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2227 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002228 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2229 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231
2232 BitSet32 pointerIds;
2233 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002234 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002236 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
2238 }
2239 }
2240
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002241 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002243 // Let the previous window know that the hover sequence is over, unless we already did
2244 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002245 if (mLastHoverWindowHandle != nullptr &&
2246 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2247 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002248 if (DEBUG_HOVER) {
2249 ALOGD("Sending hover exit event to window %s.",
2250 mLastHoverWindowHandle->getName().c_str());
2251 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2253 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
2255
Garfield Tandf26e862020-07-01 20:18:19 -07002256 // Let the new window know that the hover sequence is starting, unless we already did it
2257 // when dispatching it as is to newTouchedWindowHandle.
2258 if (newHoverWindowHandle != nullptr &&
2259 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2260 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002261 if (DEBUG_HOVER) {
2262 ALOGD("Sending hover enter event to window %s.",
2263 newHoverWindowHandle->getName().c_str());
2264 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002265 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2266 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2267 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269 }
2270
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002271 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2272 // of the touched windows we previously found if they became paused or unresponsive or were
2273 // removed.
2274 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2275 [](const TouchedWindow& touchedWindow) {
2276 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2277 touchedWindow.windowHandle->getInfo()->isSpy();
2278 })) {
2279 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2280 displayId);
2281 injectionResult = InputEventInjectionResult::FAILED;
2282 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002285 // Check permission to inject into all touched foreground windows.
2286 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2287 [this, &entry](const TouchedWindow& touchedWindow) {
2288 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2289 !checkInjectionPermission(touchedWindow.windowHandle,
2290 entry.injectionState);
2291 })) {
2292 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2293 injectionPermission = INJECTION_PERMISSION_DENIED;
2294 goto Failed;
2295 }
2296 // Permission granted to inject into all touched foreground windows.
2297 injectionPermission = INJECTION_PERMISSION_GRANTED;
2298
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 // Check whether windows listening for outside touches are owned by the same UID. If it is
2300 // set the policy flag that we will not reveal coordinate information to this window.
2301 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002302 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002304 if (foregroundWindowHandle) {
2305 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002306 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002307 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002308 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2309 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2310 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 InputTarget::FLAG_ZERO_COORDS,
2312 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315 }
2316 }
2317 }
2318
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 // If this is the first pointer going down and the touched window has a wallpaper
2320 // then also add the touched wallpaper windows so they are locked in for the duration
2321 // of the touch gesture.
2322 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2323 // engine only supports touch events. We would need to add a mechanism similar
2324 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2325 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002326 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002327 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002328 if (foregroundWindowHandle &&
2329 foregroundWindowHandle->getInfo()->inputConfig.test(
2330 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002331 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002332 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002333 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2334 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002335 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002336 windowHandle->getInfo()->inputConfig.test(
2337 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002338 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 .addOrUpdateWindow(windowHandle,
2340 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2341 InputTarget::
2342 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2343 InputTarget::FLAG_DISPATCH_AS_IS,
2344 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 }
2346 }
2347 }
2348 }
2349
2350 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002351 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002353 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
2358 // Drop the outside or hover touch windows since we will not care about them
2359 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002360 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
2362Failed:
2363 // Check injection permission once and for all.
2364 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002365 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 injectionPermission = INJECTION_PERMISSION_GRANTED;
2367 } else {
2368 injectionPermission = INJECTION_PERMISSION_DENIED;
2369 }
2370 }
2371
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002372 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2373 return injectionResult;
2374 }
2375
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002377 if (!wrongDevice) {
2378 if (switchedDevice) {
2379 if (DEBUG_FOCUS) {
2380 ALOGD("Conflicting pointer actions: Switched to a different device.");
2381 }
2382 *outConflictingPointerActions = true;
2383 }
2384
2385 if (isHoverAction) {
2386 // Started hovering, therefore no longer down.
2387 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002388 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002389 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2390 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 *outConflictingPointerActions = true;
2393 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 tempTouchState.reset();
2395 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2396 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2397 tempTouchState.deviceId = entry.deviceId;
2398 tempTouchState.source = entry.source;
2399 tempTouchState.displayId = displayId;
2400 }
2401 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2402 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2403 // All pointers up or canceled.
2404 tempTouchState.reset();
2405 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2406 // First pointer went down.
2407 if (oldState && oldState->down) {
2408 if (DEBUG_FOCUS) {
2409 ALOGD("Conflicting pointer actions: Down received while already down.");
2410 }
2411 *outConflictingPointerActions = true;
2412 }
2413 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2414 // One pointer went up.
2415 if (isSplit) {
2416 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2417 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002419 for (size_t i = 0; i < tempTouchState.windows.size();) {
2420 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2421 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2422 touchedWindow.pointerIds.clearBit(pointerId);
2423 if (touchedWindow.pointerIds.isEmpty()) {
2424 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2425 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002428 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002430 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002431 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002432
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002433 // Save changes unless the action was scroll in which case the temporary touch
2434 // state was only valid for this one action.
2435 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2436 if (tempTouchState.displayId >= 0) {
2437 mTouchStatesByDisplay[displayId] = tempTouchState;
2438 } else {
2439 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002443 // Update hover state.
2444 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 }
2446
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 return injectionResult;
2448}
2449
arthurhung6d4bed92021-03-17 11:59:33 +08002450void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002451 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2452 // have an explicit reason to support it.
2453 constexpr bool isStylus = false;
2454
chaviw98318de2021-05-19 16:45:23 -05002455 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002456 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002457 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002458 if (dropWindow) {
2459 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002460 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002461 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002462 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002463 }
2464 mDragState.reset();
2465}
2466
2467void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2468 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002469 return;
2470 }
2471
arthurhung6d4bed92021-03-17 11:59:33 +08002472 if (!mDragState->isStartDrag) {
2473 mDragState->isStartDrag = true;
2474 mDragState->isStylusButtonDownAtStart =
2475 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2476 }
2477
arthurhungb89ccb02020-12-30 16:19:01 +08002478 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2479 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2480 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2481 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002482 // Handle the special case : stylus button no longer pressed.
2483 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2484 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2485 finishDragAndDrop(entry.displayId, x, y);
2486 return;
2487 }
2488
Prabir Pradhand65552b2021-10-07 11:23:50 -07002489 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2490 // we have an explicit reason to support it.
2491 constexpr bool isStylus = false;
2492
chaviw98318de2021-05-19 16:45:23 -05002493 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002494 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002495 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002496 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002497 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2498 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2499 if (mDragState->dragHoverWindowHandle != nullptr) {
2500 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2501 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002502 }
arthurhung6d4bed92021-03-17 11:59:33 +08002503 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002504 }
2505 // enqueue drag location if needed.
2506 if (hoverWindowHandle != nullptr) {
2507 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2508 }
arthurhung6d4bed92021-03-17 11:59:33 +08002509 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2510 finishDragAndDrop(entry.displayId, x, y);
2511 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002512 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002513 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002514 }
2515}
2516
chaviw98318de2021-05-19 16:45:23 -05002517void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 int32_t targetFlags, BitSet32 pointerIds,
2519 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002520 std::vector<InputTarget>::iterator it =
2521 std::find_if(inputTargets.begin(), inputTargets.end(),
2522 [&windowHandle](const InputTarget& inputTarget) {
2523 return inputTarget.inputChannel->getConnectionToken() ==
2524 windowHandle->getToken();
2525 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002526
chaviw98318de2021-05-19 16:45:23 -05002527 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002528
2529 if (it == inputTargets.end()) {
2530 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002531 std::shared_ptr<InputChannel> inputChannel =
2532 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002533 if (inputChannel == nullptr) {
2534 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2535 return;
2536 }
2537 inputTarget.inputChannel = inputChannel;
2538 inputTarget.flags = targetFlags;
2539 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002540 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2541 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002542 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002543 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002544 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002545 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002546 inputTargets.push_back(inputTarget);
2547 it = inputTargets.end() - 1;
2548 }
2549
2550 ALOG_ASSERT(it->flags == targetFlags);
2551 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2552
chaviw1ff3d1e2020-07-01 15:53:47 -07002553 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554}
2555
Michael Wright3dd60e22019-03-27 22:06:44 +00002556void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002557 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002558 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2559 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002560
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002561 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2562 InputTarget target;
2563 target.inputChannel = monitor.inputChannel;
2564 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2565 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2566 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002567 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002568 target.setDefaultPointerTransform(target.displayTransform);
2569 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
2571}
2572
chaviw98318de2021-05-19 16:45:23 -05002573bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 const InjectionState* injectionState) {
2575 if (injectionState &&
2576 (windowHandle == nullptr ||
2577 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2578 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002579 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 "owned by uid %d",
2582 injectionState->injectorPid, injectionState->injectorUid,
2583 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 } else {
2585 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
2588 return false;
2589 }
2590 return true;
2591}
2592
Robert Carrc9bf1d32020-04-13 17:21:08 -07002593/**
2594 * Indicate whether one window handle should be considered as obscuring
2595 * another window handle. We only check a few preconditions. Actually
2596 * checking the bounds is left to the caller.
2597 */
chaviw98318de2021-05-19 16:45:23 -05002598static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2599 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002600 // Compare by token so cloned layers aren't counted
2601 if (haveSameToken(windowHandle, otherHandle)) {
2602 return false;
2603 }
2604 auto info = windowHandle->getInfo();
2605 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002606 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002607 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002608 } else if (otherInfo->alpha == 0 &&
2609 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002610 // Those act as if they were invisible, so we don't need to flag them.
2611 // We do want to potentially flag touchable windows even if they have 0
2612 // opacity, since they can consume touches and alter the effects of the
2613 // user interaction (eg. apps that rely on
2614 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2615 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2616 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002617 } else if (info->ownerUid == otherInfo->ownerUid) {
2618 // If ownerUid is the same we don't generate occlusion events as there
2619 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002620 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002621 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002622 return false;
2623 } else if (otherInfo->displayId != info->displayId) {
2624 return false;
2625 }
2626 return true;
2627}
2628
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002629/**
2630 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2631 * untrusted, one should check:
2632 *
2633 * 1. If result.hasBlockingOcclusion is true.
2634 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2635 * BLOCK_UNTRUSTED.
2636 *
2637 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2638 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2639 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2640 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2641 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2642 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2643 *
2644 * If neither of those is true, then it means the touch can be allowed.
2645 */
2646InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002647 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2648 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002649 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002650 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002651 TouchOcclusionInfo info;
2652 info.hasBlockingOcclusion = false;
2653 info.obscuringOpacity = 0;
2654 info.obscuringUid = -1;
2655 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002656 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002657 if (windowHandle == otherHandle) {
2658 break; // All future windows are below us. Exit early.
2659 }
chaviw98318de2021-05-19 16:45:23 -05002660 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002661 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2662 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002663 if (DEBUG_TOUCH_OCCLUSION) {
2664 info.debugInfo.push_back(
2665 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2666 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002667 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2668 // we perform the checks below to see if the touch can be propagated or not based on the
2669 // window's touch occlusion mode
2670 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2671 info.hasBlockingOcclusion = true;
2672 info.obscuringUid = otherInfo->ownerUid;
2673 info.obscuringPackage = otherInfo->packageName;
2674 break;
2675 }
2676 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2677 uint32_t uid = otherInfo->ownerUid;
2678 float opacity =
2679 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2680 // Given windows A and B:
2681 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2682 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2683 opacityByUid[uid] = opacity;
2684 if (opacity > info.obscuringOpacity) {
2685 info.obscuringOpacity = opacity;
2686 info.obscuringUid = uid;
2687 info.obscuringPackage = otherInfo->packageName;
2688 }
2689 }
2690 }
2691 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002692 if (DEBUG_TOUCH_OCCLUSION) {
2693 info.debugInfo.push_back(
2694 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2695 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002696 return info;
2697}
2698
chaviw98318de2021-05-19 16:45:23 -05002699std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002700 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002701 return StringPrintf(INDENT2
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002702 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002703 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002704 "], touchableRegion=%s, window={%s}, inputConfig={%s}, inputFeatures={%s}, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002705 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002706 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2707 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2708 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2709 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2710 info->name.c_str(), info->inputConfig.string().c_str(),
2711 info->inputFeatures.string().c_str(), toString(info->token != nullptr),
2712 info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002713 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002714}
2715
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002716bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2717 if (occlusionInfo.hasBlockingOcclusion) {
2718 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2719 occlusionInfo.obscuringUid);
2720 return false;
2721 }
2722 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2723 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2724 "%.2f, maximum allowed = %.2f)",
2725 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2726 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2727 return false;
2728 }
2729 return true;
2730}
2731
chaviw98318de2021-05-19 16:45:23 -05002732bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002735 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2736 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002737 if (windowHandle == otherHandle) {
2738 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
chaviw98318de2021-05-19 16:45:23 -05002740 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002741 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002742 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 return true;
2744 }
2745 }
2746 return false;
2747}
2748
chaviw98318de2021-05-19 16:45:23 -05002749bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002750 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002751 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2752 const WindowInfo* windowInfo = windowHandle->getInfo();
2753 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002754 if (windowHandle == otherHandle) {
2755 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002756 }
chaviw98318de2021-05-19 16:45:23 -05002757 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002758 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002759 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002760 return true;
2761 }
2762 }
2763 return false;
2764}
2765
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002766std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002767 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002768 if (applicationHandle != nullptr) {
2769 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002770 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 } else {
2772 return applicationHandle->getName();
2773 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002774 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002775 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002777 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 }
2779}
2780
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002781void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002782 if (!isUserActivityEvent(eventEntry)) {
2783 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002784 return;
2785 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002786 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002787 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002788 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002789 const WindowInfo* info = focusedWindowHandle->getInfo();
2790 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002791 if (DEBUG_DISPATCH_CYCLE) {
2792 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 return;
2795 }
2796 }
2797
2798 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002800 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002801 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2802 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002803 return;
2804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002806 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807 eventType = USER_ACTIVITY_EVENT_TOUCH;
2808 }
2809 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002811 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002812 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2813 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002814 return;
2815 }
2816 eventType = USER_ACTIVITY_EVENT_BUTTON;
2817 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002819 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002820 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002821 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002822 break;
2823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825
Prabir Pradhancef936d2021-07-21 16:17:52 +00002826 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2827 REQUIRES(mLock) {
2828 scoped_unlock unlock(mLock);
2829 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2830 };
2831 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832}
2833
2834void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002836 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002837 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002838 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002840 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002841 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002842 ATRACE_NAME(message.c_str());
2843 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002844 if (DEBUG_DISPATCH_CYCLE) {
2845 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2846 "globalScaleFactor=%f, pointerIds=0x%x %s",
2847 connection->getInputChannelName().c_str(), inputTarget.flags,
2848 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2849 inputTarget.getPointerInfoString().c_str());
2850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
2852 // Skip this event if the connection status is not normal.
2853 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002854 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002855 if (DEBUG_DISPATCH_CYCLE) {
2856 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002857 connection->getInputChannelName().c_str(),
2858 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 return;
2861 }
2862
2863 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002864 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2865 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2866 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002867 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002869 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002870 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002871 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002872 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 if (!splitMotionEntry) {
2874 return; // split event was dropped
2875 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002876 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2877 std::string reason = std::string("reason=pointer cancel on split window");
2878 android_log_event_list(LOGTAG_INPUT_CANCEL)
2879 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2880 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002881 if (DEBUG_FOCUS) {
2882 ALOGD("channel '%s' ~ Split motion event.",
2883 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002885 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002886 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2887 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 return;
2889 }
2890 }
2891
2892 // Not splitting. Enqueue dispatch entries for the event as is.
2893 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2894}
2895
2896void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002898 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002899 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002900 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002902 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002903 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002904 ATRACE_NAME(message.c_str());
2905 }
2906
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002907 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
2909 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002910 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002912 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002914 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002916 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002918 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002920 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
2923 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002924 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 startDispatchCycleLocked(currentTime, connection);
2926 }
2927}
2928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002931 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002933 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2935 connection->getInputChannelName().c_str(),
2936 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002937 ATRACE_NAME(message.c_str());
2938 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002939 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 if (!(inputTargetFlags & dispatchMode)) {
2941 return;
2942 }
2943 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2944
2945 // This is a new event.
2946 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002947 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002948 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002950 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2951 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002955 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002956 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002957 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 dispatchEntry->resolvedAction = keyEntry.action;
2959 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2962 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002963 if (DEBUG_DISPATCH_CYCLE) {
2964 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2965 "event",
2966 connection->getInputChannelName().c_str());
2967 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 return; // skip the inconsistent event
2969 }
2970 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002973 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002974 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002975 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2976 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2977 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2978 static_cast<int32_t>(IdGenerator::Source::OTHER);
2979 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2981 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2982 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2984 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2985 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2986 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2987 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2988 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2989 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2990 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002991 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002992 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 }
2994 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2996 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002997 if (DEBUG_DISPATCH_CYCLE) {
2998 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2999 "enter event",
3000 connection->getInputChannelName().c_str());
3001 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003002 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3003 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003007 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3009 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3010 }
3011 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3012 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3016 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003017 if (DEBUG_DISPATCH_CYCLE) {
3018 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3019 "event",
3020 connection->getInputChannelName().c_str());
3021 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003022 return; // skip the inconsistent event
3023 }
3024
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003025 dispatchEntry->resolvedEventId =
3026 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3027 ? mIdGenerator.nextId()
3028 : motionEntry.id;
3029 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3030 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3031 ") to MotionEvent(id=0x%" PRIx32 ").",
3032 motionEntry.id, dispatchEntry->resolvedEventId);
3033 ATRACE_NAME(message.c_str());
3034 }
3035
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003036 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3037 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3038 // Skip reporting pointer down outside focus to the policy.
3039 break;
3040 }
3041
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003043 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044
3045 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003047 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003048 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003049 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3050 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003051 break;
3052 }
Chris Yef59a2f42020-10-16 12:55:26 -07003053 case EventEntry::Type::SENSOR: {
3054 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3055 break;
3056 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003057 case EventEntry::Type::CONFIGURATION_CHANGED:
3058 case EventEntry::Type::DEVICE_RESET: {
3059 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003060 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003061 break;
3062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 }
3064
3065 // Remember that we are waiting for this dispatch to complete.
3066 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003067 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069
3070 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003071 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003072 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003073}
3074
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003075/**
3076 * This function is purely for debugging. It helps us understand where the user interaction
3077 * was taking place. For example, if user is touching launcher, we will see a log that user
3078 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3079 * We will see both launcher and wallpaper in that list.
3080 * Once the interaction with a particular set of connections starts, no new logs will be printed
3081 * until the set of interacted connections changes.
3082 *
3083 * The following items are skipped, to reduce the logspam:
3084 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3085 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3086 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3087 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3088 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003089 */
3090void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3091 const std::vector<InputTarget>& targets) {
3092 // Skip ACTION_UP events, and all events other than keys and motions
3093 if (entry.type == EventEntry::Type::KEY) {
3094 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3095 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3096 return;
3097 }
3098 } else if (entry.type == EventEntry::Type::MOTION) {
3099 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3100 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3101 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3102 return;
3103 }
3104 } else {
3105 return; // Not a key or a motion
3106 }
3107
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003108 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003109 std::vector<sp<Connection>> newConnections;
3110 for (const InputTarget& target : targets) {
3111 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3112 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3113 continue; // Skip windows that receive ACTION_OUTSIDE
3114 }
3115
3116 sp<IBinder> token = target.inputChannel->getConnectionToken();
3117 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003118 if (connection == nullptr) {
3119 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003120 }
3121 newConnectionTokens.insert(std::move(token));
3122 newConnections.emplace_back(connection);
3123 }
3124 if (newConnectionTokens == mInteractionConnectionTokens) {
3125 return; // no change
3126 }
3127 mInteractionConnectionTokens = newConnectionTokens;
3128
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003129 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003130 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003131 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003132 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003133 std::string message = "Interaction with: " + targetList;
3134 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003135 message += "<none>";
3136 }
3137 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3138}
3139
chaviwfd6d3512019-03-25 13:23:49 -07003140void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003141 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003142 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003143 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3144 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003145 return;
3146 }
3147
Vishnu Nairc519ff72021-01-21 08:23:08 -08003148 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003149 if (focusedToken == token) {
3150 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003151 return;
3152 }
3153
Prabir Pradhancef936d2021-07-21 16:17:52 +00003154 auto command = [this, token]() REQUIRES(mLock) {
3155 scoped_unlock unlock(mLock);
3156 mPolicy->onPointerDownOutsideFocus(token);
3157 };
3158 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159}
3160
3161void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003163 if (ATRACE_ENABLED()) {
3164 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003166 ATRACE_NAME(message.c_str());
3167 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003168 if (DEBUG_DISPATCH_CYCLE) {
3169 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003172 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003173 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003175 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003176 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177
3178 // Publish the event.
3179 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3181 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003182 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3184 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003186 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003187 status = connection->inputPublisher
3188 .publishKeyEvent(dispatchEntry->seq,
3189 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3190 keyEntry.source, keyEntry.displayId,
3191 std::move(hmac), dispatchEntry->resolvedAction,
3192 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3193 keyEntry.scanCode, keyEntry.metaState,
3194 keyEntry.repeatCount, keyEntry.downTime,
3195 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003199 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003200 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003203 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204
chaviw82357092020-01-28 13:13:06 -08003205 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003206 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3208 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003209 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003210 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3211 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003212 // Don't apply window scale here since we don't want scale to affect raw
3213 // coordinates. The scale will be sent back to the client and applied
3214 // later when requesting relative coordinates.
3215 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3216 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 }
3218 usingCoords = scaledCoords;
3219 }
3220 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 // We don't want the dispatch target to know.
3222 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 scaledCoords[i].clear();
3225 }
3226 usingCoords = scaledCoords;
3227 }
3228 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003229
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003230 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231
3232 // Publish the motion event.
3233 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003234 .publishMotionEvent(dispatchEntry->seq,
3235 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 motionEntry.deviceId, motionEntry.source,
3237 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003238 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 motionEntry.edgeFlags, motionEntry.metaState,
3242 motionEntry.buttonState,
3243 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003244 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003245 motionEntry.xPrecision, motionEntry.yPrecision,
3246 motionEntry.xCursorPosition,
3247 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003248 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003249 motionEntry.downTime, motionEntry.eventTime,
3250 motionEntry.pointerCount,
3251 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 break;
3253 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003254
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003255 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003257 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003258 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003259 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003260 break;
3261 }
3262
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003263 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3264 const TouchModeEntry& touchModeEntry =
3265 static_cast<const TouchModeEntry&>(eventEntry);
3266 status = connection->inputPublisher
3267 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3268 touchModeEntry.inTouchMode);
3269
3270 break;
3271 }
3272
Prabir Pradhan99987712020-11-10 18:43:05 -08003273 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3274 const auto& captureEntry =
3275 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3276 status = connection->inputPublisher
3277 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003278 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003279 break;
3280 }
3281
arthurhungb89ccb02020-12-30 16:19:01 +08003282 case EventEntry::Type::DRAG: {
3283 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3284 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3285 dragEntry.id, dragEntry.x,
3286 dragEntry.y,
3287 dragEntry.isExiting);
3288 break;
3289 }
3290
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003291 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003292 case EventEntry::Type::DEVICE_RESET:
3293 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003294 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003295 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 }
3299
3300 // Check the result.
3301 if (status) {
3302 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003303 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 "This is unexpected because the wait queue is empty, so the pipe "
3306 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003307 "event to it, status=%s(%d)",
3308 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3309 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3311 } else {
3312 // Pipe is full and we are waiting for the app to finish process some events
3313 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003314 if (DEBUG_DISPATCH_CYCLE) {
3315 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3316 "waiting for the application to catch up",
3317 connection->getInputChannelName().c_str());
3318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 }
3320 } else {
3321 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003322 "status=%s(%d)",
3323 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3324 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3326 }
3327 return;
3328 }
3329
3330 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003331 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3332 connection->outboundQueue.end(),
3333 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003334 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003335 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003336 if (connection->responsive) {
3337 mAnrTracker.insert(dispatchEntry->timeoutTime,
3338 connection->inputChannel->getConnectionToken());
3339 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003340 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 }
3342}
3343
chaviw09c8d2d2020-08-24 15:48:26 -07003344std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3345 size_t size;
3346 switch (event.type) {
3347 case VerifiedInputEvent::Type::KEY: {
3348 size = sizeof(VerifiedKeyEvent);
3349 break;
3350 }
3351 case VerifiedInputEvent::Type::MOTION: {
3352 size = sizeof(VerifiedMotionEvent);
3353 break;
3354 }
3355 }
3356 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3357 return mHmacKeyManager.sign(start, size);
3358}
3359
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003360const std::array<uint8_t, 32> InputDispatcher::getSignature(
3361 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003362 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3363 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003364 // Only sign events up and down events as the purely move events
3365 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003366 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003367 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003368
3369 VerifiedMotionEvent verifiedEvent =
3370 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3371 verifiedEvent.actionMasked = actionMasked;
3372 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3373 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003374}
3375
3376const std::array<uint8_t, 32> InputDispatcher::getSignature(
3377 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3378 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3379 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3380 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003381 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003382}
3383
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003386 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003387 if (DEBUG_DISPATCH_CYCLE) {
3388 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3389 connection->getInputChannelName().c_str(), seq, toString(handled));
3390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003392 if (connection->status == Connection::Status::BROKEN ||
3393 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 return;
3395 }
3396
3397 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003398 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3399 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3400 };
3401 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402}
3403
3404void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 const sp<Connection>& connection,
3406 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003407 if (DEBUG_DISPATCH_CYCLE) {
3408 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3409 connection->getInputChannelName().c_str(), toString(notify));
3410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
3412 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003413 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417
3418 // The connection appears to be unrecoverably broken.
3419 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003420 if (connection->status == Connection::Status::NORMAL) {
3421 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422
3423 if (notify) {
3424 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003425 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3426 connection->getInputChannelName().c_str());
3427
3428 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003429 scoped_unlock unlock(mLock);
3430 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3431 };
3432 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 }
3434 }
3435}
3436
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003437void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3438 while (!queue.empty()) {
3439 DispatchEntry* dispatchEntry = queue.front();
3440 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003441 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 }
3443}
3444
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003445void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003447 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449 delete dispatchEntry;
3450}
3451
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003452int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3453 std::scoped_lock _l(mLock);
3454 sp<Connection> connection = getConnectionLocked(connectionToken);
3455 if (connection == nullptr) {
3456 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3457 connectionToken.get(), events);
3458 return 0; // remove the callback
3459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003461 bool notify;
3462 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3463 if (!(events & ALOOPER_EVENT_INPUT)) {
3464 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3465 "events=0x%x",
3466 connection->getInputChannelName().c_str(), events);
3467 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
3469
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003470 nsecs_t currentTime = now();
3471 bool gotOne = false;
3472 status_t status = OK;
3473 for (;;) {
3474 Result<InputPublisher::ConsumerResponse> result =
3475 connection->inputPublisher.receiveConsumerResponse();
3476 if (!result.ok()) {
3477 status = result.error().code();
3478 break;
3479 }
3480
3481 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3482 const InputPublisher::Finished& finish =
3483 std::get<InputPublisher::Finished>(*result);
3484 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3485 finish.consumeTime);
3486 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003487 if (shouldReportMetricsForConnection(*connection)) {
3488 const InputPublisher::Timeline& timeline =
3489 std::get<InputPublisher::Timeline>(*result);
3490 mLatencyTracker
3491 .trackGraphicsLatency(timeline.inputEventId,
3492 connection->inputChannel->getConnectionToken(),
3493 std::move(timeline.graphicsTimeline));
3494 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003495 }
3496 gotOne = true;
3497 }
3498 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003499 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003500 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 return 1;
3502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 }
3504
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003505 notify = status != DEAD_OBJECT || !connection->monitor;
3506 if (notify) {
3507 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3508 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3509 status);
3510 }
3511 } else {
3512 // Monitor channels are never explicitly unregistered.
3513 // We do it automatically when the remote endpoint is closed so don't warn about them.
3514 const bool stillHaveWindowHandle =
3515 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3516 notify = !connection->monitor && stillHaveWindowHandle;
3517 if (notify) {
3518 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3519 connection->getInputChannelName().c_str(), events);
3520 }
3521 }
3522
3523 // Remove the channel.
3524 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3525 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526}
3527
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003528void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003530 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003531 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533}
3534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003535void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003536 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003537 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003538 for (const Monitor& monitor : monitors) {
3539 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003540 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003541 }
3542}
3543
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003545 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003546 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003547 if (connection == nullptr) {
3548 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003550
3551 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552}
3553
3554void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3555 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003556 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 return;
3558 }
3559
3560 nsecs_t currentTime = now();
3561
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003562 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003563 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003565 if (cancelationEvents.empty()) {
3566 return;
3567 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003568 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3569 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3570 "with reality: %s, mode=%d.",
3571 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3572 options.mode);
3573 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003574
Arthur Hungb3307ee2021-10-14 10:57:37 +00003575 std::string reason = std::string("reason=").append(options.reason);
3576 android_log_event_list(LOGTAG_INPUT_CANCEL)
3577 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3578
Svet Ganov5d3bc372020-01-26 23:11:07 -08003579 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003580 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003581 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3582 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003583 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003584 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003585 target.globalScaleFactor = windowInfo->globalScaleFactor;
3586 }
3587 target.inputChannel = connection->inputChannel;
3588 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3589
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003590 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003591 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003592 switch (cancelationEventEntry->type) {
3593 case EventEntry::Type::KEY: {
3594 logOutboundKeyDetails("cancel - ",
3595 static_cast<const KeyEntry&>(*cancelationEventEntry));
3596 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003598 case EventEntry::Type::MOTION: {
3599 logOutboundMotionDetails("cancel - ",
3600 static_cast<const MotionEntry&>(*cancelationEventEntry));
3601 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003603 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003604 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003605 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3606 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003607 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003608 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003609 break;
3610 }
3611 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003612 case EventEntry::Type::DEVICE_RESET:
3613 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003614 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003615 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003616 break;
3617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003620 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3621 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003623
3624 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625}
3626
Svet Ganov5d3bc372020-01-26 23:11:07 -08003627void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3628 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003629 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003630 return;
3631 }
3632
3633 nsecs_t currentTime = now();
3634
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003635 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003636 connection->inputState.synthesizePointerDownEvents(currentTime);
3637
3638 if (downEvents.empty()) {
3639 return;
3640 }
3641
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003642 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003643 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3644 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003645 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003646
3647 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003648 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003649 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3650 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003651 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003652 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003653 target.globalScaleFactor = windowInfo->globalScaleFactor;
3654 }
3655 target.inputChannel = connection->inputChannel;
3656 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3657
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003658 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003659 switch (downEventEntry->type) {
3660 case EventEntry::Type::MOTION: {
3661 logOutboundMotionDetails("down - ",
3662 static_cast<const MotionEntry&>(*downEventEntry));
3663 break;
3664 }
3665
3666 case EventEntry::Type::KEY:
3667 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003668 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003670 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003671 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003672 case EventEntry::Type::SENSOR:
3673 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003674 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003675 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 break;
3677 }
3678 }
3679
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003680 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3681 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003682 }
3683
3684 startDispatchCycleLocked(currentTime, connection);
3685}
3686
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003687std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3688 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 ALOG_ASSERT(pointerIds.value != 0);
3690
3691 uint32_t splitPointerIndexMap[MAX_POINTERS];
3692 PointerProperties splitPointerProperties[MAX_POINTERS];
3693 PointerCoords splitPointerCoords[MAX_POINTERS];
3694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003695 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 uint32_t splitPointerCount = 0;
3697
3698 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003699 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003701 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 uint32_t pointerId = uint32_t(pointerProperties.id);
3703 if (pointerIds.hasBit(pointerId)) {
3704 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3705 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3706 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003707 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 splitPointerCount += 1;
3709 }
3710 }
3711
3712 if (splitPointerCount != pointerIds.count()) {
3713 // This is bad. We are missing some of the pointers that we expected to deliver.
3714 // Most likely this indicates that we received an ACTION_MOVE events that has
3715 // different pointer ids than we expected based on the previous ACTION_DOWN
3716 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3717 // in this way.
3718 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719 "we expected there to be %d pointers. This probably means we received "
3720 "a broken sequence of pointer ids from the input device.",
3721 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003722 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 }
3724
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003725 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003727 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3728 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3730 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003731 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 uint32_t pointerId = uint32_t(pointerProperties.id);
3733 if (pointerIds.hasBit(pointerId)) {
3734 if (pointerIds.count() == 1) {
3735 // The first/last pointer went down/up.
3736 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003737 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003738 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3739 ? AMOTION_EVENT_ACTION_CANCEL
3740 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 } else {
3742 // A secondary pointer went down/up.
3743 uint32_t splitPointerIndex = 0;
3744 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3745 splitPointerIndex += 1;
3746 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003747 action = maskedAction |
3748 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 }
3750 } else {
3751 // An unrelated pointer changed.
3752 action = AMOTION_EVENT_ACTION_MOVE;
3753 }
3754 }
3755
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003756 int32_t newId = mIdGenerator.nextId();
3757 if (ATRACE_ENABLED()) {
3758 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3759 ") to MotionEvent(id=0x%" PRIx32 ").",
3760 originalMotionEntry.id, newId);
3761 ATRACE_NAME(message.c_str());
3762 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003763 std::unique_ptr<MotionEntry> splitMotionEntry =
3764 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3765 originalMotionEntry.deviceId, originalMotionEntry.source,
3766 originalMotionEntry.displayId,
3767 originalMotionEntry.policyFlags, action,
3768 originalMotionEntry.actionButton,
3769 originalMotionEntry.flags, originalMotionEntry.metaState,
3770 originalMotionEntry.buttonState,
3771 originalMotionEntry.classification,
3772 originalMotionEntry.edgeFlags,
3773 originalMotionEntry.xPrecision,
3774 originalMotionEntry.yPrecision,
3775 originalMotionEntry.xCursorPosition,
3776 originalMotionEntry.yCursorPosition,
3777 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003778 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003780 if (originalMotionEntry.injectionState) {
3781 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 splitMotionEntry->injectionState->refCount += 1;
3783 }
3784
3785 return splitMotionEntry;
3786}
3787
3788void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003789 if (DEBUG_INBOUND_EVENT_DETAILS) {
3790 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
Antonio Kantekf16f2832021-09-28 04:39:20 +00003793 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003795 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003797 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3798 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3799 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 } // release lock
3801
3802 if (needWake) {
3803 mLooper->wake();
3804 }
3805}
3806
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003807/**
3808 * If one of the meta shortcuts is detected, process them here:
3809 * Meta + Backspace -> generate BACK
3810 * Meta + Enter -> generate HOME
3811 * This will potentially overwrite keyCode and metaState.
3812 */
3813void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003815 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3816 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3817 if (keyCode == AKEYCODE_DEL) {
3818 newKeyCode = AKEYCODE_BACK;
3819 } else if (keyCode == AKEYCODE_ENTER) {
3820 newKeyCode = AKEYCODE_HOME;
3821 }
3822 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003823 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003824 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003825 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003826 keyCode = newKeyCode;
3827 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3828 }
3829 } else if (action == AKEY_EVENT_ACTION_UP) {
3830 // In order to maintain a consistent stream of up and down events, check to see if the key
3831 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3832 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003833 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003834 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003835 auto replacementIt = mReplacedKeys.find(replacement);
3836 if (replacementIt != mReplacedKeys.end()) {
3837 keyCode = replacementIt->second;
3838 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003839 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3840 }
3841 }
3842}
3843
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003845 if (DEBUG_INBOUND_EVENT_DETAILS) {
3846 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3847 "policyFlags=0x%x, action=0x%x, "
3848 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3849 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3850 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3851 args->downTime);
3852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 if (!validateKeyEvent(args->action)) {
3854 return;
3855 }
3856
3857 uint32_t policyFlags = args->policyFlags;
3858 int32_t flags = args->flags;
3859 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003860 // InputDispatcher tracks and generates key repeats on behalf of
3861 // whatever notifies it, so repeatCount should always be set to 0
3862 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3864 policyFlags |= POLICY_FLAG_VIRTUAL;
3865 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 if (policyFlags & POLICY_FLAG_FUNCTION) {
3868 metaState |= AMETA_FUNCTION_ON;
3869 }
3870
3871 policyFlags |= POLICY_FLAG_TRUSTED;
3872
Michael Wright78f24442014-08-06 15:55:28 -07003873 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003874 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003875
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003877 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003878 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3879 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880
Michael Wright2b3c3302018-03-02 17:19:13 +00003881 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003883 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3884 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003885 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Antonio Kantekf16f2832021-09-28 04:39:20 +00003888 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 { // acquire lock
3890 mLock.lock();
3891
3892 if (shouldSendKeyToInputFilterLocked(args)) {
3893 mLock.unlock();
3894
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003895 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3897 return; // event was consumed by the filter
3898 }
3899
3900 mLock.lock();
3901 }
3902
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003903 std::unique_ptr<KeyEntry> newEntry =
3904 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3905 args->displayId, policyFlags, args->action, flags,
3906 keyCode, args->scanCode, metaState, repeatCount,
3907 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003909 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 mLock.unlock();
3911 } // release lock
3912
3913 if (needWake) {
3914 mLooper->wake();
3915 }
3916}
3917
3918bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3919 return mInputFilterEnabled;
3920}
3921
3922void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003923 if (DEBUG_INBOUND_EVENT_DETAILS) {
3924 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3925 "displayId=%" PRId32 ", policyFlags=0x%x, "
3926 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3927 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3928 "yCursorPosition=%f, downTime=%" PRId64,
3929 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3930 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3931 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3932 args->xCursorPosition, args->yCursorPosition, args->downTime);
3933 for (uint32_t i = 0; i < args->pointerCount; i++) {
3934 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3935 "x=%f, y=%f, pressure=%f, size=%f, "
3936 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3937 "orientation=%f",
3938 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3939 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3940 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3941 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3942 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3943 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3944 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3945 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3946 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3951 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 return;
3953 }
3954
3955 uint32_t policyFlags = args->policyFlags;
3956 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003957
3958 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003959 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003960 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3961 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
Antonio Kantekf16f2832021-09-28 04:39:20 +00003965 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 { // acquire lock
3967 mLock.lock();
3968
3969 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003970 ui::Transform displayTransform;
3971 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3972 displayTransform = it->second.transform;
3973 }
3974
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 mLock.unlock();
3976
3977 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003978 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3979 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003980 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003981 displayTransform, args->xPrecision, args->yPrecision,
3982 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003983 args->downTime, args->eventTime, args->pointerCount,
3984 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 policyFlags |= POLICY_FLAG_FILTERED;
3987 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3988 return; // event was consumed by the filter
3989 }
3990
3991 mLock.lock();
3992 }
3993
3994 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003995 std::unique_ptr<MotionEntry> newEntry =
3996 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3997 args->source, args->displayId, policyFlags,
3998 args->action, args->actionButton, args->flags,
3999 args->metaState, args->buttonState,
4000 args->classification, args->edgeFlags,
4001 args->xPrecision, args->yPrecision,
4002 args->xCursorPosition, args->yCursorPosition,
4003 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004004 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004006 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4007 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4008 !mInputFilterEnabled) {
4009 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4010 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4011 }
4012
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004013 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 mLock.unlock();
4015 } // release lock
4016
4017 if (needWake) {
4018 mLooper->wake();
4019 }
4020}
4021
Chris Yef59a2f42020-10-16 12:55:26 -07004022void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 if (DEBUG_INBOUND_EVENT_DETAILS) {
4024 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4025 " sensorType=%s",
4026 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004027 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 }
Chris Yef59a2f42020-10-16 12:55:26 -07004029
Antonio Kantekf16f2832021-09-28 04:39:20 +00004030 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004031 { // acquire lock
4032 mLock.lock();
4033
4034 // Just enqueue a new sensor event.
4035 std::unique_ptr<SensorEntry> newEntry =
4036 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4037 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4038 args->sensorType, args->accuracy,
4039 args->accuracyChanged, args->values);
4040
4041 needWake = enqueueInboundEventLocked(std::move(newEntry));
4042 mLock.unlock();
4043 } // release lock
4044
4045 if (needWake) {
4046 mLooper->wake();
4047 }
4048}
4049
Chris Yefb552902021-02-03 17:18:37 -08004050void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004051 if (DEBUG_INBOUND_EVENT_DETAILS) {
4052 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4053 args->deviceId, args->isOn);
4054 }
Chris Yefb552902021-02-03 17:18:37 -08004055 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4056}
4057
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004059 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060}
4061
4062void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004063 if (DEBUG_INBOUND_EVENT_DETAILS) {
4064 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4065 "switchMask=0x%08x",
4066 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068
4069 uint32_t policyFlags = args->policyFlags;
4070 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072}
4073
4074void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004075 if (DEBUG_INBOUND_EVENT_DETAILS) {
4076 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4077 args->deviceId);
4078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
Antonio Kantekf16f2832021-09-28 04:39:20 +00004080 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004082 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084 std::unique_ptr<DeviceResetEntry> newEntry =
4085 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4086 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 } // release lock
4088
4089 if (needWake) {
4090 mLooper->wake();
4091 }
4092}
4093
Prabir Pradhan7e186182020-11-10 13:56:45 -08004094void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004095 if (DEBUG_INBOUND_EVENT_DETAILS) {
4096 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004097 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004098 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004099
Antonio Kantekf16f2832021-09-28 04:39:20 +00004100 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004101 { // acquire lock
4102 std::scoped_lock _l(mLock);
4103 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004104 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004105 needWake = enqueueInboundEventLocked(std::move(entry));
4106 } // release lock
4107
4108 if (needWake) {
4109 mLooper->wake();
4110 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004111}
4112
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004113InputEventInjectionResult InputDispatcher::injectInputEvent(
4114 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4115 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004116 if (DEBUG_INBOUND_EVENT_DETAILS) {
4117 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4118 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4119 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4120 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004121 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
4123 policyFlags |= POLICY_FLAG_INJECTED;
4124 if (hasInjectionPermission(injectorPid, injectorUid)) {
4125 policyFlags |= POLICY_FLAG_TRUSTED;
4126 }
4127
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004128 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004129 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4130 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4131 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4132 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4133 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004134 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004135 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004136 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004137 }
4138
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004139 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004142 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4143 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004148 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004149 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4150 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4151 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004152 int32_t keyCode = incomingKey.getKeyCode();
4153 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004154 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004156 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004157 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004158 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4159 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4160 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4163 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165
4166 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4167 android::base::Timer t;
4168 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4169 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4170 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4171 std::to_string(t.duration().count()).c_str());
4172 }
4173 }
4174
4175 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004176 std::unique_ptr<KeyEntry> injectedEntry =
4177 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 incomingKey.getDisplayId(), policyFlags, action,
4180 flags, keyCode, incomingKey.getScanCode(), metaState,
4181 incomingKey.getRepeatCount(),
4182 incomingKey.getDownTime());
4183 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
4186
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004188 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004189 const int32_t action = motionEvent.getAction();
4190 const bool isPointerEvent =
4191 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4192 // If a pointer event has no displayId specified, inject it to the default display.
4193 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4194 ? ADISPLAY_ID_DEFAULT
4195 : event->getDisplayId();
4196 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004197 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004198 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004199 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 }
4203
4204 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004205 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 android::base::Timer t;
4207 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4208 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4209 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4210 std::to_string(t.duration().count()).c_str());
4211 }
4212 }
4213
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004214 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4215 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4216 }
4217
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004218 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004219 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4220 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004221 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004222 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4223 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004224 displayId, policyFlags, action, actionButton,
4225 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004226 motionEvent.getButtonState(),
4227 motionEvent.getClassification(),
4228 motionEvent.getEdgeFlags(),
4229 motionEvent.getXPrecision(),
4230 motionEvent.getYPrecision(),
4231 motionEvent.getRawXCursorPosition(),
4232 motionEvent.getRawYCursorPosition(),
4233 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004234 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004235 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 sampleEventTimes += 1;
4239 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004240 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004241 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4242 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004243 displayId, policyFlags, action, actionButton,
4244 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004245 motionEvent.getButtonState(),
4246 motionEvent.getClassification(),
4247 motionEvent.getEdgeFlags(),
4248 motionEvent.getXPrecision(),
4249 motionEvent.getYPrecision(),
4250 motionEvent.getRawXCursorPosition(),
4251 motionEvent.getRawYCursorPosition(),
4252 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004253 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004254 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004255 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4256 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004257 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 }
4259 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004263 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 }
4266
4267 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004268 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 injectionState->injectionIsAsync = true;
4270 }
4271
4272 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004273 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
4275 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004276 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004278 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280
4281 mLock.unlock();
4282
4283 if (needWake) {
4284 mLooper->wake();
4285 }
4286
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004287 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004289 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 if (syncMode == InputEventInjectionSync::NONE) {
4292 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 } else {
4294 for (;;) {
4295 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 break;
4298 }
4299
4300 nsecs_t remainingTimeout = endTime - now();
4301 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004302 if (DEBUG_INJECTION) {
4303 ALOGD("injectInputEvent - Timed out waiting for injection result "
4304 "to become available.");
4305 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 break;
4308 }
4309
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004310 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004313 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4314 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004316 if (DEBUG_INJECTION) {
4317 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4318 injectionState->pendingForegroundDispatches);
4319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 nsecs_t remainingTimeout = endTime - now();
4321 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004322 if (DEBUG_INJECTION) {
4323 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4324 "dispatches to finish.");
4325 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 break;
4328 }
4329
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004330 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332 }
4333 }
4334
4335 injectionState->release();
4336 } // release lock
4337
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004338 if (DEBUG_INJECTION) {
4339 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4340 injectionResult, injectorPid, injectorUid);
4341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342
4343 return injectionResult;
4344}
4345
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004346std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004347 std::array<uint8_t, 32> calculatedHmac;
4348 std::unique_ptr<VerifiedInputEvent> result;
4349 switch (event.getType()) {
4350 case AINPUT_EVENT_TYPE_KEY: {
4351 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4352 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4353 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004354 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004355 break;
4356 }
4357 case AINPUT_EVENT_TYPE_MOTION: {
4358 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4359 VerifiedMotionEvent verifiedMotionEvent =
4360 verifiedMotionEventFromMotionEvent(motionEvent);
4361 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004362 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004363 break;
4364 }
4365 default: {
4366 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4367 return nullptr;
4368 }
4369 }
4370 if (calculatedHmac == INVALID_HMAC) {
4371 return nullptr;
4372 }
4373 if (calculatedHmac != event.getHmac()) {
4374 return nullptr;
4375 }
4376 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004377}
4378
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 return injectorUid == 0 ||
4381 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382}
4383
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004384void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004386 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004388 if (DEBUG_INJECTION) {
4389 ALOGD("Setting input event injection result to %d. "
4390 "injectorPid=%d, injectorUid=%d",
4391 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004394 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 // Log the outcome since the injector did not wait for the injection result.
4396 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004397 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 ALOGV("Asynchronous input event injection succeeded.");
4399 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 ALOGW("Asynchronous input event injection failed.");
4402 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 ALOGW("Asynchronous input event injection permission denied.");
4405 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 ALOGW("Asynchronous input event injection timed out.");
4408 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004409 case InputEventInjectionResult::PENDING:
4410 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4411 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 }
4413 }
4414
4415 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004416 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
4418}
4419
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004420void InputDispatcher::transformMotionEntryForInjectionLocked(
4421 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004422 // Input injection works in the logical display coordinate space, but the input pipeline works
4423 // display space, so we need to transform the injected events accordingly.
4424 const auto it = mDisplayInfos.find(entry.displayId);
4425 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004426 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004427
4428 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4429 PointerCoords& pc = entry.pointerCoords[i];
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004430 // Make a copy of the injected coords. We cannot change them in place because some of them
4431 // are interdependent (for example, X coordinate might depend on the Y coordinate).
4432 PointerCoords injectedCoords = entry.pointerCoords[i];
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004433
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004434 BitSet64 bits(injectedCoords.bits);
4435 while (!bits.isEmpty()) {
4436 const auto axis = static_cast<int32_t>(bits.clearFirstMarkedBit());
4437 const float value =
4438 MotionEvent::calculateTransformedAxisValue(axis, entry.source,
4439 transformToDisplay, injectedCoords);
4440 pc.setAxisValue(axis, value);
4441 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004442 }
4443}
4444
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004445void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4446 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 if (injectionState) {
4448 injectionState->pendingForegroundDispatches += 1;
4449 }
4450}
4451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004452void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4453 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 if (injectionState) {
4455 injectionState->pendingForegroundDispatches -= 1;
4456
4457 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004458 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460 }
4461}
4462
chaviw98318de2021-05-19 16:45:23 -05004463const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004464 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004465 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004466 auto it = mWindowHandlesByDisplay.find(displayId);
4467 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004468}
4469
chaviw98318de2021-05-19 16:45:23 -05004470sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004471 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004472 if (windowHandleToken == nullptr) {
4473 return nullptr;
4474 }
4475
Arthur Hungb92218b2018-08-14 12:00:21 +08004476 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004477 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4478 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004479 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004480 return windowHandle;
4481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004484 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485}
4486
chaviw98318de2021-05-19 16:45:23 -05004487sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4488 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004489 if (windowHandleToken == nullptr) {
4490 return nullptr;
4491 }
4492
chaviw98318de2021-05-19 16:45:23 -05004493 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004494 if (windowHandle->getToken() == windowHandleToken) {
4495 return windowHandle;
4496 }
4497 }
4498 return nullptr;
4499}
4500
chaviw98318de2021-05-19 16:45:23 -05004501sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4502 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004503 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004504 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4505 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004506 if (handle->getId() == windowHandle->getId() &&
4507 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004508 if (windowHandle->getInfo()->displayId != it.first) {
4509 ALOGE("Found window %s in display %" PRId32
4510 ", but it should belong to display %" PRId32,
4511 windowHandle->getName().c_str(), it.first,
4512 windowHandle->getInfo()->displayId);
4513 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004514 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 }
4517 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004518 return nullptr;
4519}
4520
chaviw98318de2021-05-19 16:45:23 -05004521sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004522 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4523 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524}
4525
chaviw98318de2021-05-19 16:45:23 -05004526bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004527 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4528 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004529 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004530 if (connection != nullptr && noInputChannel) {
4531 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4532 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4533 return false;
4534 }
4535
4536 if (connection == nullptr) {
4537 if (!noInputChannel) {
4538 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4539 }
4540 return false;
4541 }
4542 if (!connection->responsive) {
4543 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4544 return false;
4545 }
4546 return true;
4547}
4548
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004549std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4550 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004551 auto connectionIt = mConnectionsByToken.find(token);
4552 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004553 return nullptr;
4554 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004555 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004556}
4557
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004558void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004559 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4560 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004561 // Remove all handles on a display if there are no windows left.
4562 mWindowHandlesByDisplay.erase(displayId);
4563 return;
4564 }
4565
4566 // Since we compare the pointer of input window handles across window updates, we need
4567 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004568 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4569 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4570 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004571 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004572 }
4573
chaviw98318de2021-05-19 16:45:23 -05004574 std::vector<sp<WindowInfoHandle>> newHandles;
4575 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004576 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004577 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004578 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004579 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004580 const bool canReceiveInput =
4581 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4582 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004583 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004584 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004585 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004586 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004587 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004588 }
4589
4590 if (info->displayId != displayId) {
4591 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4592 handle->getName().c_str(), displayId, info->displayId);
4593 continue;
4594 }
4595
Robert Carredd13602020-04-13 17:24:34 -07004596 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4597 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004598 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004599 oldHandle->updateFrom(handle);
4600 newHandles.push_back(oldHandle);
4601 } else {
4602 newHandles.push_back(handle);
4603 }
4604 }
4605
4606 // Insert or replace
4607 mWindowHandlesByDisplay[displayId] = newHandles;
4608}
4609
Arthur Hung72d8dc32020-03-28 00:48:39 +00004610void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004611 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004612 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004613 { // acquire lock
4614 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004615 for (const auto& [displayId, handles] : handlesPerDisplay) {
4616 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004617 }
4618 }
4619 // Wake up poll loop since it may need to make new input dispatching choices.
4620 mLooper->wake();
4621}
4622
Arthur Hungb92218b2018-08-14 12:00:21 +08004623/**
4624 * Called from InputManagerService, update window handle list by displayId that can receive input.
4625 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4626 * If set an empty list, remove all handles from the specific display.
4627 * For focused handle, check if need to change and send a cancel event to previous one.
4628 * For removed handle, check if need to send a cancel event if already in touch.
4629 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004630void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004631 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004632 if (DEBUG_FOCUS) {
4633 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004634 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004635 windowList += iwh->getName() + " ";
4636 }
4637 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639
Prabir Pradhand65552b2021-10-07 11:23:50 -07004640 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004641 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004642 const WindowInfo& info = *window->getInfo();
4643
4644 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4645 const bool noInputWindow = info.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004646 if (noInputWindow && window->getToken() != nullptr) {
4647 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4648 window->getName().c_str());
4649 window->releaseChannel();
4650 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004651
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004652 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004653 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4654 !info.inputConfig.test(
4655 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004656 "%s has feature SPY, but is not a trusted overlay.",
4657 window->getName().c_str());
4658
Prabir Pradhand65552b2021-10-07 11:23:50 -07004659 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004660 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4661 !info.inputConfig.test(
4662 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004663 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4664 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004665 }
4666
Arthur Hung72d8dc32020-03-28 00:48:39 +00004667 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004668 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004670 // Save the old windows' orientation by ID before it gets updated.
4671 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004672 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004673 oldWindowOrientations.emplace(handle->getId(),
4674 handle->getInfo()->transform.getOrientation());
4675 }
4676
chaviw98318de2021-05-19 16:45:23 -05004677 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004678
chaviw98318de2021-05-19 16:45:23 -05004679 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004680 if (mLastHoverWindowHandle &&
4681 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4682 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004683 mLastHoverWindowHandle = nullptr;
4684 }
4685
Vishnu Nairc519ff72021-01-21 08:23:08 -08004686 std::optional<FocusResolver::FocusChanges> changes =
4687 mFocusResolver.setInputWindows(displayId, windowHandles);
4688 if (changes) {
4689 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004692 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4693 mTouchStatesByDisplay.find(displayId);
4694 if (stateIt != mTouchStatesByDisplay.end()) {
4695 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004696 for (size_t i = 0; i < state.windows.size();) {
4697 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004698 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004699 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004700 ALOGD("Touched window was removed: %s in display %" PRId32,
4701 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004702 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004703 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004704 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4705 if (touchedInputChannel != nullptr) {
4706 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4707 "touched window was removed");
4708 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004709 // Since we are about to drop the touch, cancel the events for the wallpaper as
4710 // well.
4711 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004712 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4713 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004714 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4715 if (wallpaper != nullptr) {
4716 sp<Connection> wallpaperConnection =
4717 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004718 if (wallpaperConnection != nullptr) {
4719 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4720 options);
4721 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004722 }
4723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004725 state.windows.erase(state.windows.begin() + i);
4726 } else {
4727 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729 }
arthurhungb89ccb02020-12-30 16:19:01 +08004730
arthurhung6d4bed92021-03-17 11:59:33 +08004731 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004732 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004733 if (mDragState &&
4734 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004735 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004736 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004737 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004738 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004739
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004740 // Determine if the orientation of any of the input windows have changed, and cancel all
4741 // pointer events if necessary.
4742 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4743 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4744 if (newWindowHandle != nullptr &&
4745 newWindowHandle->getInfo()->transform.getOrientation() !=
4746 oldWindowOrientations[oldWindowHandle->getId()]) {
4747 std::shared_ptr<InputChannel> inputChannel =
4748 getInputChannelLocked(newWindowHandle->getToken());
4749 if (inputChannel != nullptr) {
4750 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4751 "touched window's orientation changed");
4752 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004753 }
4754 }
4755 }
4756
Arthur Hung72d8dc32020-03-28 00:48:39 +00004757 // Release information for windows that are no longer present.
4758 // This ensures that unused input channels are released promptly.
4759 // Otherwise, they might stick around until the window handle is destroyed
4760 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004761 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004762 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004763 if (DEBUG_FOCUS) {
4764 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004765 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004766 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004767 }
chaviw291d88a2019-02-14 10:33:58 -08004768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769}
4770
4771void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004772 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004773 if (DEBUG_FOCUS) {
4774 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4775 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4776 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004777 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004778 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004779 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 } // release lock
4781
4782 // Wake up poll loop since it may need to make new input dispatching choices.
4783 mLooper->wake();
4784}
4785
Vishnu Nair599f1412021-06-21 10:39:58 -07004786void InputDispatcher::setFocusedApplicationLocked(
4787 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4788 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4789 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4790
4791 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4792 return; // This application is already focused. No need to wake up or change anything.
4793 }
4794
4795 // Set the new application handle.
4796 if (inputApplicationHandle != nullptr) {
4797 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4798 } else {
4799 mFocusedApplicationHandlesByDisplay.erase(displayId);
4800 }
4801
4802 // No matter what the old focused application was, stop waiting on it because it is
4803 // no longer focused.
4804 resetNoFocusedWindowTimeoutLocked();
4805}
4806
Tiger Huang721e26f2018-07-24 22:26:19 +08004807/**
4808 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4809 * the display not specified.
4810 *
4811 * We track any unreleased events for each window. If a window loses the ability to receive the
4812 * released event, we will send a cancel event to it. So when the focused display is changed, we
4813 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4814 * display. The display-specified events won't be affected.
4815 */
4816void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004817 if (DEBUG_FOCUS) {
4818 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4819 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004820 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004821 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004822
4823 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004824 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004825 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004826 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004827 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004828 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004829 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830 CancelationOptions
4831 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4832 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004833 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004834 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4835 }
4836 }
4837 mFocusedDisplayId = displayId;
4838
Chris Ye3c2d6f52020-08-09 10:39:48 -07004839 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004840 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004841 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004842
Vishnu Nairad321cd2020-08-20 16:40:21 -07004843 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004844 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004845 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004846 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004847 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004848 }
4849 }
4850 }
4851
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004852 if (DEBUG_FOCUS) {
4853 logDispatchStateLocked();
4854 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004855 } // release lock
4856
4857 // Wake up poll loop since it may need to make new input dispatching choices.
4858 mLooper->wake();
4859}
4860
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004862 if (DEBUG_FOCUS) {
4863 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865
4866 bool changed;
4867 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004868 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869
4870 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4871 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874
4875 if (mDispatchEnabled && !enabled) {
4876 resetAndDropEverythingLocked("dispatcher is being disabled");
4877 }
4878
4879 mDispatchEnabled = enabled;
4880 mDispatchFrozen = frozen;
4881 changed = true;
4882 } else {
4883 changed = false;
4884 }
4885
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004886 if (DEBUG_FOCUS) {
4887 logDispatchStateLocked();
4888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 } // release lock
4890
4891 if (changed) {
4892 // Wake up poll loop since it may need to make new input dispatching choices.
4893 mLooper->wake();
4894 }
4895}
4896
4897void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004898 if (DEBUG_FOCUS) {
4899 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
4902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004903 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904
4905 if (mInputFilterEnabled == enabled) {
4906 return;
4907 }
4908
4909 mInputFilterEnabled = enabled;
4910 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4911 } // release lock
4912
4913 // Wake up poll loop since there might be work to do to drop everything.
4914 mLooper->wake();
4915}
4916
Antonio Kantekea47acb2021-12-23 12:41:25 -08004917bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4918 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004919 bool needWake = false;
4920 {
4921 std::scoped_lock lock(mLock);
4922 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004923 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004924 }
4925 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004926 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4927 "hasPermission=%s)",
4928 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4929 }
4930 if (!hasPermission) {
4931 const sp<IBinder> focusedToken =
4932 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4933
Antonio Kantek019eb662022-02-08 13:41:52 -08004934 // TODO(b/218541064): if no window is currently focused, then we need to check the last
Antonio Kantekea47acb2021-12-23 12:41:25 -08004935 // interacted window (within 1 second timeout). We should allow touch mode change
4936 // if the last interacted window owner's pid/uid match the calling ones.
4937 if (focusedToken == nullptr) {
4938 return false;
4939 }
4940 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4941 if (windowHandle == nullptr) {
4942 return false;
4943 }
4944 const WindowInfo* windowInfo = windowHandle->getInfo();
4945 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4946 return false;
4947 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004948 }
4949
4950 // TODO(b/198499018): Store touch mode per display.
4951 mInTouchMode = inTouchMode;
4952
Antonio Kantekf16f2832021-09-28 04:39:20 +00004953 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4954 needWake = enqueueInboundEventLocked(std::move(entry));
4955 } // release lock
4956
4957 if (needWake) {
4958 mLooper->wake();
4959 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004960 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004961}
4962
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004963void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4964 if (opacity < 0 || opacity > 1) {
4965 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4966 return;
4967 }
4968
4969 std::scoped_lock lock(mLock);
4970 mMaximumObscuringOpacityForTouch = opacity;
4971}
4972
4973void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4974 std::scoped_lock lock(mLock);
4975 mBlockUntrustedTouchesMode = mode;
4976}
4977
Arthur Hungabbb9d82021-09-01 14:52:30 +00004978std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4979 const sp<IBinder>& token) {
4980 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4981 for (TouchedWindow& w : state.windows) {
4982 if (w.windowHandle->getToken() == token) {
4983 return std::make_pair(&state, &w);
4984 }
4985 }
4986 }
4987 return std::make_pair(nullptr, nullptr);
4988}
4989
arthurhungb89ccb02020-12-30 16:19:01 +08004990bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4991 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004992 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004993 if (DEBUG_FOCUS) {
4994 ALOGD("Trivial transfer to same window.");
4995 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004996 return true;
4997 }
4998
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005000 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001
Arthur Hungabbb9d82021-09-01 14:52:30 +00005002 // Find the target touch state and touched window by fromToken.
5003 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5004 if (state == nullptr || touchedWindow == nullptr) {
5005 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 return false;
5007 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005008
5009 const int32_t displayId = state->displayId;
5010 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5011 if (toWindowHandle == nullptr) {
5012 ALOGW("Cannot transfer focus because to window not found.");
5013 return false;
5014 }
5015
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005016 if (DEBUG_FOCUS) {
5017 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005018 touchedWindow->windowHandle->getName().c_str(),
5019 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 }
5021
Arthur Hungabbb9d82021-09-01 14:52:30 +00005022 // Erase old window.
5023 int32_t oldTargetFlags = touchedWindow->targetFlags;
5024 BitSet32 pointerIds = touchedWindow->pointerIds;
5025 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026
Arthur Hungabbb9d82021-09-01 14:52:30 +00005027 // Add new window.
5028 int32_t newTargetFlags = oldTargetFlags &
5029 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5030 InputTarget::FLAG_DISPATCH_AS_IS);
5031 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032
Arthur Hungabbb9d82021-09-01 14:52:30 +00005033 // Store the dragging window.
5034 if (isDragDrop) {
5035 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
5037
Arthur Hungabbb9d82021-09-01 14:52:30 +00005038 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005039 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5040 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005041 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005042 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 CancelationOptions
5044 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5045 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005047 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 }
5049
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005050 if (DEBUG_FOCUS) {
5051 logDispatchStateLocked();
5052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 } // release lock
5054
5055 // Wake up poll loop since it may need to make new input dispatching choices.
5056 mLooper->wake();
5057 return true;
5058}
5059
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005060// Binder call
5061bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5062 sp<IBinder> fromToken;
5063 { // acquire lock
5064 std::scoped_lock _l(mLock);
5065
Arthur Hungabbb9d82021-09-01 14:52:30 +00005066 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5067 [](const auto& pair) { return pair.second.windows.size() == 1; });
5068 if (it == mTouchStatesByDisplay.end()) {
5069 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5070 return false;
5071 }
5072 const int32_t displayId = it->first;
5073 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005074 if (toWindowHandle == nullptr) {
5075 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5076 return false;
5077 }
5078
Arthur Hungabbb9d82021-09-01 14:52:30 +00005079 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005080 const TouchedWindow& touchedWindow = state.windows[0];
5081 fromToken = touchedWindow.windowHandle->getToken();
5082 } // release lock
5083
5084 return transferTouchFocus(fromToken, destChannelToken);
5085}
5086
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005088 if (DEBUG_FOCUS) {
5089 ALOGD("Resetting and dropping all events (%s).", reason);
5090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091
5092 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5093 synthesizeCancelationEventsForAllConnectionsLocked(options);
5094
5095 resetKeyRepeatLocked();
5096 releasePendingEventLocked();
5097 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005098 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005101 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005103 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104}
5105
5106void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005107 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 dumpDispatchStateLocked(dump);
5109
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 std::istringstream stream(dump);
5111 std::string line;
5112
5113 while (std::getline(stream, line, '\n')) {
5114 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
5116}
5117
Prabir Pradhan99987712020-11-10 18:43:05 -08005118std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5119 std::string dump;
5120
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005121 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5122 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005123
5124 std::string windowName = "None";
5125 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005126 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005127 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5128 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5129 : "token has capture without window";
5130 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005131 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005132
5133 return dump;
5134}
5135
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005136void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005137 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5138 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5139 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005140 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141
Tiger Huang721e26f2018-07-24 22:26:19 +08005142 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5143 dump += StringPrintf(INDENT "FocusedApplications:\n");
5144 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5145 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005146 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005147 const std::chrono::duration timeout =
5148 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005149 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005150 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005151 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005154 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005156
Vishnu Nairc519ff72021-01-21 08:23:08 -08005157 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005158 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005160 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005161 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005162 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5163 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005164 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005165 state.displayId, toString(state.down), toString(state.split),
5166 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005167 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005168 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005169 for (size_t i = 0; i < state.windows.size(); i++) {
5170 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005171 dump += StringPrintf(INDENT4
5172 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5173 i, touchedWindow.windowHandle->getName().c_str(),
5174 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005175 }
5176 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 }
5180 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005181 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 }
5183
arthurhung6d4bed92021-03-17 11:59:33 +08005184 if (mDragState) {
5185 dump += StringPrintf(INDENT "DragState:\n");
5186 mDragState->dump(dump, INDENT2);
5187 }
5188
Arthur Hungb92218b2018-08-14 12:00:21 +08005189 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005190 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5191 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5192 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5193 const auto& displayInfo = it->second;
5194 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5195 displayInfo.logicalHeight);
5196 displayInfo.transform.dump(dump, "transform", INDENT4);
5197 } else {
5198 dump += INDENT2 "No DisplayInfo found!\n";
5199 }
5200
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005201 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005202 dump += INDENT2 "Windows:\n";
5203 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005204 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5205 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005207 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005208 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005209 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005210 "applicationInfo.name=%s, "
5211 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005212 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005213 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005214 windowInfo->displayId,
5215 windowInfo->inputConfig.string().c_str(),
5216 windowInfo->alpha, windowInfo->frameLeft,
5217 windowInfo->frameTop, windowInfo->frameRight,
5218 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005219 windowInfo->applicationInfo.name.c_str(),
5220 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005221 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005222 dump += StringPrintf(", inputFeatures=%s",
5223 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005224 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005225 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005226 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005227 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005228 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005229 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005230 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005231 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005232 }
5233 } else {
5234 dump += INDENT2 "Windows: <none>\n";
5235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 }
5237 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005238 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 }
5240
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005241 if (!mGlobalMonitorsByDisplay.empty()) {
5242 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5243 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005244 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005247 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 }
5249
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005250 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
5252 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005253 if (!mRecentQueue.empty()) {
5254 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005255 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005256 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005257 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005258 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 }
5260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005261 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
5263
5264 // Dump event currently being dispatched.
5265 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005266 dump += INDENT "PendingEvent:\n";
5267 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005268 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005269 dump += StringPrintf(", age=%" PRId64 "ms\n",
5270 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005272 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 }
5274
5275 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005276 if (!mInboundQueue.empty()) {
5277 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005278 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005279 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005280 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005281 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 }
5283 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005284 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005287 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005288 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005289 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5290 const KeyReplacement& replacement = pair.first;
5291 int32_t newKeyCode = pair.second;
5292 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005293 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005294 }
5295 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005296 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005297 }
5298
Prabir Pradhancef936d2021-07-21 16:17:52 +00005299 if (!mCommandQueue.empty()) {
5300 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5301 } else {
5302 dump += INDENT "CommandQueue: <empty>\n";
5303 }
5304
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005305 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005307 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005308 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005309 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005310 connection->inputChannel->getFd().get(),
5311 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005312 connection->getWindowName().c_str(),
5313 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005314 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005316 if (!connection->outboundQueue.empty()) {
5317 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5318 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005319 dump += dumpQueue(connection->outboundQueue, currentTime);
5320
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005322 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 }
5324
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005325 if (!connection->waitQueue.empty()) {
5326 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5327 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005328 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005330 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 }
5332 }
5333 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336
5337 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005338 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5339 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005341 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 }
5343
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005344 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005345 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5346 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5347 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005348 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005349 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350}
5351
Michael Wright3dd60e22019-03-27 22:06:44 +00005352void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5353 const size_t numMonitors = monitors.size();
5354 for (size_t i = 0; i < numMonitors; i++) {
5355 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005356 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005357 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5358 dump += "\n";
5359 }
5360}
5361
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005362class LooperEventCallback : public LooperCallback {
5363public:
5364 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5365 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5366
5367private:
5368 std::function<int(int events)> mCallback;
5369};
5370
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005371Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005372 if (DEBUG_CHANNEL_CREATION) {
5373 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005376 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005377 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005378 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005379
5380 if (result) {
5381 return base::Error(result) << "Failed to open input channel pair with name " << name;
5382 }
5383
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005385 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005386 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005387 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005388 sp<Connection> connection =
5389 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005391 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5392 ALOGE("Created a new connection, but the token %p is already known", token.get());
5393 }
5394 mConnectionsByToken.emplace(token, connection);
5395
5396 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5397 this, std::placeholders::_1, token);
5398
5399 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 } // release lock
5401
5402 // Wake the looper because some connections have changed.
5403 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005404 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405}
5406
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005407Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005408 const std::string& name,
5409 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005410 std::shared_ptr<InputChannel> serverChannel;
5411 std::unique_ptr<InputChannel> clientChannel;
5412 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5413 if (result) {
5414 return base::Error(result) << "Failed to open input channel pair with name " << name;
5415 }
5416
Michael Wright3dd60e22019-03-27 22:06:44 +00005417 { // acquire lock
5418 std::scoped_lock _l(mLock);
5419
5420 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005421 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5422 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005423 }
5424
Garfield Tan15601662020-09-22 15:32:38 -07005425 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005426 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005427 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005428
5429 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5430 ALOGE("Created a new connection, but the token %p is already known", token.get());
5431 }
5432 mConnectionsByToken.emplace(token, connection);
5433 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5434 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005435
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005436 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005437
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005438 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005439 }
Garfield Tan15601662020-09-22 15:32:38 -07005440
Michael Wright3dd60e22019-03-27 22:06:44 +00005441 // Wake the looper because some connections have changed.
5442 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005443 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005444}
5445
Garfield Tan15601662020-09-22 15:32:38 -07005446status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005448 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449
Garfield Tan15601662020-09-22 15:32:38 -07005450 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 if (status) {
5452 return status;
5453 }
5454 } // release lock
5455
5456 // Wake the poll loop because removing the connection may have changed the current
5457 // synchronization state.
5458 mLooper->wake();
5459 return OK;
5460}
5461
Garfield Tan15601662020-09-22 15:32:38 -07005462status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5463 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005464 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005465 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005466 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 return BAD_VALUE;
5468 }
5469
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005470 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005471
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005473 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 }
5475
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005476 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477
5478 nsecs_t currentTime = now();
5479 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5480
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005481 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 return OK;
5483}
5484
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005485void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005486 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5487 auto& [displayId, monitors] = *it;
5488 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5489 return monitor.inputChannel->getConnectionToken() == connectionToken;
5490 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005491
Michael Wright3dd60e22019-03-27 22:06:44 +00005492 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005493 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005494 } else {
5495 ++it;
5496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
5498}
5499
Michael Wright3dd60e22019-03-27 22:06:44 +00005500status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005501 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005502
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005503 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5504 if (!requestingChannel) {
5505 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5506 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005507 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005508
5509 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5510 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5511 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5512 " Ignoring.");
5513 return BAD_VALUE;
5514 }
5515
5516 TouchState& state = *statePtr;
5517
5518 // Send cancel events to all the input channels we're stealing from.
5519 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5520 "input channel stole pointer stream");
5521 options.deviceId = state.deviceId;
5522 options.displayId = state.displayId;
5523 std::string canceledWindows;
5524 for (const TouchedWindow& window : state.windows) {
5525 const std::shared_ptr<InputChannel> channel =
5526 getInputChannelLocked(window.windowHandle->getToken());
5527 if (channel != nullptr && channel->getConnectionToken() != token) {
5528 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5529 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5530 canceledWindows += channel->getName();
5531 }
5532 }
5533 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5534 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5535 canceledWindows.c_str());
5536
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005537 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005538 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005539 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005540 return OK;
5541}
5542
Prabir Pradhan99987712020-11-10 18:43:05 -08005543void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5544 { // acquire lock
5545 std::scoped_lock _l(mLock);
5546 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005547 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005548 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5549 windowHandle != nullptr ? windowHandle->getName().c_str()
5550 : "token without window");
5551 }
5552
Vishnu Nairc519ff72021-01-21 08:23:08 -08005553 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005554 if (focusedToken != windowToken) {
5555 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5556 enabled ? "enable" : "disable");
5557 return;
5558 }
5559
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005560 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005561 ALOGW("Ignoring request to %s Pointer Capture: "
5562 "window has %s requested pointer capture.",
5563 enabled ? "enable" : "disable", enabled ? "already" : "not");
5564 return;
5565 }
5566
Christine Franksb768bb42021-11-29 12:11:31 -08005567 if (enabled) {
5568 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5569 mIneligibleDisplaysForPointerCapture.end(),
5570 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5571 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5572 return;
5573 }
5574 }
5575
Prabir Pradhan99987712020-11-10 18:43:05 -08005576 setPointerCaptureLocked(enabled);
5577 } // release lock
5578
5579 // Wake the thread to process command entries.
5580 mLooper->wake();
5581}
5582
Christine Franksb768bb42021-11-29 12:11:31 -08005583void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5584 { // acquire lock
5585 std::scoped_lock _l(mLock);
5586 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5587 if (!isEligible) {
5588 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5589 }
5590 } // release lock
5591}
5592
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005593std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5594 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005595 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005596 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005597 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005598 }
5599 }
5600 }
5601 return std::nullopt;
5602}
5603
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005604sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005605 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005606 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005607 }
5608
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005609 for (const auto& [token, connection] : mConnectionsByToken) {
5610 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005611 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
5613 }
Robert Carr4e670e52018-08-15 13:26:12 -07005614
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005615 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616}
5617
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005618std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5619 sp<Connection> connection = getConnectionLocked(connectionToken);
5620 if (connection == nullptr) {
5621 return "<nullptr>";
5622 }
5623 return connection->getInputChannelName();
5624}
5625
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005626void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005627 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005628 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005629}
5630
Prabir Pradhancef936d2021-07-21 16:17:52 +00005631void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5632 const sp<Connection>& connection, uint32_t seq,
5633 bool handled, nsecs_t consumeTime) {
5634 // Handle post-event policy actions.
5635 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5636 if (dispatchEntryIt == connection->waitQueue.end()) {
5637 return;
5638 }
5639 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5640 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5641 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5642 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5643 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5644 }
5645 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5646 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5647 connection->inputChannel->getConnectionToken(),
5648 dispatchEntry->deliveryTime, consumeTime, finishTime);
5649 }
5650
5651 bool restartEvent;
5652 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5653 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5654 restartEvent =
5655 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5656 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5657 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5658 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5659 handled);
5660 } else {
5661 restartEvent = false;
5662 }
5663
5664 // Dequeue the event and start the next cycle.
5665 // Because the lock might have been released, it is possible that the
5666 // contents of the wait queue to have been drained, so we need to double-check
5667 // a few things.
5668 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5669 if (dispatchEntryIt != connection->waitQueue.end()) {
5670 dispatchEntry = *dispatchEntryIt;
5671 connection->waitQueue.erase(dispatchEntryIt);
5672 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5673 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5674 if (!connection->responsive) {
5675 connection->responsive = isConnectionResponsive(*connection);
5676 if (connection->responsive) {
5677 // The connection was unresponsive, and now it's responsive.
5678 processConnectionResponsiveLocked(*connection);
5679 }
5680 }
5681 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005682 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005683 connection->outboundQueue.push_front(dispatchEntry);
5684 traceOutboundQueueLength(*connection);
5685 } else {
5686 releaseDispatchEntry(dispatchEntry);
5687 }
5688 }
5689
5690 // Start the next dispatch cycle for this connection.
5691 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692}
5693
Prabir Pradhancef936d2021-07-21 16:17:52 +00005694void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5695 const sp<IBinder>& newToken) {
5696 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5697 scoped_unlock unlock(mLock);
5698 mPolicy->notifyFocusChanged(oldToken, newToken);
5699 };
5700 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701}
5702
Prabir Pradhancef936d2021-07-21 16:17:52 +00005703void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5704 auto command = [this, token, x, y]() REQUIRES(mLock) {
5705 scoped_unlock unlock(mLock);
5706 mPolicy->notifyDropWindow(token, x, y);
5707 };
5708 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005709}
5710
Prabir Pradhancef936d2021-07-21 16:17:52 +00005711void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5712 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5713 scoped_unlock unlock(mLock);
5714 mPolicy->notifyUntrustedTouch(obscuringPackage);
5715 };
5716 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005717}
5718
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005719void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5720 if (connection == nullptr) {
5721 LOG_ALWAYS_FATAL("Caller must check for nullness");
5722 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005723 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5724 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005725 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005726 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005727 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005728 return;
5729 }
5730 /**
5731 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5732 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5733 * has changed. This could cause newer entries to time out before the already dispatched
5734 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5735 * processes the events linearly. So providing information about the oldest entry seems to be
5736 * most useful.
5737 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005738 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005739 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5740 std::string reason =
5741 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005742 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005743 ns2ms(currentWait),
5744 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005745 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005746 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005747
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005748 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5749
5750 // Stop waking up for events on this connection, it is already unresponsive
5751 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005752}
5753
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005754void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5755 std::string reason =
5756 StringPrintf("%s does not have a focused window", application->getName().c_str());
5757 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005758
Prabir Pradhancef936d2021-07-21 16:17:52 +00005759 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5760 scoped_unlock unlock(mLock);
5761 mPolicy->notifyNoFocusedWindowAnr(application);
5762 };
5763 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005764}
5765
chaviw98318de2021-05-19 16:45:23 -05005766void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005767 const std::string& reason) {
5768 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5769 updateLastAnrStateLocked(windowLabel, reason);
5770}
5771
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005772void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5773 const std::string& reason) {
5774 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005775 updateLastAnrStateLocked(windowLabel, reason);
5776}
5777
5778void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5779 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005781 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 struct tm tm;
5783 localtime_r(&t, &tm);
5784 char timestr[64];
5785 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005786 mLastAnrState.clear();
5787 mLastAnrState += INDENT "ANR:\n";
5788 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005789 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5790 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005791 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792}
5793
Prabir Pradhancef936d2021-07-21 16:17:52 +00005794void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5795 KeyEntry& entry) {
5796 const KeyEvent event = createKeyEvent(entry);
5797 nsecs_t delay = 0;
5798 { // release lock
5799 scoped_unlock unlock(mLock);
5800 android::base::Timer t;
5801 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5802 entry.policyFlags);
5803 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5804 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5805 std::to_string(t.duration().count()).c_str());
5806 }
5807 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808
5809 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005810 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005811 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005812 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005814 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5815 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817}
5818
Prabir Pradhancef936d2021-07-21 16:17:52 +00005819void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005820 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005821 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005822 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005823 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005824 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005825 };
5826 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005827}
5828
Prabir Pradhanedd96402022-02-15 01:46:16 -08005829void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5830 std::optional<int32_t> pid) {
5831 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005832 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005833 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005834 };
5835 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005836}
5837
5838/**
5839 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5840 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5841 * command entry to the command queue.
5842 */
5843void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5844 std::string reason) {
5845 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005846 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005847 if (connection.monitor) {
5848 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5849 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005850 pid = findMonitorPidByTokenLocked(connectionToken);
5851 } else {
5852 // The connection is a window
5853 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5854 reason.c_str());
5855 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5856 if (handle != nullptr) {
5857 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005858 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005859 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005860 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005861}
5862
5863/**
5864 * Tell the policy that a connection has become responsive so that it can stop ANR.
5865 */
5866void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5867 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005868 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005869 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005870 pid = findMonitorPidByTokenLocked(connectionToken);
5871 } else {
5872 // The connection is a window
5873 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5874 if (handle != nullptr) {
5875 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005876 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005877 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005878 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005879}
5880
Prabir Pradhancef936d2021-07-21 16:17:52 +00005881bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005882 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005883 KeyEntry& keyEntry, bool handled) {
5884 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005885 if (!handled) {
5886 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005887 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005888 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889 return false;
5890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005892 // Get the fallback key state.
5893 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005894 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005895 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005896 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897 connection->inputState.removeFallbackKey(originalKeyCode);
5898 }
5899
5900 if (handled || !dispatchEntry->hasForegroundTarget()) {
5901 // If the application handles the original key for which we previously
5902 // generated a fallback or if the window is not a foreground window,
5903 // then cancel the associated fallback key, if any.
5904 if (fallbackKeyCode != -1) {
5905 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005906 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5907 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5908 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5909 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5910 keyEntry.policyFlags);
5911 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005912 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914
5915 mLock.unlock();
5916
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005917 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919
5920 mLock.lock();
5921
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922 // Cancel the fallback key.
5923 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925 "application handled the original non-fallback key "
5926 "or is no longer a foreground target, "
5927 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928 options.keyCode = fallbackKeyCode;
5929 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005931 connection->inputState.removeFallbackKey(originalKeyCode);
5932 }
5933 } else {
5934 // If the application did not handle a non-fallback key, first check
5935 // that we are in a good state to perform unhandled key event processing
5936 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005937 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005938 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005939 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5940 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5941 "since this is not an initial down. "
5942 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5943 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5944 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005945 return false;
5946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005949 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5950 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5951 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5952 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5953 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005954 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955
5956 mLock.unlock();
5957
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005958 bool fallback =
5959 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005960 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961
5962 mLock.lock();
5963
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005964 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005965 connection->inputState.removeFallbackKey(originalKeyCode);
5966 return false;
5967 }
5968
5969 // Latch the fallback keycode for this key on an initial down.
5970 // The fallback keycode cannot change at any other point in the lifecycle.
5971 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 fallbackKeyCode = event.getKeyCode();
5974 } else {
5975 fallbackKeyCode = AKEYCODE_UNKNOWN;
5976 }
5977 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5978 }
5979
5980 ALOG_ASSERT(fallbackKeyCode != -1);
5981
5982 // Cancel the fallback key if the policy decides not to send it anymore.
5983 // We will continue to dispatch the key to the policy but we will no
5984 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005985 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5986 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005987 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5988 if (fallback) {
5989 ALOGD("Unhandled key event: Policy requested to send key %d"
5990 "as a fallback for %d, but on the DOWN it had requested "
5991 "to send %d instead. Fallback canceled.",
5992 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
5993 } else {
5994 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
5995 "but on the DOWN it had requested to send %d. "
5996 "Fallback canceled.",
5997 originalKeyCode, fallbackKeyCode);
5998 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005999 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006000
6001 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6002 "canceling fallback, policy no longer desires it");
6003 options.keyCode = fallbackKeyCode;
6004 synthesizeCancelationEventsForConnectionLocked(connection, options);
6005
6006 fallback = false;
6007 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006008 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006009 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 }
6011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006013 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6014 {
6015 std::string msg;
6016 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6017 connection->inputState.getFallbackKeys();
6018 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6019 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6020 }
6021 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6022 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006023 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006024 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006025
6026 if (fallback) {
6027 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006028 keyEntry.eventTime = event.getEventTime();
6029 keyEntry.deviceId = event.getDeviceId();
6030 keyEntry.source = event.getSource();
6031 keyEntry.displayId = event.getDisplayId();
6032 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6033 keyEntry.keyCode = fallbackKeyCode;
6034 keyEntry.scanCode = event.getScanCode();
6035 keyEntry.metaState = event.getMetaState();
6036 keyEntry.repeatCount = event.getRepeatCount();
6037 keyEntry.downTime = event.getDownTime();
6038 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006040 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6041 ALOGD("Unhandled key event: Dispatching fallback key. "
6042 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6043 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6044 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045 return true; // restart the event
6046 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006047 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6048 ALOGD("Unhandled key event: No fallback key.");
6049 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006050
6051 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
6054 }
6055 return false;
6056}
6057
Prabir Pradhancef936d2021-07-21 16:17:52 +00006058bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006059 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006060 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 return false;
6062}
6063
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064void InputDispatcher::traceInboundQueueLengthLocked() {
6065 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006066 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006067 }
6068}
6069
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006070void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 if (ATRACE_ENABLED()) {
6072 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006073 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6074 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 }
6076}
6077
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006078void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 if (ATRACE_ENABLED()) {
6080 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006081 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6082 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 }
6084}
6085
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006086void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006087 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006089 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 dumpDispatchStateLocked(dump);
6091
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006092 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006093 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006094 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 }
6096}
6097
6098void InputDispatcher::monitor() {
6099 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006100 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006102 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103}
6104
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006105/**
6106 * Wake up the dispatcher and wait until it processes all events and commands.
6107 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6108 * this method can be safely called from any thread, as long as you've ensured that
6109 * the work you are interested in completing has already been queued.
6110 */
6111bool InputDispatcher::waitForIdle() {
6112 /**
6113 * Timeout should represent the longest possible time that a device might spend processing
6114 * events and commands.
6115 */
6116 constexpr std::chrono::duration TIMEOUT = 100ms;
6117 std::unique_lock lock(mLock);
6118 mLooper->wake();
6119 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6120 return result == std::cv_status::no_timeout;
6121}
6122
Vishnu Naire798b472020-07-23 13:52:21 -07006123/**
6124 * Sets focus to the window identified by the token. This must be called
6125 * after updating any input window handles.
6126 *
6127 * Params:
6128 * request.token - input channel token used to identify the window that should gain focus.
6129 * request.focusedToken - the token that the caller expects currently to be focused. If the
6130 * specified token does not match the currently focused window, this request will be dropped.
6131 * If the specified focused token matches the currently focused window, the call will succeed.
6132 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6133 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6134 * when requesting the focus change. This determines which request gets
6135 * precedence if there is a focus change request from another source such as pointer down.
6136 */
Vishnu Nair958da932020-08-21 17:12:37 -07006137void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6138 { // acquire lock
6139 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006140 std::optional<FocusResolver::FocusChanges> changes =
6141 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6142 if (changes) {
6143 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006144 }
6145 } // release lock
6146 // Wake up poll loop since it may need to make new input dispatching choices.
6147 mLooper->wake();
6148}
6149
Vishnu Nairc519ff72021-01-21 08:23:08 -08006150void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6151 if (changes.oldFocus) {
6152 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006153 if (focusedInputChannel) {
6154 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6155 "focus left window");
6156 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006157 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006158 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006159 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006160 if (changes.newFocus) {
6161 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006162 }
6163
Prabir Pradhan99987712020-11-10 18:43:05 -08006164 // If a window has pointer capture, then it must have focus. We need to ensure that this
6165 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6166 // If the window loses focus before it loses pointer capture, then the window can be in a state
6167 // where it has pointer capture but not focus, violating the contract. Therefore we must
6168 // dispatch the pointer capture event before the focus event. Since focus events are added to
6169 // the front of the queue (above), we add the pointer capture event to the front of the queue
6170 // after the focus events are added. This ensures the pointer capture event ends up at the
6171 // front.
6172 disablePointerCaptureForcedLocked();
6173
Vishnu Nairc519ff72021-01-21 08:23:08 -08006174 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006175 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006176 }
6177}
Vishnu Nair958da932020-08-21 17:12:37 -07006178
Prabir Pradhan99987712020-11-10 18:43:05 -08006179void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006180 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006181 return;
6182 }
6183
6184 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6185
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006186 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006187 setPointerCaptureLocked(false);
6188 }
6189
6190 if (!mWindowTokenWithPointerCapture) {
6191 // No need to send capture changes because no window has capture.
6192 return;
6193 }
6194
6195 if (mPendingEvent != nullptr) {
6196 // Move the pending event to the front of the queue. This will give the chance
6197 // for the pending event to be dropped if it is a captured event.
6198 mInboundQueue.push_front(mPendingEvent);
6199 mPendingEvent = nullptr;
6200 }
6201
6202 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006203 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006204 mInboundQueue.push_front(std::move(entry));
6205}
6206
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006207void InputDispatcher::setPointerCaptureLocked(bool enable) {
6208 mCurrentPointerCaptureRequest.enable = enable;
6209 mCurrentPointerCaptureRequest.seq++;
6210 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006211 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006212 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006213 };
6214 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006215}
6216
Vishnu Nair599f1412021-06-21 10:39:58 -07006217void InputDispatcher::displayRemoved(int32_t displayId) {
6218 { // acquire lock
6219 std::scoped_lock _l(mLock);
6220 // Set an empty list to remove all handles from the specific display.
6221 setInputWindowsLocked(/* window handles */ {}, displayId);
6222 setFocusedApplicationLocked(displayId, nullptr);
6223 // Call focus resolver to clean up stale requests. This must be called after input windows
6224 // have been removed for the removed display.
6225 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006226 // Reset pointer capture eligibility, regardless of previous state.
6227 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006228 } // release lock
6229
6230 // Wake up poll loop since it may need to make new input dispatching choices.
6231 mLooper->wake();
6232}
6233
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006234void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6235 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006236 // The listener sends the windows as a flattened array. Separate the windows by display for
6237 // more convenient parsing.
6238 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006239 for (const auto& info : windowInfos) {
6240 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6241 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6242 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006243
6244 { // acquire lock
6245 std::scoped_lock _l(mLock);
6246 mDisplayInfos.clear();
6247 for (const auto& displayInfo : displayInfos) {
6248 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6249 }
6250
6251 for (const auto& [displayId, handles] : handlesPerDisplay) {
6252 setInputWindowsLocked(handles, displayId);
6253 }
6254 }
6255 // Wake up poll loop since it may need to make new input dispatching choices.
6256 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006257}
6258
Vishnu Nair062a8672021-09-03 16:07:44 -07006259bool InputDispatcher::shouldDropInput(
6260 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6261 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6262 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6263 isWindowObscuredLocked(windowHandle))) {
6264 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6265 "%" PRId32 ".",
6266 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6267 windowHandle->getInfo()->inputFeatures.string().c_str(),
6268 windowHandle->getInfo()->displayId);
6269 return true;
6270 }
6271 return false;
6272}
6273
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006274void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6275 const std::vector<gui::WindowInfo>& windowInfos,
6276 const std::vector<DisplayInfo>& displayInfos) {
6277 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6278}
6279
Arthur Hungdfd528e2021-12-08 13:23:04 +00006280void InputDispatcher::cancelCurrentTouch() {
6281 {
6282 std::scoped_lock _l(mLock);
6283 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6284 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6285 "cancel current touch");
6286 synthesizeCancelationEventsForAllConnectionsLocked(options);
6287
6288 mTouchStatesByDisplay.clear();
6289 mLastHoverWindowHandle.clear();
6290 }
6291 // Wake up poll loop since there might be work to do.
6292 mLooper->wake();
6293}
6294
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006295void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6296 std::scoped_lock _l(mLock);
6297 mMonitorDispatchingTimeout = timeout;
6298}
6299
Garfield Tane84e6f92019-08-29 17:28:41 -07006300} // namespace android::inputdispatcher