blob: 00a3bb05cb67cc0e193a38c9f381c008eb83e37a [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>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100027#include <binder/IServiceManager.h>
28#include <com/android/internal/compat/IPlatformCompatNative.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080031#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000033#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010035#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
Michael Wright44753b12020-07-08 13:48:11 +010038#include <cerrno>
39#include <cinttypes>
40#include <climits>
41#include <cstddef>
42#include <ctime>
43#include <queue>
44#include <sstream>
45
46#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070047#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#define INDENT " "
50#define INDENT2 " "
51#define INDENT3 " "
52#define INDENT4 " "
53
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080054using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000055using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070057using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050058using android::gui::FocusRequest;
59using android::gui::TouchOcclusionMode;
60using android::gui::WindowInfo;
61using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100063using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080064using android::os::InputEventInjectionResult;
65using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100066using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067
Garfield Tane84e6f92019-08-29 17:28:41 -070068namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
Prabir Pradhancef936d2021-07-21 16:17:52 +000070namespace {
71
Prabir Pradhan61a5d242021-07-26 16:41:09 +000072// Log detailed debug messages about each inbound event notification to the dispatcher.
73constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
74
75// Log detailed debug messages about each outbound event processed by the dispatcher.
76constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
77
78// Log debug messages about the dispatch cycle.
79constexpr bool DEBUG_DISPATCH_CYCLE = false;
80
81// Log debug messages about channel creation
82constexpr bool DEBUG_CHANNEL_CREATION = false;
83
84// Log debug messages about input event injection.
85constexpr bool DEBUG_INJECTION = false;
86
87// Log debug messages about input focus tracking.
88constexpr bool DEBUG_FOCUS = false;
89
Antonio Kantekf16f2832021-09-28 04:39:20 +000090// Log debug messages about touch mode event
91constexpr bool DEBUG_TOUCH_MODE = false;
92
Prabir Pradhan61a5d242021-07-26 16:41:09 +000093// Log debug messages about touch occlusion
94// STOPSHIP(b/169067926): Set to false
95constexpr bool DEBUG_TOUCH_OCCLUSION = true;
96
97// Log debug messages about the app switch latency optimization.
98constexpr bool DEBUG_APP_SWITCH = false;
99
100// Log debug messages about hover events.
101constexpr bool DEBUG_HOVER = false;
102
Prabir Pradhancef936d2021-07-21 16:17:52 +0000103// Temporarily releases a held mutex for the lifetime of the instance.
104// Named to match std::scoped_lock
105class scoped_unlock {
106public:
107 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
108 ~scoped_unlock() { mMutex.lock(); }
109
110private:
111 std::mutex& mMutex;
112};
113
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114// Default input dispatching timeout if there is no focused application or paused window
115// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800116const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
117 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
118 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119
120// Amount of time to allow for all pending events to be processed when an app switch
121// key is on the way. This is used to preempt input dispatch and drop input events
122// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000123constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124
125// Amount of time to allow for an event to be dispatched (measured since its eventTime)
126// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000127constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// 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 +0000130constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
131
132// Log a warning when an interception call takes longer than this to process.
133constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700135// Additional key latency in case a connection is still processing some motion events.
136// This will help with the case when a user touched a button that opens a new window,
137// and gives us the chance to dispatch the key to this new window.
138constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
139
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000141constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
142
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000143// Event log tags. See EventLogTags.logtags for reference
144constexpr int LOGTAG_INPUT_INTERACTION = 62000;
145constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000146constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000147
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000148inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 return systemTime(SYSTEM_TIME_MONOTONIC);
150}
151
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000152inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153 return value ? "true" : "false";
154}
155
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000156inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000157 if (binder == nullptr) {
158 return "<null>";
159 }
160 return StringPrintf("%p", binder.get());
161}
162
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000163inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
165 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166}
167
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000168bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 case AKEY_EVENT_ACTION_DOWN:
171 case AKEY_EVENT_ACTION_UP:
172 return true;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000178bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700179 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 ALOGE("Key event has invalid action code 0x%x", action);
181 return false;
182 }
183 return true;
184}
185
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000186bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700188 case AMOTION_EVENT_ACTION_DOWN:
189 case AMOTION_EVENT_ACTION_UP:
190 case AMOTION_EVENT_ACTION_CANCEL:
191 case AMOTION_EVENT_ACTION_MOVE:
192 case AMOTION_EVENT_ACTION_OUTSIDE:
193 case AMOTION_EVENT_ACTION_HOVER_ENTER:
194 case AMOTION_EVENT_ACTION_HOVER_MOVE:
195 case AMOTION_EVENT_ACTION_HOVER_EXIT:
196 case AMOTION_EVENT_ACTION_SCROLL:
197 return true;
198 case AMOTION_EVENT_ACTION_POINTER_DOWN:
199 case AMOTION_EVENT_ACTION_POINTER_UP: {
200 int32_t index = getMotionEventActionPointerIndex(action);
201 return index >= 0 && index < pointerCount;
202 }
203 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
204 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
205 return actionButton != 0;
206 default:
207 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 }
209}
210
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000211int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500212 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
213}
214
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000215bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
216 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700217 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 ALOGE("Motion event has invalid action code 0x%x", action);
219 return false;
220 }
221 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000222 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700223 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 return false;
225 }
226 BitSet32 pointerIdBits;
227 for (size_t i = 0; i < pointerCount; i++) {
228 int32_t id = pointerProperties[i].id;
229 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700230 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
231 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 return false;
233 }
234 if (pointerIdBits.hasBit(id)) {
235 ALOGE("Motion event has duplicate pointer id %d", id);
236 return false;
237 }
238 pointerIdBits.markBit(id);
239 }
240 return true;
241}
242
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000243std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000245 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 }
247
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000248 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 bool first = true;
250 Region::const_iterator cur = region.begin();
251 Region::const_iterator const tail = region.end();
252 while (cur != tail) {
253 if (first) {
254 first = false;
255 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800256 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800258 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 cur++;
260 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000261 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262}
263
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000264std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500265 constexpr size_t maxEntries = 50; // max events to print
266 constexpr size_t skipBegin = maxEntries / 2;
267 const size_t skipEnd = queue.size() - maxEntries / 2;
268 // skip from maxEntries / 2 ... size() - maxEntries/2
269 // only print from 0 .. skipBegin and then from skipEnd .. size()
270
271 std::string dump;
272 for (size_t i = 0; i < queue.size(); i++) {
273 const DispatchEntry& entry = *queue[i];
274 if (i >= skipBegin && i < skipEnd) {
275 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
276 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
277 continue;
278 }
279 dump.append(INDENT4);
280 dump += entry.eventEntry->getDescription();
281 dump += StringPrintf(", seq=%" PRIu32
282 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
283 entry.seq, entry.targetFlags, entry.resolvedAction,
284 ns2ms(currentTime - entry.eventEntry->eventTime));
285 if (entry.deliveryTime != 0) {
286 // This entry was delivered, so add information on how long we've been waiting
287 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
288 }
289 dump.append("\n");
290 }
291 return dump;
292}
293
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700294/**
295 * Find the entry in std::unordered_map by key, and return it.
296 * If the entry is not found, return a default constructed entry.
297 *
298 * Useful when the entries are vectors, since an empty vector will be returned
299 * if the entry is not found.
300 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
301 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700302template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000303V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700304 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700305 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800306}
307
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000308bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700309 if (first == second) {
310 return true;
311 }
312
313 if (first == nullptr || second == nullptr) {
314 return false;
315 }
316
317 return first->getToken() == second->getToken();
318}
319
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000320bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000321 if (first == nullptr || second == nullptr) {
322 return false;
323 }
324 return first->applicationInfo.token != nullptr &&
325 first->applicationInfo.token == second->applicationInfo.token;
326}
327
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000328bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800329 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
330}
331
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000332std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
333 std::shared_ptr<EventEntry> eventEntry,
334 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 if (inputTarget.useDefaultPointerTransform()) {
336 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700337 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700338 inputTarget.displayTransform,
339 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000340 }
341
342 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
343 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700345 std::vector<PointerCoords> pointerCoords;
346 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000347
348 // Use the first pointer information to normalize all other pointers. This could be any pointer
349 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700350 // uses the transform for the normalized pointer.
351 const ui::Transform& firstPointerTransform =
352 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
353 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000354
355 // Iterate through all pointers in the event to normalize against the first.
356 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
357 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
358 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700359 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360
361 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700362 // First, apply the current pointer's transform to update the coordinates into
363 // window space.
364 pointerCoords[pointerIndex].transform(currTransform);
365 // Next, apply the inverse transform of the normalized coordinates so the
366 // current coordinates are transformed into the normalized coordinate space.
367 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368 }
369
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700370 std::unique_ptr<MotionEntry> combinedMotionEntry =
371 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
372 motionEntry.deviceId, motionEntry.source,
373 motionEntry.displayId, motionEntry.policyFlags,
374 motionEntry.action, motionEntry.actionButton,
375 motionEntry.flags, motionEntry.metaState,
376 motionEntry.buttonState, motionEntry.classification,
377 motionEntry.edgeFlags, motionEntry.xPrecision,
378 motionEntry.yPrecision, motionEntry.xCursorPosition,
379 motionEntry.yCursorPosition, motionEntry.downTime,
380 motionEntry.pointerCount, motionEntry.pointerProperties,
Alex Chauf7c99f32021-12-03 10:37:54 +0000381 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382
383 if (motionEntry.injectionState) {
384 combinedMotionEntry->injectionState = motionEntry.injectionState;
385 combinedMotionEntry->injectionState->refCount += 1;
386 }
387
388 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700389 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700390 firstPointerTransform, inputTarget.displayTransform,
391 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000392 return dispatchEntry;
393}
394
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000395status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
396 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700397 std::unique_ptr<InputChannel> uniqueServerChannel;
398 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
399
400 serverChannel = std::move(uniqueServerChannel);
401 return result;
402}
403
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500404template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000405bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500406 if (lhs == nullptr && rhs == nullptr) {
407 return true;
408 }
409 if (lhs == nullptr || rhs == nullptr) {
410 return false;
411 }
412 return *lhs == *rhs;
413}
414
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000415sp<IPlatformCompatNative> getCompatService() {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000416 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
417 if (service == nullptr) {
418 ALOGE("Failed to link to compat service");
419 return nullptr;
420 }
421 return interface_cast<IPlatformCompatNative>(service);
422}
423
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000424KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000425 KeyEvent event;
426 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
427 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
428 entry.repeatCount, entry.downTime, entry.eventTime);
429 return event;
430}
431
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000432std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000433 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
434 const sp<IBinder>& token) {
435 for (const auto& it : monitorsByDisplay) {
436 const std::vector<Monitor>& monitors = it.second;
437 for (const Monitor& monitor : monitors) {
438 if (monitor.inputChannel->getConnectionToken() == token) {
439 return monitor.pid;
440 }
441 }
442 }
443 return std::nullopt;
444}
445
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000446bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000447 // Do not keep track of gesture monitors. They receive every event and would disproportionately
448 // affect the statistics.
449 if (connection.monitor) {
450 return false;
451 }
452 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
453 if (!connection.responsive) {
454 return false;
455 }
456 return true;
457}
458
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000459bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000460 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
461 const int32_t& inputEventId = eventEntry.id;
462 if (inputEventId != dispatchEntry.resolvedEventId) {
463 // Event was transmuted
464 return false;
465 }
466 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
467 return false;
468 }
469 // Only track latency for events that originated from hardware
470 if (eventEntry.isSynthesized()) {
471 return false;
472 }
473 const EventEntry::Type& inputEventEntryType = eventEntry.type;
474 if (inputEventEntryType == EventEntry::Type::KEY) {
475 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
476 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
477 return false;
478 }
479 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
480 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
481 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
482 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
483 return false;
484 }
485 } else {
486 // Not a key or a motion
487 return false;
488 }
489 if (!shouldReportMetricsForConnection(connection)) {
490 return false;
491 }
492 return true;
493}
494
Prabir Pradhancef936d2021-07-21 16:17:52 +0000495/**
496 * Connection is responsive if it has no events in the waitQueue that are older than the
497 * current time.
498 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000499bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000500 const nsecs_t currentTime = now();
501 for (const DispatchEntry* entry : connection.waitQueue) {
502 if (entry->timeoutTime < currentTime) {
503 return false;
504 }
505 }
506 return true;
507}
508
Alex Chau663fc832021-12-03 10:37:54 +0000509vec2 transformWithoutTranslation(const ui::Transform& transform, float x, float y) {
510 const vec2 transformedXy = transform.transform(x, y);
511 const vec2 transformedOrigin = transform.transform(0, 0);
512 return transformedXy - transformedOrigin;
513}
514
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515// Returns true if the event type passed as argument represents a user activity.
516bool isUserActivityEvent(const EventEntry& eventEntry) {
517 switch (eventEntry.type) {
518 case EventEntry::Type::FOCUS:
519 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
520 case EventEntry::Type::DRAG:
521 case EventEntry::Type::TOUCH_MODE_CHANGED:
522 case EventEntry::Type::SENSOR:
523 case EventEntry::Type::CONFIGURATION_CHANGED:
524 return false;
525 case EventEntry::Type::DEVICE_RESET:
526 case EventEntry::Type::KEY:
527 case EventEntry::Type::MOTION:
528 return true;
529 }
530}
531
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800532// Returns true if the given window can accept pointer events at the given display location.
533bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y) {
534 if (windowInfo.displayId != displayId || !windowInfo.visible) {
535 return false;
536 }
537 const auto flags = windowInfo.flags;
538 if (flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
539 return false;
540 }
541 const bool isModalWindow = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
542 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
543 if (!isModalWindow && !windowInfo.touchableRegionContainsPoint(x, y)) {
544 return false;
545 }
546 return true;
547}
548
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000549} // namespace
550
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551// --- InputDispatcher ---
552
Garfield Tan00f511d2019-06-12 16:55:40 -0700553InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
554 : mPolicy(policy),
555 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700556 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800557 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700558 mAppSwitchSawKeyDown(false),
559 mAppSwitchDueTime(LONG_LONG_MAX),
560 mNextUnblockedEvent(nullptr),
561 mDispatchEnabled(false),
562 mDispatchFrozen(false),
563 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800564 // mInTouchMode will be initialized by the WindowManager to the default device config.
565 // To avoid leaking stack in case that call never comes, and for tests,
566 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000567 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100568 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000569 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800570 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000571 mLatencyAggregator(),
572 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000573 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800575 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700577 mWindowInfoListener = new DispatcherWindowListener(*this);
578 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
579
Yi Kong9b14ac62018-07-17 13:48:38 -0700580 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581
582 policy->getDispatcherConfiguration(&mConfig);
583}
584
585InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000586 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587
Prabir Pradhancef936d2021-07-21 16:17:52 +0000588 resetKeyRepeatLocked();
589 releasePendingEventLocked();
590 drainInboundQueueLocked();
591 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000593 while (!mConnectionsByToken.empty()) {
594 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000595 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
596 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597 }
598}
599
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700601 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700602 return ALREADY_EXISTS;
603 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700604 mThread = std::make_unique<InputThread>(
605 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
606 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700607}
608
609status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 if (mThread && mThread->isCallingThread()) {
611 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700612 return INVALID_OPERATION;
613 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700614 mThread.reset();
615 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700616}
617
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618void InputDispatcher::dispatchOnce() {
619 nsecs_t nextWakeupTime = LONG_LONG_MAX;
620 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800621 std::scoped_lock _l(mLock);
622 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623
624 // Run a dispatch loop if there are no pending commands.
625 // The dispatch loop might enqueue commands to run afterwards.
626 if (!haveCommandsLocked()) {
627 dispatchOnceInnerLocked(&nextWakeupTime);
628 }
629
630 // Run all pending commands if there are any.
631 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000632 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 nextWakeupTime = LONG_LONG_MIN;
634 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800635
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700636 // If we are still waiting for ack on some events,
637 // we might have to wake up earlier to check if an app is anr'ing.
638 const nsecs_t nextAnrCheck = processAnrsLocked();
639 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
640
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800641 // We are about to enter an infinitely long sleep, because we have no commands or
642 // pending or queued events
643 if (nextWakeupTime == LONG_LONG_MAX) {
644 mDispatcherEnteredIdle.notify_all();
645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 } // release lock
647
648 // Wait for callback or timeout or wake. (make sure we round up, not down)
649 nsecs_t currentTime = now();
650 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
651 mLooper->pollOnce(timeoutMillis);
652}
653
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700654/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500655 * Raise ANR if there is no focused window.
656 * Before the ANR is raised, do a final state check:
657 * 1. The currently focused application must be the same one we are waiting for.
658 * 2. Ensure we still don't have a focused window.
659 */
660void InputDispatcher::processNoFocusedWindowAnrLocked() {
661 // Check if the application that we are waiting for is still focused.
662 std::shared_ptr<InputApplicationHandle> focusedApplication =
663 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
664 if (focusedApplication == nullptr ||
665 focusedApplication->getApplicationToken() !=
666 mAwaitedFocusedApplication->getApplicationToken()) {
667 // Unexpected because we should have reset the ANR timer when focused application changed
668 ALOGE("Waited for a focused window, but focused application has already changed to %s",
669 focusedApplication->getName().c_str());
670 return; // The focused application has changed.
671 }
672
chaviw98318de2021-05-19 16:45:23 -0500673 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500674 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
675 if (focusedWindowHandle != nullptr) {
676 return; // We now have a focused window. No need for ANR.
677 }
678 onAnrLocked(mAwaitedFocusedApplication);
679}
680
681/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700682 * Check if any of the connections' wait queues have events that are too old.
683 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
684 * Return the time at which we should wake up next.
685 */
686nsecs_t InputDispatcher::processAnrsLocked() {
687 const nsecs_t currentTime = now();
688 nsecs_t nextAnrCheck = LONG_LONG_MAX;
689 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
690 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
691 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500692 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700693 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500694 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700695 return LONG_LONG_MIN;
696 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500697 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700698 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
699 }
700 }
701
702 // Check if any connection ANRs are due
703 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
704 if (currentTime < nextAnrCheck) { // most likely scenario
705 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
706 }
707
708 // If we reached here, we have an unresponsive connection.
709 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
710 if (connection == nullptr) {
711 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
712 return nextAnrCheck;
713 }
714 connection->responsive = false;
715 // Stop waking up for this unresponsive connection
716 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000717 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700718 return LONG_LONG_MIN;
719}
720
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500721std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500722 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700723 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500724 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700725 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500726 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700727}
728
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
730 nsecs_t currentTime = now();
731
Jeff Browndc5992e2014-04-11 01:27:26 -0700732 // Reset the key repeat timer whenever normal dispatch is suspended while the
733 // device is in a non-interactive state. This is to ensure that we abort a key
734 // repeat if the device is just coming out of sleep.
735 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 resetKeyRepeatLocked();
737 }
738
739 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
740 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100741 if (DEBUG_FOCUS) {
742 ALOGD("Dispatch frozen. Waiting some more.");
743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 return;
745 }
746
747 // Optimize latency of app switches.
748 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
749 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
750 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
751 if (mAppSwitchDueTime < *nextWakeupTime) {
752 *nextWakeupTime = mAppSwitchDueTime;
753 }
754
755 // Ready to start a new event.
756 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700757 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700758 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 if (isAppSwitchDue) {
760 // The inbound queue is empty so the app switch key we were waiting
761 // for will never arrive. Stop waiting for it.
762 resetPendingAppSwitchLocked(false);
763 isAppSwitchDue = false;
764 }
765
766 // Synthesize a key repeat if appropriate.
767 if (mKeyRepeatState.lastKeyEntry) {
768 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
769 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
770 } else {
771 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
772 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
773 }
774 }
775 }
776
777 // Nothing to do if there is no pending event.
778 if (!mPendingEvent) {
779 return;
780 }
781 } else {
782 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700783 mPendingEvent = mInboundQueue.front();
784 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 traceInboundQueueLengthLocked();
786 }
787
788 // Poke user activity for this event.
789 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700790 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 // Now we have an event to dispatch.
795 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700796 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700798 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
805 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700806 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 }
808
809 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700810 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700811 const ConfigurationChangedEntry& typedEntry =
812 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700814 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 break;
816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700818 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700819 const DeviceResetEntry& typedEntry =
820 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700822 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700823 break;
824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100826 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700827 std::shared_ptr<FocusEntry> typedEntry =
828 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100829 dispatchFocusLocked(currentTime, typedEntry);
830 done = true;
831 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
832 break;
833 }
834
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700835 case EventEntry::Type::TOUCH_MODE_CHANGED: {
836 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
837 dispatchTouchModeChangeLocked(currentTime, typedEntry);
838 done = true;
839 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
840 break;
841 }
842
Prabir Pradhan99987712020-11-10 18:43:05 -0800843 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
844 const auto typedEntry =
845 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
846 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
847 done = true;
848 break;
849 }
850
arthurhungb89ccb02020-12-30 16:19:01 +0800851 case EventEntry::Type::DRAG: {
852 std::shared_ptr<DragEntry> typedEntry =
853 std::static_pointer_cast<DragEntry>(mPendingEvent);
854 dispatchDragLocked(currentTime, typedEntry);
855 done = true;
856 break;
857 }
858
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700859 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700860 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700862 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 resetPendingAppSwitchLocked(true);
864 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 } else if (dropReason == DropReason::NOT_DROPPED) {
866 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 }
868 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700872 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
873 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700875 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 break;
877 }
878
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700879 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 std::shared_ptr<MotionEntry> motionEntry =
881 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
883 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700885 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700886 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700888 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
889 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700891 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700892 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
Chris Yef59a2f42020-10-16 12:55:26 -0700894
895 case EventEntry::Type::SENSOR: {
896 std::shared_ptr<SensorEntry> sensorEntry =
897 std::static_pointer_cast<SensorEntry>(mPendingEvent);
898 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
899 dropReason = DropReason::APP_SWITCH;
900 }
901 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
902 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
903 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
904 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
905 dropReason = DropReason::STALE;
906 }
907 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
908 done = true;
909 break;
910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912
913 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700914 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700915 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 }
Michael Wright3a981722015-06-10 15:26:13 +0100917 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918
919 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 }
922}
923
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924/**
925 * Return true if the events preceding this incoming motion event should be dropped
926 * Return false otherwise (the default behaviour)
927 */
928bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700930 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931
932 // Optimize case where the current application is unresponsive and the user
933 // decides to touch a window in a different application.
934 // If the application takes too long to catch up then we drop all events preceding
935 // the touch into the other window.
936 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 int32_t displayId = motionEntry.displayId;
938 int32_t x = static_cast<int32_t>(
939 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
940 int32_t y = static_cast<int32_t>(
941 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500942 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700943 findTouchedWindowAtLocked(displayId, x, y, nullptr);
944 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 touchedWindowHandle->getApplicationToken() !=
946 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700947 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948 ALOGI("Pruning input queue because user touched a different application while waiting "
949 "for %s",
950 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700951 return true;
952 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700953
954 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700955 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700956 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700957 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000958 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 // This monitor could take more input. Drop all events preceding this
960 // event, so that gesture monitor could get a chance to receive the stream
961 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
962 "responsive gesture monitor that may handle the event",
963 mAwaitedFocusedApplication->getName().c_str());
964 return true;
965 }
966 }
967 }
968
969 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
970 // yet been processed by some connections, the dispatcher will wait for these motion
971 // events to be processed before dispatching the key event. This is because these motion events
972 // may cause a new window to be launched, which the user might expect to receive focus.
973 // To prevent waiting forever for such events, just send the key to the currently focused window
974 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
975 ALOGD("Received a new pointer down event, stop waiting for events to process and "
976 "just send the pending key event to the focused window.");
977 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700978 }
979 return false;
980}
981
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700983 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984 mInboundQueue.push_back(std::move(newEntry));
985 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 traceInboundQueueLengthLocked();
987
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700988 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700989 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 // Optimize app switch latency.
991 // If the application takes too long to catch up then we drop all events preceding
992 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700993 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700995 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700996 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000999 if (DEBUG_APP_SWITCH) {
1000 ALOGD("App switch is pending!");
1001 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001002 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 mAppSwitchSawKeyDown = false;
1004 needWake = true;
1005 }
1006 }
1007 }
1008 break;
1009 }
1010
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001011 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001012 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1013 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001014 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001018 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001019 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1020 break;
1021 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001022 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001023 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001024 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001025 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001026 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1027 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001028 // nothing to do
1029 break;
1030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 }
1032
1033 return needWake;
1034}
1035
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001036void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001037 // Do not store sensor event in recent queue to avoid flooding the queue.
1038 if (entry->type != EventEntry::Type::SENSOR) {
1039 mRecentQueue.push_back(entry);
1040 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001041 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001042 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 }
1044}
1045
chaviw98318de2021-05-19 16:45:23 -05001046sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1047 int32_t y, TouchState* touchState,
1048 bool addOutsideTargets,
1049 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001050 if (addOutsideTargets && touchState == nullptr) {
1051 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001054 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001055 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001056 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001057 continue;
1058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001060 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001061 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001062 return windowHandle;
1063 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001064
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001065 if (addOutsideTargets && info.flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
1066 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1067 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071}
1072
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001073std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(int32_t displayId,
1074 int32_t x,
1075 int32_t y) const {
1076 // Traverse windows from front to back and gather the touched spy windows.
1077 std::vector<sp<WindowInfoHandle>> spyWindows;
1078 const auto& windowHandles = getWindowHandlesLocked(displayId);
1079 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1080 const WindowInfo& info = *windowHandle->getInfo();
1081
1082 if (!windowAcceptsTouchAt(info, displayId, x, y)) {
1083 continue;
1084 }
1085 if (!info.isSpy()) {
1086 // The first touched non-spy window was found, so return the spy windows touched so far.
1087 return spyWindows;
1088 }
1089 spyWindows.push_back(windowHandle);
1090 }
1091 return spyWindows;
1092}
1093
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001094void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 const char* reason;
1096 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001098 if (DEBUG_INBOUND_EVENT_DETAILS) {
1099 ALOGD("Dropped event because policy consumed it.");
1100 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 reason = "inbound event was dropped because the policy consumed it";
1102 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 case DropReason::DISABLED:
1104 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 ALOGI("Dropped event because input dispatch is disabled.");
1106 }
1107 reason = "inbound event was dropped because input dispatch is disabled";
1108 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 ALOGI("Dropped event because of pending overdue app switch.");
1111 reason = "inbound event was dropped because of pending overdue app switch";
1112 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 ALOGI("Dropped event because the current application is not responding and the user "
1115 "has started interacting with a different application.");
1116 reason = "inbound event was dropped because the current application is not responding "
1117 "and the user has started interacting with a different application";
1118 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001119 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 ALOGI("Dropped event because it is stale.");
1121 reason = "inbound event was dropped because it is stale";
1122 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001123 case DropReason::NO_POINTER_CAPTURE:
1124 ALOGI("Dropped event because there is no window with Pointer Capture.");
1125 reason = "inbound event was dropped because there is no window with Pointer Capture";
1126 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001127 case DropReason::NOT_DROPPED: {
1128 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
1132
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001133 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001134 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1136 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001139 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001140 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1141 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1143 synthesizeCancelationEventsForAllConnectionsLocked(options);
1144 } else {
1145 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1146 synthesizeCancelationEventsForAllConnectionsLocked(options);
1147 }
1148 break;
1149 }
Chris Yef59a2f42020-10-16 12:55:26 -07001150 case EventEntry::Type::SENSOR: {
1151 break;
1152 }
arthurhungb89ccb02020-12-30 16:19:01 +08001153 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1154 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001155 break;
1156 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001157 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001158 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001159 case EventEntry::Type::CONFIGURATION_CHANGED:
1160 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001161 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001162 break;
1163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 }
1165}
1166
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001167static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1169 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170}
1171
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001172bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1173 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1174 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1175 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
1178bool InputDispatcher::isAppSwitchPendingLocked() {
1179 return mAppSwitchDueTime != LONG_LONG_MAX;
1180}
1181
1182void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1183 mAppSwitchDueTime = LONG_LONG_MAX;
1184
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001185 if (DEBUG_APP_SWITCH) {
1186 if (handled) {
1187 ALOGD("App switch has arrived.");
1188 } else {
1189 ALOGD("App switch was abandoned.");
1190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001195 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196}
1197
Prabir Pradhancef936d2021-07-21 16:17:52 +00001198bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001199 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 return false;
1201 }
1202
1203 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001204 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001205 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001206 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1207 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001208 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 return true;
1210}
1211
Prabir Pradhancef936d2021-07-21 16:17:52 +00001212void InputDispatcher::postCommandLocked(Command&& command) {
1213 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214}
1215
1216void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001217 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001218 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001219 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 releaseInboundEventLocked(entry);
1221 }
1222 traceInboundQueueLengthLocked();
1223}
1224
1225void InputDispatcher::releasePendingEventLocked() {
1226 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001228 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230}
1231
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001232void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001234 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001235 if (DEBUG_DISPATCH_CYCLE) {
1236 ALOGD("Injected inbound event was dropped.");
1237 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001241 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 }
1243 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244}
1245
1246void InputDispatcher::resetKeyRepeatLocked() {
1247 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001248 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
1250}
1251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1253 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
Michael Wright2e732952014-09-24 13:26:59 -07001255 uint32_t policyFlags = entry->policyFlags &
1256 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001258 std::shared_ptr<KeyEntry> newEntry =
1259 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1260 entry->source, entry->displayId, policyFlags, entry->action,
1261 entry->flags, entry->keyCode, entry->scanCode,
1262 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264 newEntry->syntheticRepeat = true;
1265 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268}
1269
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001272 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1273 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275
1276 // Reset key repeating in case a keyboard device was added or removed or something.
1277 resetKeyRepeatLocked();
1278
1279 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001280 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1281 scoped_unlock unlock(mLock);
1282 mPolicy->notifyConfigurationChanged(eventTime);
1283 };
1284 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 return true;
1286}
1287
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001288bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1289 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001290 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1291 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1292 entry.deviceId);
1293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
liushenxiang42232912021-05-21 20:24:09 +08001295 // Reset key repeating in case a keyboard device was disabled or enabled.
1296 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1297 resetKeyRepeatLocked();
1298 }
1299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 synthesizeCancelationEventsForAllConnectionsLocked(options);
1303 return true;
1304}
1305
Vishnu Nairad321cd2020-08-20 16:40:21 -07001306void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001307 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001308 if (mPendingEvent != nullptr) {
1309 // Move the pending event to the front of the queue. This will give the chance
1310 // for the pending event to get dispatched to the newly focused window
1311 mInboundQueue.push_front(mPendingEvent);
1312 mPendingEvent = nullptr;
1313 }
1314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315 std::unique_ptr<FocusEntry> focusEntry =
1316 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1317 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001318
1319 // This event should go to the front of the queue, but behind all other focus events
1320 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001322 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001323 [](const std::shared_ptr<EventEntry>& event) {
1324 return event->type == EventEntry::Type::FOCUS;
1325 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001326
1327 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001328 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001329}
1330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001332 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001333 if (channel == nullptr) {
1334 return; // Window has gone away
1335 }
1336 InputTarget target;
1337 target.inputChannel = channel;
1338 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1339 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001340 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1341 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001342 std::string reason = std::string("reason=").append(entry->reason);
1343 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001344 dispatchEventLocked(currentTime, entry, {target});
1345}
1346
Prabir Pradhan99987712020-11-10 18:43:05 -08001347void InputDispatcher::dispatchPointerCaptureChangedLocked(
1348 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1349 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001350 dropReason = DropReason::NOT_DROPPED;
1351
Prabir Pradhan99987712020-11-10 18:43:05 -08001352 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001353 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001354
1355 if (entry->pointerCaptureRequest.enable) {
1356 // Enable Pointer Capture.
1357 if (haveWindowWithPointerCapture &&
1358 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1359 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1360 "to the window.");
1361 }
1362 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001363 // This can happen if a window requests capture and immediately releases capture.
1364 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001365 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001366 return;
1367 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001368 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1369 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1370 return;
1371 }
1372
Vishnu Nairc519ff72021-01-21 08:23:08 -08001373 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001374 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1375 mWindowTokenWithPointerCapture = token;
1376 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377 // Disable Pointer Capture.
1378 // We do not check if the sequence number matches for requests to disable Pointer Capture
1379 // for two reasons:
1380 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1381 // to disable capture with the same sequence number: one generated by
1382 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1383 // Capture being disabled in InputReader.
1384 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1385 // actual Pointer Capture state that affects events being generated by input devices is
1386 // in InputReader.
1387 if (!haveWindowWithPointerCapture) {
1388 // Pointer capture was already forcefully disabled because of focus change.
1389 dropReason = DropReason::NOT_DROPPED;
1390 return;
1391 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 token = mWindowTokenWithPointerCapture;
1393 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001394 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001395 setPointerCaptureLocked(false);
1396 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001397 }
1398
1399 auto channel = getInputChannelLocked(token);
1400 if (channel == nullptr) {
1401 // Window has gone away, clean up Pointer Capture state.
1402 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001403 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001404 setPointerCaptureLocked(false);
1405 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001406 return;
1407 }
1408 InputTarget target;
1409 target.inputChannel = channel;
1410 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1411 entry->dispatchInProgress = true;
1412 dispatchEventLocked(currentTime, entry, {target});
1413
1414 dropReason = DropReason::NOT_DROPPED;
1415}
1416
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001417void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1418 const std::shared_ptr<TouchModeEntry>& entry) {
1419 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1420 getWindowHandlesLocked(mFocusedDisplayId);
1421 if (windowHandles.empty()) {
1422 return;
1423 }
1424 const std::vector<InputTarget> inputTargets =
1425 getInputTargetsFromWindowHandlesLocked(windowHandles);
1426 if (inputTargets.empty()) {
1427 return;
1428 }
1429 entry->dispatchInProgress = true;
1430 dispatchEventLocked(currentTime, entry, inputTargets);
1431}
1432
1433std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1434 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1435 std::vector<InputTarget> inputTargets;
1436 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1437 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1438 const sp<IBinder>& token = handle->getToken();
1439 if (token == nullptr) {
1440 continue;
1441 }
1442 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1443 if (channel == nullptr) {
1444 continue; // Window has gone away
1445 }
1446 InputTarget target;
1447 target.inputChannel = channel;
1448 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1449 inputTargets.push_back(target);
1450 }
1451 return inputTargets;
1452}
1453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 if (!entry->dispatchInProgress) {
1458 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1459 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1460 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1461 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001462 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 // We have seen two identical key downs in a row which indicates that the device
1464 // driver is automatically generating key repeats itself. We take note of the
1465 // repeat here, but we disable our own next key repeat timer since it is clear that
1466 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001467 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1468 // Make sure we don't get key down from a different device. If a different
1469 // device Id has same key pressed down, the new device Id will replace the
1470 // current one to hold the key repeat with repeat count reset.
1471 // In the future when got a KEY_UP on the device id, drop it and do not
1472 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1474 resetKeyRepeatLocked();
1475 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1476 } else {
1477 // Not a repeat. Save key down state in case we do see a repeat later.
1478 resetKeyRepeatLocked();
1479 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1480 }
1481 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001482 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1483 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001484 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001485 if (DEBUG_INBOUND_EVENT_DETAILS) {
1486 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1487 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001488 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 resetKeyRepeatLocked();
1490 }
1491
1492 if (entry->repeatCount == 1) {
1493 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1494 } else {
1495 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1496 }
1497
1498 entry->dispatchInProgress = true;
1499
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001500 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502
1503 // Handle case where the policy asked us to try again later last time.
1504 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1505 if (currentTime < entry->interceptKeyWakeupTime) {
1506 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1507 *nextWakeupTime = entry->interceptKeyWakeupTime;
1508 }
1509 return false; // wait until next wakeup
1510 }
1511 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1512 entry->interceptKeyWakeupTime = 0;
1513 }
1514
1515 // Give the policy a chance to intercept the key.
1516 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1517 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001518 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001519 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001520
1521 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1522 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1523 };
1524 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 return false; // wait for the command to run
1526 } else {
1527 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1528 }
1529 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001530 if (*dropReason == DropReason::NOT_DROPPED) {
1531 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 }
1533 }
1534
1535 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001536 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001537 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001538 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1539 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001540 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 return true;
1542 }
1543
1544 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001545 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001546 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001547 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001548 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 return false;
1550 }
1551
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001552 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001553 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 return true;
1555 }
1556
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001557 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001558 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559
1560 // Dispatch the key.
1561 dispatchEventLocked(currentTime, entry, inputTargets);
1562 return true;
1563}
1564
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001566 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1567 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1568 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1569 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1570 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1571 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1572 entry.metaState, entry.repeatCount, entry.downTime);
1573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574}
1575
Prabir Pradhancef936d2021-07-21 16:17:52 +00001576void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1577 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001578 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001579 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1580 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1581 "source=0x%x, sensorType=%s",
1582 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001583 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001584 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001585 auto command = [this, entry]() REQUIRES(mLock) {
1586 scoped_unlock unlock(mLock);
1587
1588 if (entry->accuracyChanged) {
1589 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1590 }
1591 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1592 entry->hwTimestamp, entry->values);
1593 };
1594 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001595}
1596
1597bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001598 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1599 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001600 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001601 }
Chris Yef59a2f42020-10-16 12:55:26 -07001602 { // acquire lock
1603 std::scoped_lock _l(mLock);
1604
1605 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1606 std::shared_ptr<EventEntry> entry = *it;
1607 if (entry->type == EventEntry::Type::SENSOR) {
1608 it = mInboundQueue.erase(it);
1609 releaseInboundEventLocked(entry);
1610 }
1611 }
1612 }
1613 return true;
1614}
1615
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001616bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001617 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001618 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001620 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 entry->dispatchInProgress = true;
1622
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 }
1625
1626 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001627 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001628 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001629 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1630 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 return true;
1632 }
1633
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001634 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635
1636 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001637 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638
1639 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 if (isPointerEvent) {
1642 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001643 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001645 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 } else {
1647 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001651 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 return false;
1653 }
1654
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001655 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001656 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001657 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1658 return true;
1659 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001660 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001661 CancelationOptions::Mode mode(isPointerEvent
1662 ? CancelationOptions::CANCEL_POINTER_EVENTS
1663 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1664 CancelationOptions options(mode, "input event injection failed");
1665 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return true;
1667 }
1668
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001669 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671
1672 // Dispatch the motion.
1673 if (conflictingPointerActions) {
1674 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 synthesizeCancelationEventsForAllConnectionsLocked(options);
1677 }
1678 dispatchEventLocked(currentTime, entry, inputTargets);
1679 return true;
1680}
1681
chaviw98318de2021-05-19 16:45:23 -05001682void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001683 bool isExiting, const MotionEntry& motionEntry) {
1684 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1685 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1686 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1687 PointerCoords pointerCoords;
1688 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1689 pointerCoords.transform(windowHandle->getInfo()->transform);
1690
1691 std::unique_ptr<DragEntry> dragEntry =
1692 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1693 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1694 pointerCoords.getY());
1695
1696 enqueueInboundEventLocked(std::move(dragEntry));
1697}
1698
1699void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1700 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1701 if (channel == nullptr) {
1702 return; // Window has gone away
1703 }
1704 InputTarget target;
1705 target.inputChannel = channel;
1706 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1707 entry->dispatchInProgress = true;
1708 dispatchEventLocked(currentTime, entry, {target});
1709}
1710
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001711void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001712 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1713 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1714 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001715 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001716 "metaState=0x%x, buttonState=0x%x,"
1717 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1718 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001719 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1720 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1721 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001723 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1724 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1725 "x=%f, y=%f, pressure=%f, size=%f, "
1726 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1727 "orientation=%f",
1728 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1729 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1730 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1731 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1732 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1733 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1734 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1735 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1736 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1737 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740}
1741
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001742void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1743 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001744 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001745 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001746 if (DEBUG_DISPATCH_CYCLE) {
1747 ALOGD("dispatchEventToCurrentInputTargets");
1748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001750 updateInteractionTokensLocked(*eventEntry, inputTargets);
1751
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001756 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001757 sp<Connection> connection =
1758 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001759 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001760 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001762 if (DEBUG_FOCUS) {
1763 ALOGD("Dropping event delivery to target with channel '%s' because it "
1764 "is no longer registered with the input dispatcher.",
1765 inputTarget.inputChannel->getName().c_str());
1766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768 }
1769}
1770
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001771void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1772 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1773 // If the policy decides to close the app, we will get a channel removal event via
1774 // unregisterInputChannel, and will clean up the connection that way. We are already not
1775 // sending new pointers to the connection when it blocked, but focused events will continue to
1776 // pile up.
1777 ALOGW("Canceling events for %s because it is unresponsive",
1778 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001779 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001780 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1781 "application not responding");
1782 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 }
1784}
1785
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001787 if (DEBUG_FOCUS) {
1788 ALOGD("Resetting ANR timeouts.");
1789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790
1791 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001792 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001793 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794}
1795
Tiger Huang721e26f2018-07-24 22:26:19 +08001796/**
1797 * Get the display id that the given event should go to. If this event specifies a valid display id,
1798 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1799 * Focused display is the display that the user most recently interacted with.
1800 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001801int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001802 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001803 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001804 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001805 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1806 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001807 break;
1808 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001809 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001810 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1811 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001812 break;
1813 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001814 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001815 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001816 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001817 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001818 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001819 case EventEntry::Type::SENSOR:
1820 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001821 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 return ADISPLAY_ID_NONE;
1823 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001824 }
1825 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1826}
1827
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1829 const char* focusedWindowName) {
1830 if (mAnrTracker.empty()) {
1831 // already processed all events that we waited for
1832 mKeyIsWaitingForEventsTimeout = std::nullopt;
1833 return false;
1834 }
1835
1836 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1837 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001838 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001839 mKeyIsWaitingForEventsTimeout = currentTime +
1840 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1841 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001842 return true;
1843 }
1844
1845 // We still have pending events, and already started the timer
1846 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1847 return true; // Still waiting
1848 }
1849
1850 // Waited too long, and some connection still hasn't processed all motions
1851 // Just send the key to the focused window
1852 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1853 focusedWindowName);
1854 mKeyIsWaitingForEventsTimeout = std::nullopt;
1855 return false;
1856}
1857
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001858InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1859 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1860 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001861 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Tiger Huang721e26f2018-07-24 22:26:19 +08001863 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001864 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001865 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001866 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1867
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 // If there is no currently focused window and no focused application
1869 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001870 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1871 ALOGI("Dropping %s event because there is no focused window or focused application in "
1872 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001873 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876
Vishnu Nair062a8672021-09-03 16:07:44 -07001877 // Drop key events if requested by input feature
1878 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1879 return InputEventInjectionResult::FAILED;
1880 }
1881
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1883 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1884 // start interacting with another application via touch (app switch). This code can be removed
1885 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1886 // an app is expected to have a focused window.
1887 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1888 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1889 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001890 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1891 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1892 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001894 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001895 ALOGW("Waiting because no window has focus but %s may eventually add a "
1896 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001897 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001900 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1901 // Already raised ANR. Drop the event
1902 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001903 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001905 } else {
1906 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 }
1909 }
1910
1911 // we have a valid, non-null focused window
1912 resetNoFocusedWindowTimeoutLocked();
1913
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001915 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 }
1918
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001919 if (focusedWindowHandle->getInfo()->paused) {
1920 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001922 }
1923
1924 // If the event is a key event, then we must wait for all previous events to
1925 // complete before delivering it because previous events may have the
1926 // side-effect of transferring focus to a different window and we want to
1927 // ensure that the following keys are sent to the new window.
1928 //
1929 // Suppose the user touches a button in a window then immediately presses "A".
1930 // If the button causes a pop-up window to appear then we want to ensure that
1931 // the "A" key is delivered to the new pop-up window. This is because users
1932 // often anticipate pending UI changes when typing on a keyboard.
1933 // To obtain this behavior, we must serialize key events with respect to all
1934 // prior input events.
1935 if (entry.type == EventEntry::Type::KEY) {
1936 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1937 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
1941
1942 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001943 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001944 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1945 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
1947 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001948 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949}
1950
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951/**
1952 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1953 * that are currently unresponsive.
1954 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001955std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1956 const std::vector<Monitor>& monitors) const {
1957 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001959 [this](const Monitor& monitor) REQUIRES(mLock) {
1960 sp<Connection> connection =
1961 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 if (connection == nullptr) {
1963 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001964 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001965 return false;
1966 }
1967 if (!connection->responsive) {
1968 ALOGW("Unresponsive monitor %s will not get the new gesture",
1969 connection->inputChannel->getName().c_str());
1970 return false;
1971 }
1972 return true;
1973 });
1974 return responsiveMonitors;
1975}
1976
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001977InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1978 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1979 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001980 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 enum InjectionPermission {
1982 INJECTION_PERMISSION_UNKNOWN,
1983 INJECTION_PERMISSION_GRANTED,
1984 INJECTION_PERMISSION_DENIED
1985 };
1986
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 // For security reasons, we defer updating the touch state until we are sure that
1988 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001989 const int32_t displayId = entry.displayId;
1990 const int32_t action = entry.action;
1991 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
1993 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001994 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001996 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1997 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 // Copy current touch state into tempTouchState.
2000 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2001 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002002 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002004 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2005 oldState = &(it->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002006 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002007 }
2008
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002009 bool isSplit = tempTouchState.split;
2010 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2011 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2012 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002013
2014 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2015 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2016 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2017 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2018 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002019 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 bool wrongDevice = false;
2021 if (newGesture) {
2022 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002024 ALOGI("Dropping event because a pointer for a different device is already down "
2025 "in display %" PRId32,
2026 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002027 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002028 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 switchedDevice = false;
2030 wrongDevice = true;
2031 goto Failed;
2032 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002033 tempTouchState.reset();
2034 tempTouchState.down = down;
2035 tempTouchState.deviceId = entry.deviceId;
2036 tempTouchState.source = entry.source;
2037 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002039 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002040 ALOGI("Dropping move event because a pointer for a different device is already active "
2041 "in display %" PRId32,
2042 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002043 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002044 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002045 switchedDevice = false;
2046 wrongDevice = true;
2047 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
2049
2050 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2051 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2052
Garfield Tan00f511d2019-06-12 16:55:40 -07002053 int32_t x;
2054 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002055 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002056 // Always dispatch mouse events to cursor position.
2057 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002058 x = int32_t(entry.xCursorPosition);
2059 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002060 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002061 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2062 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002063 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002064 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002065 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2066 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002067
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002069 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002070 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2071 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002073 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002074 }
2075
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002076 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002077 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002078 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2079 // New window supports splitting, but we should never split mouse events.
2080 isSplit = !isFromMouse;
2081 } else if (isSplit) {
2082 // New window does not support splitting but we have already split events.
2083 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002084 newTouchedWindowHandle = nullptr;
2085 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002086 } else {
2087 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002088 // be delivered to a new window which supports split touch. Pointers from a mouse device
2089 // should never be split.
2090 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002091 }
2092
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002093 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002094 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002095 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2096 newHoverWindowHandle = nullptr;
2097 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002099 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002100 }
2101
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002102 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
2103 findTouchedSpyWindowsAtLocked(displayId, x, y);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002104 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002105 // Process the foreground window first so that it is the first to receive the event.
2106 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002107 }
2108
2109 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2110 const WindowInfo& info = *windowHandle->getInfo();
2111
2112 if (info.paused) {
2113 ALOGI("Not sending touch event to %s because it is paused",
2114 windowHandle->getName().c_str());
2115 continue;
2116 }
2117
2118 // Ensure the window has a connection and the connection is responsive
2119 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2120 if (!isResponsive) {
2121 ALOGW("Not sending touch gesture to %s because it is not responsive",
2122 windowHandle->getName().c_str());
2123 continue;
2124 }
2125
2126 // Drop events that can't be trusted due to occlusion
2127 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2128 TouchOcclusionInfo occlusionInfo =
2129 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2130 if (!isTouchTrustedLocked(occlusionInfo)) {
2131 if (DEBUG_TOUCH_OCCLUSION) {
2132 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2133 for (const auto& log : occlusionInfo.debugInfo) {
2134 ALOGD("%s", log.c_str());
2135 }
2136 }
2137 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2138 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2139 ALOGW("Dropping untrusted touch event due to %s/%d",
2140 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2141 continue;
2142 }
2143 }
2144 }
2145
2146 // Drop touch events if requested by input feature
2147 if (shouldDropInput(entry, windowHandle)) {
2148 continue;
2149 }
2150
2151 // Set target flags.
2152 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2153
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002154 if (!info.isSpy()) {
2155 // There should only be one new foreground (non-spy) window at this location.
2156 targetFlags |= InputTarget::FLAG_FOREGROUND;
2157 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002158
2159 if (isSplit) {
2160 targetFlags |= InputTarget::FLAG_SPLIT;
2161 }
2162 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2163 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2164 } else if (isWindowObscuredLocked(windowHandle)) {
2165 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2166 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002167
2168 // Update the temporary touch state.
2169 BitSet32 pointerIds;
2170 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002171 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002172 pointerIds.markBit(pointerId);
2173 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002174
2175 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002177
2178 const std::vector<Monitor> newGestureMonitors = isDown
2179 ? selectResponsiveMonitorsLocked(
2180 getValueByKey(mGestureMonitorsByDisplay, displayId))
2181 : std::vector<Monitor>{};
2182
2183 if (newTouchedWindows.empty() && newGestureMonitors.empty() &&
2184 tempTouchState.gestureMonitors.empty()) {
2185 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
2186 "(%d, %d) in display %" PRId32 ".",
2187 x, y, displayId);
2188 injectionResult = InputEventInjectionResult::FAILED;
2189 goto Failed;
Arthur Hung2ea44b92021-11-23 07:42:21 +00002190 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191
2192 tempTouchState.addGestureMonitors(newGestureMonitors);
2193
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 } else {
2195 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2196
2197 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002198 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002199 if (DEBUG_FOCUS) {
2200 ALOGD("Dropping event because the pointer is not down or we previously "
2201 "dropped the pointer down event in display %" PRId32,
2202 displayId);
2203 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002204 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 goto Failed;
2206 }
2207
arthurhung6d4bed92021-03-17 11:59:33 +08002208 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002209
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002211 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002213 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2214 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215
chaviw98318de2021-05-19 16:45:23 -05002216 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002217 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002218 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002219
2220 // Drop touch events if requested by input feature
2221 if (newTouchedWindowHandle != nullptr &&
2222 shouldDropInput(entry, newTouchedWindowHandle)) {
2223 newTouchedWindowHandle = nullptr;
2224 }
2225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002226 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2227 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002228 if (DEBUG_FOCUS) {
2229 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2230 oldTouchedWindowHandle->getName().c_str(),
2231 newTouchedWindowHandle->getName().c_str(), displayId);
2232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2235 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2236 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237
2238 // Make a slippery entrance into the new window.
2239 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002240 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 }
2242
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002243 int32_t targetFlags =
2244 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 if (isSplit) {
2246 targetFlags |= InputTarget::FLAG_SPLIT;
2247 }
2248 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2249 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002250 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2251 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
2253
2254 BitSet32 pointerIds;
2255 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002256 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002258 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 }
2260 }
2261 }
2262
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002263 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 // Let the previous window know that the hover sequence is over, unless we already did
2266 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002267 if (mLastHoverWindowHandle != nullptr &&
2268 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2269 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002270 if (DEBUG_HOVER) {
2271 ALOGD("Sending hover exit event to window %s.",
2272 mLastHoverWindowHandle->getName().c_str());
2273 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002274 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2275 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
Garfield Tandf26e862020-07-01 20:18:19 -07002278 // Let the new window know that the hover sequence is starting, unless we already did it
2279 // when dispatching it as is to newTouchedWindowHandle.
2280 if (newHoverWindowHandle != nullptr &&
2281 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2282 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002283 if (DEBUG_HOVER) {
2284 ALOGD("Sending hover enter event to window %s.",
2285 newHoverWindowHandle->getName().c_str());
2286 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002287 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2288 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2289 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291 }
2292
2293 // Check permission to inject into all touched foreground windows and ensure there
2294 // is at least one touched foreground window.
2295 {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002296 bool haveForegroundOrSpyWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002297 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002298 const bool isForeground =
2299 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
2300 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2301 haveForegroundOrSpyWindow = true;
2302 LOG_ALWAYS_FATAL_IF(isForeground,
2303 "Spy window cannot be dispatched as a foreground window.");
2304 }
2305 if (isForeground) {
2306 haveForegroundOrSpyWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002307 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002308 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 injectionPermission = INJECTION_PERMISSION_DENIED;
2310 goto Failed;
2311 }
2312 }
2313 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002314 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002315 if (!haveForegroundOrSpyWindow && !hasGestureMonitor) {
2316 ALOGI("Dropping event because there is no touched window in display "
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002317 "%" PRId32 " or gesture monitor to receive it.",
2318 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002319 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 goto Failed;
2321 }
2322
2323 // Permission granted to injection into all touched foreground windows.
2324 injectionPermission = INJECTION_PERMISSION_GRANTED;
2325 }
2326
2327 // Check whether windows listening for outside touches are owned by the same UID. If it is
2328 // set the policy flag that we will not reveal coordinate information to this window.
2329 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002330 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002331 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002332 if (foregroundWindowHandle) {
2333 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002334 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002335 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002336 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2337 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2338 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002339 InputTarget::FLAG_ZERO_COORDS,
2340 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 }
2343 }
2344 }
2345 }
2346
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 // If this is the first pointer going down and the touched window has a wallpaper
2348 // then also add the touched wallpaper windows so they are locked in for the duration
2349 // of the touch gesture.
2350 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2351 // engine only supports touch events. We would need to add a mechanism similar
2352 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2353 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002354 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002355 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002356 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002357 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002358 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002359 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2360 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002362 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002363 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002364 .addOrUpdateWindow(windowHandle,
2365 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2366 InputTarget::
2367 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2368 InputTarget::FLAG_DISPATCH_AS_IS,
2369 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371 }
2372 }
2373 }
2374
2375 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002376 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002378 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002383 for (const auto& monitor : tempTouchState.gestureMonitors) {
2384 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002385 }
2386
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 // Drop the outside or hover touch windows since we will not care about them
2388 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002389 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390
2391Failed:
2392 // Check injection permission once and for all.
2393 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002394 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 injectionPermission = INJECTION_PERMISSION_GRANTED;
2396 } else {
2397 injectionPermission = INJECTION_PERMISSION_DENIED;
2398 }
2399 }
2400
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002401 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2402 return injectionResult;
2403 }
2404
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002406 if (!wrongDevice) {
2407 if (switchedDevice) {
2408 if (DEBUG_FOCUS) {
2409 ALOGD("Conflicting pointer actions: Switched to a different device.");
2410 }
2411 *outConflictingPointerActions = true;
2412 }
2413
2414 if (isHoverAction) {
2415 // Started hovering, therefore no longer down.
2416 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002417 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002418 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2419 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 *outConflictingPointerActions = true;
2422 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002423 tempTouchState.reset();
2424 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2425 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2426 tempTouchState.deviceId = entry.deviceId;
2427 tempTouchState.source = entry.source;
2428 tempTouchState.displayId = displayId;
2429 }
2430 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2431 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2432 // All pointers up or canceled.
2433 tempTouchState.reset();
2434 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2435 // First pointer went down.
2436 if (oldState && oldState->down) {
2437 if (DEBUG_FOCUS) {
2438 ALOGD("Conflicting pointer actions: Down received while already down.");
2439 }
2440 *outConflictingPointerActions = true;
2441 }
2442 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2443 // One pointer went up.
2444 if (isSplit) {
2445 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2446 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002448 for (size_t i = 0; i < tempTouchState.windows.size();) {
2449 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2450 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2451 touchedWindow.pointerIds.clearBit(pointerId);
2452 if (touchedWindow.pointerIds.isEmpty()) {
2453 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2454 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002457 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002459 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002460 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002461
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002462 // Save changes unless the action was scroll in which case the temporary touch
2463 // state was only valid for this one action.
2464 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2465 if (tempTouchState.displayId >= 0) {
2466 mTouchStatesByDisplay[displayId] = tempTouchState;
2467 } else {
2468 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002472 // Update hover state.
2473 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 }
2475
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 return injectionResult;
2477}
2478
arthurhung6d4bed92021-03-17 11:59:33 +08002479void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002480 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002481 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002482 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002483 if (dropWindow) {
2484 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002485 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002486 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002487 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002488 }
2489 mDragState.reset();
2490}
2491
2492void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2493 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002494 return;
2495 }
2496
arthurhung6d4bed92021-03-17 11:59:33 +08002497 if (!mDragState->isStartDrag) {
2498 mDragState->isStartDrag = true;
2499 mDragState->isStylusButtonDownAtStart =
2500 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2501 }
2502
arthurhungb89ccb02020-12-30 16:19:01 +08002503 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2504 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2505 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2506 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002507 // Handle the special case : stylus button no longer pressed.
2508 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2509 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2510 finishDragAndDrop(entry.displayId, x, y);
2511 return;
2512 }
2513
chaviw98318de2021-05-19 16:45:23 -05002514 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002515 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002516 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002517 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002518 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2519 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2520 if (mDragState->dragHoverWindowHandle != nullptr) {
2521 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2522 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002523 }
arthurhung6d4bed92021-03-17 11:59:33 +08002524 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002525 }
2526 // enqueue drag location if needed.
2527 if (hoverWindowHandle != nullptr) {
2528 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2529 }
arthurhung6d4bed92021-03-17 11:59:33 +08002530 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2531 finishDragAndDrop(entry.displayId, x, y);
2532 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002533 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002534 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002535 }
2536}
2537
chaviw98318de2021-05-19 16:45:23 -05002538void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 int32_t targetFlags, BitSet32 pointerIds,
2540 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002541 std::vector<InputTarget>::iterator it =
2542 std::find_if(inputTargets.begin(), inputTargets.end(),
2543 [&windowHandle](const InputTarget& inputTarget) {
2544 return inputTarget.inputChannel->getConnectionToken() ==
2545 windowHandle->getToken();
2546 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002547
chaviw98318de2021-05-19 16:45:23 -05002548 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002549
2550 if (it == inputTargets.end()) {
2551 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002552 std::shared_ptr<InputChannel> inputChannel =
2553 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002554 if (inputChannel == nullptr) {
2555 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2556 return;
2557 }
2558 inputTarget.inputChannel = inputChannel;
2559 inputTarget.flags = targetFlags;
2560 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002561 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2562 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002563 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002564 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002565 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002566 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002567 inputTargets.push_back(inputTarget);
2568 it = inputTargets.end() - 1;
2569 }
2570
2571 ALOG_ASSERT(it->flags == targetFlags);
2572 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2573
chaviw1ff3d1e2020-07-01 15:53:47 -07002574 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575}
2576
Michael Wright3dd60e22019-03-27 22:06:44 +00002577void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002578 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002579 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2580 mGlobalMonitorsByDisplay.find(displayId);
2581
2582 if (it != mGlobalMonitorsByDisplay.end()) {
2583 const std::vector<Monitor>& monitors = it->second;
2584 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002585 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
2588}
2589
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002590void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002592 InputTarget target;
2593 target.inputChannel = monitor.inputChannel;
2594 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002595 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002596 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002597 const auto& displayTransform = it->second.transform;
2598 target.displayTransform = displayTransform;
2599 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002600 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002601 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002602 inputTargets.push_back(target);
2603}
2604
chaviw98318de2021-05-19 16:45:23 -05002605bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606 const InjectionState* injectionState) {
2607 if (injectionState &&
2608 (windowHandle == nullptr ||
2609 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2610 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002611 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 "owned by uid %d",
2614 injectionState->injectorPid, injectionState->injectorUid,
2615 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 } else {
2617 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620 return false;
2621 }
2622 return true;
2623}
2624
Robert Carrc9bf1d32020-04-13 17:21:08 -07002625/**
2626 * Indicate whether one window handle should be considered as obscuring
2627 * another window handle. We only check a few preconditions. Actually
2628 * checking the bounds is left to the caller.
2629 */
chaviw98318de2021-05-19 16:45:23 -05002630static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2631 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002632 // Compare by token so cloned layers aren't counted
2633 if (haveSameToken(windowHandle, otherHandle)) {
2634 return false;
2635 }
2636 auto info = windowHandle->getInfo();
2637 auto otherInfo = otherHandle->getInfo();
2638 if (!otherInfo->visible) {
2639 return false;
chaviw98318de2021-05-19 16:45:23 -05002640 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002641 // Those act as if they were invisible, so we don't need to flag them.
2642 // We do want to potentially flag touchable windows even if they have 0
2643 // opacity, since they can consume touches and alter the effects of the
2644 // user interaction (eg. apps that rely on
2645 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2646 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2647 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002648 } else if (info->ownerUid == otherInfo->ownerUid) {
2649 // If ownerUid is the same we don't generate occlusion events as there
2650 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002651 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002652 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002653 return false;
2654 } else if (otherInfo->displayId != info->displayId) {
2655 return false;
2656 }
2657 return true;
2658}
2659
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002660/**
2661 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2662 * untrusted, one should check:
2663 *
2664 * 1. If result.hasBlockingOcclusion is true.
2665 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2666 * BLOCK_UNTRUSTED.
2667 *
2668 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2669 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2670 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2671 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2672 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2673 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2674 *
2675 * If neither of those is true, then it means the touch can be allowed.
2676 */
2677InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002678 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2679 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002680 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002681 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002682 TouchOcclusionInfo info;
2683 info.hasBlockingOcclusion = false;
2684 info.obscuringOpacity = 0;
2685 info.obscuringUid = -1;
2686 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002687 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002688 if (windowHandle == otherHandle) {
2689 break; // All future windows are below us. Exit early.
2690 }
chaviw98318de2021-05-19 16:45:23 -05002691 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002692 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2693 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002694 if (DEBUG_TOUCH_OCCLUSION) {
2695 info.debugInfo.push_back(
2696 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2697 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002698 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2699 // we perform the checks below to see if the touch can be propagated or not based on the
2700 // window's touch occlusion mode
2701 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2702 info.hasBlockingOcclusion = true;
2703 info.obscuringUid = otherInfo->ownerUid;
2704 info.obscuringPackage = otherInfo->packageName;
2705 break;
2706 }
2707 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2708 uint32_t uid = otherInfo->ownerUid;
2709 float opacity =
2710 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2711 // Given windows A and B:
2712 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2713 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2714 opacityByUid[uid] = opacity;
2715 if (opacity > info.obscuringOpacity) {
2716 info.obscuringOpacity = opacity;
2717 info.obscuringUid = uid;
2718 info.obscuringPackage = otherInfo->packageName;
2719 }
2720 }
2721 }
2722 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002723 if (DEBUG_TOUCH_OCCLUSION) {
2724 info.debugInfo.push_back(
2725 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2726 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002727 return info;
2728}
2729
chaviw98318de2021-05-19 16:45:23 -05002730std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002731 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002732 return StringPrintf(INDENT2
2733 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2734 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2735 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2736 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002737 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002738 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002739 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2740 info->frameTop, info->frameRight, info->frameBottom,
2741 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002742 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2743 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2744 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002745}
2746
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002747bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2748 if (occlusionInfo.hasBlockingOcclusion) {
2749 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2750 occlusionInfo.obscuringUid);
2751 return false;
2752 }
2753 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2754 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2755 "%.2f, maximum allowed = %.2f)",
2756 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2757 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2758 return false;
2759 }
2760 return true;
2761}
2762
chaviw98318de2021-05-19 16:45:23 -05002763bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002766 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2767 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002768 if (windowHandle == otherHandle) {
2769 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 }
chaviw98318de2021-05-19 16:45:23 -05002771 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002772 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002773 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 return true;
2775 }
2776 }
2777 return false;
2778}
2779
chaviw98318de2021-05-19 16:45:23 -05002780bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002781 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002782 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2783 const WindowInfo* windowInfo = windowHandle->getInfo();
2784 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002785 if (windowHandle == otherHandle) {
2786 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002787 }
chaviw98318de2021-05-19 16:45:23 -05002788 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002789 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002790 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002791 return true;
2792 }
2793 }
2794 return false;
2795}
2796
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002797std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002798 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002799 if (applicationHandle != nullptr) {
2800 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002801 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 } else {
2803 return applicationHandle->getName();
2804 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002805 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002806 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002808 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
2810}
2811
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002812void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002813 if (!isUserActivityEvent(eventEntry)) {
2814 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002815 return;
2816 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002817 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002818 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002819 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002820 const WindowInfo* info = focusedWindowHandle->getInfo();
2821 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002822 if (DEBUG_DISPATCH_CYCLE) {
2823 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 return;
2826 }
2827 }
2828
2829 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002830 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002831 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002832 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2833 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 return;
2835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002837 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 eventType = USER_ACTIVITY_EVENT_TOUCH;
2839 }
2840 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002842 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002843 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2844 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 return;
2846 }
2847 eventType = USER_ACTIVITY_EVENT_BUTTON;
2848 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002850 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002851 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002852 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002853 break;
2854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 }
2856
Prabir Pradhancef936d2021-07-21 16:17:52 +00002857 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2858 REQUIRES(mLock) {
2859 scoped_unlock unlock(mLock);
2860 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2861 };
2862 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863}
2864
2865void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002866 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002867 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002868 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002869 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002870 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002871 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002872 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002873 ATRACE_NAME(message.c_str());
2874 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002875 if (DEBUG_DISPATCH_CYCLE) {
2876 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2877 "globalScaleFactor=%f, pointerIds=0x%x %s",
2878 connection->getInputChannelName().c_str(), inputTarget.flags,
2879 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2880 inputTarget.getPointerInfoString().c_str());
2881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
2883 // Skip this event if the connection status is not normal.
2884 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002885 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002886 if (DEBUG_DISPATCH_CYCLE) {
2887 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002888 connection->getInputChannelName().c_str(),
2889 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 return;
2892 }
2893
2894 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002895 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2896 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2897 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002898 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002900 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002901 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002902 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002903 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 if (!splitMotionEntry) {
2905 return; // split event was dropped
2906 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002907 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2908 std::string reason = std::string("reason=pointer cancel on split window");
2909 android_log_event_list(LOGTAG_INPUT_CANCEL)
2910 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2911 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002912 if (DEBUG_FOCUS) {
2913 ALOGD("channel '%s' ~ Split motion event.",
2914 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002915 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002916 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002917 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2918 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 return;
2920 }
2921 }
2922
2923 // Not splitting. Enqueue dispatch entries for the event as is.
2924 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2925}
2926
2927void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002929 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002930 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002931 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002933 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002934 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002935 ATRACE_NAME(message.c_str());
2936 }
2937
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002938 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
2940 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002941 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002942 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002943 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002945 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002947 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002949 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002951 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953
2954 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002955 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 startDispatchCycleLocked(currentTime, connection);
2957 }
2958}
2959
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002961 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002962 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002964 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2966 connection->getInputChannelName().c_str(),
2967 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002968 ATRACE_NAME(message.c_str());
2969 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002970 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 if (!(inputTargetFlags & dispatchMode)) {
2972 return;
2973 }
2974 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2975
2976 // This is a new event.
2977 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002978 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002979 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002981 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2982 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002983 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002985 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002986 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002987 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002988 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002989 dispatchEntry->resolvedAction = keyEntry.action;
2990 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2993 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002994 if (DEBUG_DISPATCH_CYCLE) {
2995 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2996 "event",
2997 connection->getInputChannelName().c_str());
2998 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 return; // skip the inconsistent event
3000 }
3001 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003004 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003005 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003006 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3007 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3008 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3009 static_cast<int32_t>(IdGenerator::Source::OTHER);
3010 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3012 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3013 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3014 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3015 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3016 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3017 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3018 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3019 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3020 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3021 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003022 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003023 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 }
3025 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003026 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3027 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003028 if (DEBUG_DISPATCH_CYCLE) {
3029 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3030 "enter event",
3031 connection->getInputChannelName().c_str());
3032 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003033 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3034 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003038 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3040 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3041 }
3042 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3043 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3047 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003048 if (DEBUG_DISPATCH_CYCLE) {
3049 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3050 "event",
3051 connection->getInputChannelName().c_str());
3052 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 return; // skip the inconsistent event
3054 }
3055
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003056 dispatchEntry->resolvedEventId =
3057 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3058 ? mIdGenerator.nextId()
3059 : motionEntry.id;
3060 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3061 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3062 ") to MotionEvent(id=0x%" PRIx32 ").",
3063 motionEntry.id, dispatchEntry->resolvedEventId);
3064 ATRACE_NAME(message.c_str());
3065 }
3066
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003067 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3068 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3069 // Skip reporting pointer down outside focus to the policy.
3070 break;
3071 }
3072
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003073 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003074 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075
3076 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003078 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003079 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003080 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3081 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003082 break;
3083 }
Chris Yef59a2f42020-10-16 12:55:26 -07003084 case EventEntry::Type::SENSOR: {
3085 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3086 break;
3087 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003088 case EventEntry::Type::CONFIGURATION_CHANGED:
3089 case EventEntry::Type::DEVICE_RESET: {
3090 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003091 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003092 break;
3093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 }
3095
3096 // Remember that we are waiting for this dispatch to complete.
3097 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003098 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 }
3100
3101 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003102 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003103 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003104}
3105
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003106/**
3107 * This function is purely for debugging. It helps us understand where the user interaction
3108 * was taking place. For example, if user is touching launcher, we will see a log that user
3109 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3110 * We will see both launcher and wallpaper in that list.
3111 * Once the interaction with a particular set of connections starts, no new logs will be printed
3112 * until the set of interacted connections changes.
3113 *
3114 * The following items are skipped, to reduce the logspam:
3115 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3116 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3117 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3118 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3119 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003120 */
3121void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3122 const std::vector<InputTarget>& targets) {
3123 // Skip ACTION_UP events, and all events other than keys and motions
3124 if (entry.type == EventEntry::Type::KEY) {
3125 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3126 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3127 return;
3128 }
3129 } else if (entry.type == EventEntry::Type::MOTION) {
3130 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3131 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3132 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3133 return;
3134 }
3135 } else {
3136 return; // Not a key or a motion
3137 }
3138
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003139 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003140 std::vector<sp<Connection>> newConnections;
3141 for (const InputTarget& target : targets) {
3142 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3143 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3144 continue; // Skip windows that receive ACTION_OUTSIDE
3145 }
3146
3147 sp<IBinder> token = target.inputChannel->getConnectionToken();
3148 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003149 if (connection == nullptr) {
3150 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003151 }
3152 newConnectionTokens.insert(std::move(token));
3153 newConnections.emplace_back(connection);
3154 }
3155 if (newConnectionTokens == mInteractionConnectionTokens) {
3156 return; // no change
3157 }
3158 mInteractionConnectionTokens = newConnectionTokens;
3159
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003160 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003161 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003162 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003163 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003164 std::string message = "Interaction with: " + targetList;
3165 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003166 message += "<none>";
3167 }
3168 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3169}
3170
chaviwfd6d3512019-03-25 13:23:49 -07003171void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003172 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003173 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003174 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3175 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003176 return;
3177 }
3178
Vishnu Nairc519ff72021-01-21 08:23:08 -08003179 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003180 if (focusedToken == token) {
3181 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003182 return;
3183 }
3184
Prabir Pradhancef936d2021-07-21 16:17:52 +00003185 auto command = [this, token]() REQUIRES(mLock) {
3186 scoped_unlock unlock(mLock);
3187 mPolicy->onPointerDownOutsideFocus(token);
3188 };
3189 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190}
3191
3192void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003194 if (ATRACE_ENABLED()) {
3195 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003197 ATRACE_NAME(message.c_str());
3198 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003199 if (DEBUG_DISPATCH_CYCLE) {
3200 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003203 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003204 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003206 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003207 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003208 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209
3210 // Publish the event.
3211 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003212 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3213 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003214 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003215 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3216 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003219 status = connection->inputPublisher
3220 .publishKeyEvent(dispatchEntry->seq,
3221 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3222 keyEntry.source, keyEntry.displayId,
3223 std::move(hmac), dispatchEntry->resolvedAction,
3224 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3225 keyEntry.scanCode, keyEntry.metaState,
3226 keyEntry.repeatCount, keyEntry.downTime,
3227 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 }
3230
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003231 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003235 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236
chaviw82357092020-01-28 13:13:06 -08003237 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003238 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3240 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003241 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003242 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3243 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003244 // Don't apply window scale here since we don't want scale to affect raw
3245 // coordinates. The scale will be sent back to the client and applied
3246 // later when requesting relative coordinates.
3247 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3248 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249 }
3250 usingCoords = scaledCoords;
3251 }
3252 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 // We don't want the dispatch target to know.
3254 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003255 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 scaledCoords[i].clear();
3257 }
3258 usingCoords = scaledCoords;
3259 }
3260 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003261
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003262 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003263
3264 // Publish the motion event.
3265 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003266 .publishMotionEvent(dispatchEntry->seq,
3267 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003268 motionEntry.deviceId, motionEntry.source,
3269 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003270 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003271 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003272 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003273 motionEntry.edgeFlags, motionEntry.metaState,
3274 motionEntry.buttonState,
3275 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003276 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003277 motionEntry.xPrecision, motionEntry.yPrecision,
3278 motionEntry.xCursorPosition,
3279 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003280 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003281 motionEntry.downTime, motionEntry.eventTime,
3282 motionEntry.pointerCount,
3283 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003284 break;
3285 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003286
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003287 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003288 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003289 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003291 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003292 break;
3293 }
3294
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003295 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3296 const TouchModeEntry& touchModeEntry =
3297 static_cast<const TouchModeEntry&>(eventEntry);
3298 status = connection->inputPublisher
3299 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3300 touchModeEntry.inTouchMode);
3301
3302 break;
3303 }
3304
Prabir Pradhan99987712020-11-10 18:43:05 -08003305 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3306 const auto& captureEntry =
3307 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3308 status = connection->inputPublisher
3309 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003310 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003311 break;
3312 }
3313
arthurhungb89ccb02020-12-30 16:19:01 +08003314 case EventEntry::Type::DRAG: {
3315 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3316 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3317 dragEntry.id, dragEntry.x,
3318 dragEntry.y,
3319 dragEntry.isExiting);
3320 break;
3321 }
3322
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003323 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003324 case EventEntry::Type::DEVICE_RESET:
3325 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003326 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003327 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 }
3331
3332 // Check the result.
3333 if (status) {
3334 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003335 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 "This is unexpected because the wait queue is empty, so the pipe "
3338 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003339 "event to it, status=%s(%d)",
3340 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3341 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3343 } else {
3344 // Pipe is full and we are waiting for the app to finish process some events
3345 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003346 if (DEBUG_DISPATCH_CYCLE) {
3347 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3348 "waiting for the application to catch up",
3349 connection->getInputChannelName().c_str());
3350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 }
3352 } else {
3353 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003354 "status=%s(%d)",
3355 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3356 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3358 }
3359 return;
3360 }
3361
3362 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003363 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3364 connection->outboundQueue.end(),
3365 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003366 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003367 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003368 if (connection->responsive) {
3369 mAnrTracker.insert(dispatchEntry->timeoutTime,
3370 connection->inputChannel->getConnectionToken());
3371 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003372 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 }
3374}
3375
chaviw09c8d2d2020-08-24 15:48:26 -07003376std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3377 size_t size;
3378 switch (event.type) {
3379 case VerifiedInputEvent::Type::KEY: {
3380 size = sizeof(VerifiedKeyEvent);
3381 break;
3382 }
3383 case VerifiedInputEvent::Type::MOTION: {
3384 size = sizeof(VerifiedMotionEvent);
3385 break;
3386 }
3387 }
3388 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3389 return mHmacKeyManager.sign(start, size);
3390}
3391
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003392const std::array<uint8_t, 32> InputDispatcher::getSignature(
3393 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003394 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3395 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003396 // Only sign events up and down events as the purely move events
3397 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003398 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003399 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003400
3401 VerifiedMotionEvent verifiedEvent =
3402 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3403 verifiedEvent.actionMasked = actionMasked;
3404 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3405 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003406}
3407
3408const std::array<uint8_t, 32> InputDispatcher::getSignature(
3409 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3410 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3411 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3412 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003413 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003414}
3415
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003418 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003419 if (DEBUG_DISPATCH_CYCLE) {
3420 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3421 connection->getInputChannelName().c_str(), seq, toString(handled));
3422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003424 if (connection->status == Connection::Status::BROKEN ||
3425 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 return;
3427 }
3428
3429 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003430 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3431 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3432 };
3433 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434}
3435
3436void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437 const sp<Connection>& connection,
3438 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003439 if (DEBUG_DISPATCH_CYCLE) {
3440 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3441 connection->getInputChannelName().c_str(), toString(notify));
3442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443
3444 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003445 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003446 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003447 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003448 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449
3450 // The connection appears to be unrecoverably broken.
3451 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003452 if (connection->status == Connection::Status::NORMAL) {
3453 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454
3455 if (notify) {
3456 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003457 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3458 connection->getInputChannelName().c_str());
3459
3460 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003461 scoped_unlock unlock(mLock);
3462 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3463 };
3464 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 }
3466 }
3467}
3468
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003469void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3470 while (!queue.empty()) {
3471 DispatchEntry* dispatchEntry = queue.front();
3472 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003473 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
3475}
3476
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003477void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003479 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 }
3481 delete dispatchEntry;
3482}
3483
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003484int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3485 std::scoped_lock _l(mLock);
3486 sp<Connection> connection = getConnectionLocked(connectionToken);
3487 if (connection == nullptr) {
3488 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3489 connectionToken.get(), events);
3490 return 0; // remove the callback
3491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003493 bool notify;
3494 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3495 if (!(events & ALOOPER_EVENT_INPUT)) {
3496 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3497 "events=0x%x",
3498 connection->getInputChannelName().c_str(), events);
3499 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
3501
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003502 nsecs_t currentTime = now();
3503 bool gotOne = false;
3504 status_t status = OK;
3505 for (;;) {
3506 Result<InputPublisher::ConsumerResponse> result =
3507 connection->inputPublisher.receiveConsumerResponse();
3508 if (!result.ok()) {
3509 status = result.error().code();
3510 break;
3511 }
3512
3513 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3514 const InputPublisher::Finished& finish =
3515 std::get<InputPublisher::Finished>(*result);
3516 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3517 finish.consumeTime);
3518 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003519 if (shouldReportMetricsForConnection(*connection)) {
3520 const InputPublisher::Timeline& timeline =
3521 std::get<InputPublisher::Timeline>(*result);
3522 mLatencyTracker
3523 .trackGraphicsLatency(timeline.inputEventId,
3524 connection->inputChannel->getConnectionToken(),
3525 std::move(timeline.graphicsTimeline));
3526 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003527 }
3528 gotOne = true;
3529 }
3530 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003531 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003532 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 return 1;
3534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003537 notify = status != DEAD_OBJECT || !connection->monitor;
3538 if (notify) {
3539 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3540 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3541 status);
3542 }
3543 } else {
3544 // Monitor channels are never explicitly unregistered.
3545 // We do it automatically when the remote endpoint is closed so don't warn about them.
3546 const bool stillHaveWindowHandle =
3547 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3548 notify = !connection->monitor && stillHaveWindowHandle;
3549 if (notify) {
3550 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3551 connection->getInputChannelName().c_str(), events);
3552 }
3553 }
3554
3555 // Remove the channel.
3556 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3557 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558}
3559
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003562 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003563 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 }
3565}
3566
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003567void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003568 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003569 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3570 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3571}
3572
3573void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3574 const CancelationOptions& options,
3575 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3576 for (const auto& it : monitorsByDisplay) {
3577 const std::vector<Monitor>& monitors = it.second;
3578 for (const Monitor& monitor : monitors) {
3579 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003580 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003581 }
3582}
3583
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003585 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003586 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003587 if (connection == nullptr) {
3588 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003590
3591 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592}
3593
3594void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3595 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003596 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 return;
3598 }
3599
3600 nsecs_t currentTime = now();
3601
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003603 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003605 if (cancelationEvents.empty()) {
3606 return;
3607 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003608 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3609 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3610 "with reality: %s, mode=%d.",
3611 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3612 options.mode);
3613 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003614
Arthur Hungb3307ee2021-10-14 10:57:37 +00003615 std::string reason = std::string("reason=").append(options.reason);
3616 android_log_event_list(LOGTAG_INPUT_CANCEL)
3617 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3618
Svet Ganov5d3bc372020-01-26 23:11:07 -08003619 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003620 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003621 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3622 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003623 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003624 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003625 target.globalScaleFactor = windowInfo->globalScaleFactor;
3626 }
3627 target.inputChannel = connection->inputChannel;
3628 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3629
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003630 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003631 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003632 switch (cancelationEventEntry->type) {
3633 case EventEntry::Type::KEY: {
3634 logOutboundKeyDetails("cancel - ",
3635 static_cast<const KeyEntry&>(*cancelationEventEntry));
3636 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003638 case EventEntry::Type::MOTION: {
3639 logOutboundMotionDetails("cancel - ",
3640 static_cast<const MotionEntry&>(*cancelationEventEntry));
3641 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003643 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003644 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003645 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3646 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003647 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003648 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003649 break;
3650 }
3651 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003652 case EventEntry::Type::DEVICE_RESET:
3653 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003654 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003655 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003656 break;
3657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 }
3659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3661 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003663
3664 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665}
3666
Svet Ganov5d3bc372020-01-26 23:11:07 -08003667void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3668 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003669 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 return;
3671 }
3672
3673 nsecs_t currentTime = now();
3674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 connection->inputState.synthesizePointerDownEvents(currentTime);
3677
3678 if (downEvents.empty()) {
3679 return;
3680 }
3681
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003682 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003683 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3684 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003685 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003686
3687 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003688 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003689 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3690 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003691 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003692 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003693 target.globalScaleFactor = windowInfo->globalScaleFactor;
3694 }
3695 target.inputChannel = connection->inputChannel;
3696 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3697
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003698 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003699 switch (downEventEntry->type) {
3700 case EventEntry::Type::MOTION: {
3701 logOutboundMotionDetails("down - ",
3702 static_cast<const MotionEntry&>(*downEventEntry));
3703 break;
3704 }
3705
3706 case EventEntry::Type::KEY:
3707 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003708 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003709 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003710 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003711 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003712 case EventEntry::Type::SENSOR:
3713 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003714 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003715 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 break;
3717 }
3718 }
3719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003720 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3721 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003722 }
3723
3724 startDispatchCycleLocked(currentTime, connection);
3725}
3726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003727std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3728 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 ALOG_ASSERT(pointerIds.value != 0);
3730
3731 uint32_t splitPointerIndexMap[MAX_POINTERS];
3732 PointerProperties splitPointerProperties[MAX_POINTERS];
3733 PointerCoords splitPointerCoords[MAX_POINTERS];
3734
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003735 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 uint32_t splitPointerCount = 0;
3737
3738 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003741 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 uint32_t pointerId = uint32_t(pointerProperties.id);
3743 if (pointerIds.hasBit(pointerId)) {
3744 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3745 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3746 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003747 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 splitPointerCount += 1;
3749 }
3750 }
3751
3752 if (splitPointerCount != pointerIds.count()) {
3753 // This is bad. We are missing some of the pointers that we expected to deliver.
3754 // Most likely this indicates that we received an ACTION_MOVE events that has
3755 // different pointer ids than we expected based on the previous ACTION_DOWN
3756 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3757 // in this way.
3758 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003759 "we expected there to be %d pointers. This probably means we received "
3760 "a broken sequence of pointer ids from the input device.",
3761 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003762 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 }
3764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003765 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003767 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3768 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3770 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003771 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 uint32_t pointerId = uint32_t(pointerProperties.id);
3773 if (pointerIds.hasBit(pointerId)) {
3774 if (pointerIds.count() == 1) {
3775 // The first/last pointer went down/up.
3776 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003778 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3779 ? AMOTION_EVENT_ACTION_CANCEL
3780 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 } else {
3782 // A secondary pointer went down/up.
3783 uint32_t splitPointerIndex = 0;
3784 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3785 splitPointerIndex += 1;
3786 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 action = maskedAction |
3788 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 }
3790 } else {
3791 // An unrelated pointer changed.
3792 action = AMOTION_EVENT_ACTION_MOVE;
3793 }
3794 }
3795
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003796 int32_t newId = mIdGenerator.nextId();
3797 if (ATRACE_ENABLED()) {
3798 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3799 ") to MotionEvent(id=0x%" PRIx32 ").",
3800 originalMotionEntry.id, newId);
3801 ATRACE_NAME(message.c_str());
3802 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003803 std::unique_ptr<MotionEntry> splitMotionEntry =
3804 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3805 originalMotionEntry.deviceId, originalMotionEntry.source,
3806 originalMotionEntry.displayId,
3807 originalMotionEntry.policyFlags, action,
3808 originalMotionEntry.actionButton,
3809 originalMotionEntry.flags, originalMotionEntry.metaState,
3810 originalMotionEntry.buttonState,
3811 originalMotionEntry.classification,
3812 originalMotionEntry.edgeFlags,
3813 originalMotionEntry.xPrecision,
3814 originalMotionEntry.yPrecision,
3815 originalMotionEntry.xCursorPosition,
3816 originalMotionEntry.yCursorPosition,
3817 originalMotionEntry.downTime, splitPointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00003818 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003820 if (originalMotionEntry.injectionState) {
3821 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 splitMotionEntry->injectionState->refCount += 1;
3823 }
3824
3825 return splitMotionEntry;
3826}
3827
3828void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003829 if (DEBUG_INBOUND_EVENT_DETAILS) {
3830 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
Antonio Kantekf16f2832021-09-28 04:39:20 +00003833 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003835 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003837 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3838 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3839 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 } // release lock
3841
3842 if (needWake) {
3843 mLooper->wake();
3844 }
3845}
3846
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003847/**
3848 * If one of the meta shortcuts is detected, process them here:
3849 * Meta + Backspace -> generate BACK
3850 * Meta + Enter -> generate HOME
3851 * This will potentially overwrite keyCode and metaState.
3852 */
3853void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003855 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3856 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3857 if (keyCode == AKEYCODE_DEL) {
3858 newKeyCode = AKEYCODE_BACK;
3859 } else if (keyCode == AKEYCODE_ENTER) {
3860 newKeyCode = AKEYCODE_HOME;
3861 }
3862 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003863 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003864 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003865 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003866 keyCode = newKeyCode;
3867 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3868 }
3869 } else if (action == AKEY_EVENT_ACTION_UP) {
3870 // In order to maintain a consistent stream of up and down events, check to see if the key
3871 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3872 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003873 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003874 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003875 auto replacementIt = mReplacedKeys.find(replacement);
3876 if (replacementIt != mReplacedKeys.end()) {
3877 keyCode = replacementIt->second;
3878 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003879 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3880 }
3881 }
3882}
3883
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003885 if (DEBUG_INBOUND_EVENT_DETAILS) {
3886 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3887 "policyFlags=0x%x, action=0x%x, "
3888 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3889 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3890 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3891 args->downTime);
3892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 if (!validateKeyEvent(args->action)) {
3894 return;
3895 }
3896
3897 uint32_t policyFlags = args->policyFlags;
3898 int32_t flags = args->flags;
3899 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003900 // InputDispatcher tracks and generates key repeats on behalf of
3901 // whatever notifies it, so repeatCount should always be set to 0
3902 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3904 policyFlags |= POLICY_FLAG_VIRTUAL;
3905 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 if (policyFlags & POLICY_FLAG_FUNCTION) {
3908 metaState |= AMETA_FUNCTION_ON;
3909 }
3910
3911 policyFlags |= POLICY_FLAG_TRUSTED;
3912
Michael Wright78f24442014-08-06 15:55:28 -07003913 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003914 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003915
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003917 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003918 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3919 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920
Michael Wright2b3c3302018-03-02 17:19:13 +00003921 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003923 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3924 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
Antonio Kantekf16f2832021-09-28 04:39:20 +00003928 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 { // acquire lock
3930 mLock.lock();
3931
3932 if (shouldSendKeyToInputFilterLocked(args)) {
3933 mLock.unlock();
3934
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003935 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3937 return; // event was consumed by the filter
3938 }
3939
3940 mLock.lock();
3941 }
3942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003943 std::unique_ptr<KeyEntry> newEntry =
3944 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3945 args->displayId, policyFlags, args->action, flags,
3946 keyCode, args->scanCode, metaState, repeatCount,
3947 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003949 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 mLock.unlock();
3951 } // release lock
3952
3953 if (needWake) {
3954 mLooper->wake();
3955 }
3956}
3957
3958bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3959 return mInputFilterEnabled;
3960}
3961
3962void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003963 if (DEBUG_INBOUND_EVENT_DETAILS) {
3964 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3965 "displayId=%" PRId32 ", policyFlags=0x%x, "
3966 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3967 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3968 "yCursorPosition=%f, downTime=%" PRId64,
3969 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3970 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3971 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3972 args->xCursorPosition, args->yCursorPosition, args->downTime);
3973 for (uint32_t i = 0; i < args->pointerCount; i++) {
3974 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3975 "x=%f, y=%f, pressure=%f, size=%f, "
3976 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3977 "orientation=%f",
3978 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3979 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3980 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3981 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3982 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3983 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3984 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3985 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3986 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3987 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3991 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 return;
3993 }
3994
3995 uint32_t policyFlags = args->policyFlags;
3996 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003997
3998 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003999 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004000 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4001 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004002 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Antonio Kantekf16f2832021-09-28 04:39:20 +00004005 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 { // acquire lock
4007 mLock.lock();
4008
4009 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004010 ui::Transform displayTransform;
4011 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4012 displayTransform = it->second.transform;
4013 }
4014
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 mLock.unlock();
4016
4017 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004018 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4019 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004020 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004021 displayTransform, args->xPrecision, args->yPrecision,
4022 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004023 args->downTime, args->eventTime, args->pointerCount,
4024 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
4026 policyFlags |= POLICY_FLAG_FILTERED;
4027 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4028 return; // event was consumed by the filter
4029 }
4030
4031 mLock.lock();
4032 }
4033
4034 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004035 std::unique_ptr<MotionEntry> newEntry =
4036 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4037 args->source, args->displayId, policyFlags,
4038 args->action, args->actionButton, args->flags,
4039 args->metaState, args->buttonState,
4040 args->classification, args->edgeFlags,
4041 args->xPrecision, args->yPrecision,
4042 args->xCursorPosition, args->yCursorPosition,
4043 args->downTime, args->pointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00004044 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004046 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4047 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4048 !mInputFilterEnabled) {
4049 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4050 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4051 }
4052
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004053 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 mLock.unlock();
4055 } // release lock
4056
4057 if (needWake) {
4058 mLooper->wake();
4059 }
4060}
4061
Chris Yef59a2f42020-10-16 12:55:26 -07004062void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004063 if (DEBUG_INBOUND_EVENT_DETAILS) {
4064 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4065 " sensorType=%s",
4066 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004067 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004068 }
Chris Yef59a2f42020-10-16 12:55:26 -07004069
Antonio Kantekf16f2832021-09-28 04:39:20 +00004070 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004071 { // acquire lock
4072 mLock.lock();
4073
4074 // Just enqueue a new sensor event.
4075 std::unique_ptr<SensorEntry> newEntry =
4076 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4077 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4078 args->sensorType, args->accuracy,
4079 args->accuracyChanged, args->values);
4080
4081 needWake = enqueueInboundEventLocked(std::move(newEntry));
4082 mLock.unlock();
4083 } // release lock
4084
4085 if (needWake) {
4086 mLooper->wake();
4087 }
4088}
4089
Chris Yefb552902021-02-03 17:18:37 -08004090void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004091 if (DEBUG_INBOUND_EVENT_DETAILS) {
4092 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4093 args->deviceId, args->isOn);
4094 }
Chris Yefb552902021-02-03 17:18:37 -08004095 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4096}
4097
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004099 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100}
4101
4102void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004103 if (DEBUG_INBOUND_EVENT_DETAILS) {
4104 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4105 "switchMask=0x%08x",
4106 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108
4109 uint32_t policyFlags = args->policyFlags;
4110 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004111 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112}
4113
4114void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004115 if (DEBUG_INBOUND_EVENT_DETAILS) {
4116 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4117 args->deviceId);
4118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
Antonio Kantekf16f2832021-09-28 04:39:20 +00004120 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004122 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004124 std::unique_ptr<DeviceResetEntry> newEntry =
4125 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4126 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 } // release lock
4128
4129 if (needWake) {
4130 mLooper->wake();
4131 }
4132}
4133
Prabir Pradhan7e186182020-11-10 13:56:45 -08004134void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004135 if (DEBUG_INBOUND_EVENT_DETAILS) {
4136 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004137 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004138 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004139
Antonio Kantekf16f2832021-09-28 04:39:20 +00004140 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004141 { // acquire lock
4142 std::scoped_lock _l(mLock);
4143 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004144 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004145 needWake = enqueueInboundEventLocked(std::move(entry));
4146 } // release lock
4147
4148 if (needWake) {
4149 mLooper->wake();
4150 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004151}
4152
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004153InputEventInjectionResult InputDispatcher::injectInputEvent(
4154 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4155 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004156 if (DEBUG_INBOUND_EVENT_DETAILS) {
4157 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4158 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4159 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4160 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004161 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
4163 policyFlags |= POLICY_FLAG_INJECTED;
4164 if (hasInjectionPermission(injectorPid, injectorUid)) {
4165 policyFlags |= POLICY_FLAG_TRUSTED;
4166 }
4167
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004168 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004169 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4170 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4171 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4172 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4173 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004174 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004175 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004177 }
4178
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004182 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4183 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004185 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004188 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004189 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4190 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4191 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004192 int32_t keyCode = incomingKey.getKeyCode();
4193 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004194 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004196 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004197 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004198 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4199 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4200 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4203 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004204 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205
4206 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4207 android::base::Timer t;
4208 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4209 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4210 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4211 std::to_string(t.duration().count()).c_str());
4212 }
4213 }
4214
4215 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004216 std::unique_ptr<KeyEntry> injectedEntry =
4217 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004218 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004219 incomingKey.getDisplayId(), policyFlags, action,
4220 flags, keyCode, incomingKey.getScanCode(), metaState,
4221 incomingKey.getRepeatCount(),
4222 incomingKey.getDownTime());
4223 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 }
4226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004229 const int32_t action = motionEvent.getAction();
4230 const bool isPointerEvent =
4231 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4232 // If a pointer event has no displayId specified, inject it to the default display.
4233 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4234 ? ADISPLAY_ID_DEFAULT
4235 : event->getDisplayId();
4236 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004238 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004239 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004241 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 }
4243
4244 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004245 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 android::base::Timer t;
4247 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4248 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4249 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4250 std::to_string(t.duration().count()).c_str());
4251 }
4252 }
4253
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004254 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4255 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4256 }
4257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004259 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4260 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004261 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4263 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004264 displayId, policyFlags, action, actionButton,
4265 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004266 motionEvent.getButtonState(),
4267 motionEvent.getClassification(),
4268 motionEvent.getEdgeFlags(),
4269 motionEvent.getXPrecision(),
4270 motionEvent.getYPrecision(),
4271 motionEvent.getRawXCursorPosition(),
4272 motionEvent.getRawYCursorPosition(),
4273 motionEvent.getDownTime(), uint32_t(pointerCount),
Alex Chau663fc832021-12-03 10:37:54 +00004274 pointerProperties, samplePointerCoords,
4275 motionEvent.getXOffset(),
4276 motionEvent.getYOffset());
4277 transformMotionEntryForInjectionLocked(*injectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 sampleEventTimes += 1;
4281 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4284 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004285 displayId, policyFlags, action, actionButton,
4286 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 motionEvent.getButtonState(),
4288 motionEvent.getClassification(),
4289 motionEvent.getEdgeFlags(),
4290 motionEvent.getXPrecision(),
4291 motionEvent.getYPrecision(),
4292 motionEvent.getRawXCursorPosition(),
4293 motionEvent.getRawYCursorPosition(),
4294 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 uint32_t(pointerCount), pointerProperties,
Alex Chau663fc832021-12-03 10:37:54 +00004296 samplePointerCoords, motionEvent.getXOffset(),
4297 motionEvent.getYOffset());
4298 transformMotionEntryForInjectionLocked(*nextInjectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 }
4301 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004305 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308
4309 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 injectionState->injectionIsAsync = true;
4312 }
4313
4314 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004315 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
4317 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004318 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004320 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322
4323 mLock.unlock();
4324
4325 if (needWake) {
4326 mLooper->wake();
4327 }
4328
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004331 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 if (syncMode == InputEventInjectionSync::NONE) {
4334 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 } else {
4336 for (;;) {
4337 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004338 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 break;
4340 }
4341
4342 nsecs_t remainingTimeout = endTime - now();
4343 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004344 if (DEBUG_INJECTION) {
4345 ALOGD("injectInputEvent - Timed out waiting for injection result "
4346 "to become available.");
4347 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004348 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 break;
4350 }
4351
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004352 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
4354
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4356 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 if (DEBUG_INJECTION) {
4359 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4360 injectionState->pendingForegroundDispatches);
4361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 nsecs_t remainingTimeout = endTime - now();
4363 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004364 if (DEBUG_INJECTION) {
4365 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4366 "dispatches to finish.");
4367 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 break;
4370 }
4371
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004372 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374 }
4375 }
4376
4377 injectionState->release();
4378 } // release lock
4379
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004380 if (DEBUG_INJECTION) {
4381 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4382 injectionResult, injectorPid, injectorUid);
4383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384
4385 return injectionResult;
4386}
4387
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004388std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004389 std::array<uint8_t, 32> calculatedHmac;
4390 std::unique_ptr<VerifiedInputEvent> result;
4391 switch (event.getType()) {
4392 case AINPUT_EVENT_TYPE_KEY: {
4393 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4394 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4395 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004396 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004397 break;
4398 }
4399 case AINPUT_EVENT_TYPE_MOTION: {
4400 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4401 VerifiedMotionEvent verifiedMotionEvent =
4402 verifiedMotionEventFromMotionEvent(motionEvent);
4403 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004404 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004405 break;
4406 }
4407 default: {
4408 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4409 return nullptr;
4410 }
4411 }
4412 if (calculatedHmac == INVALID_HMAC) {
4413 return nullptr;
4414 }
4415 if (calculatedHmac != event.getHmac()) {
4416 return nullptr;
4417 }
4418 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004419}
4420
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 return injectorUid == 0 ||
4423 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424}
4425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004428 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 if (DEBUG_INJECTION) {
4431 ALOGD("Setting input event injection result to %d. "
4432 "injectorPid=%d, injectorUid=%d",
4433 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 // Log the outcome since the injector did not wait for the injection result.
4438 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004439 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 ALOGV("Asynchronous input event injection succeeded.");
4441 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 ALOGW("Asynchronous input event injection failed.");
4444 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004445 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004446 ALOGW("Asynchronous input event injection permission denied.");
4447 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 ALOGW("Asynchronous input event injection timed out.");
4450 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 case InputEventInjectionResult::PENDING:
4452 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4453 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 }
4455 }
4456
4457 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004458 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460}
4461
Alex Chau663fc832021-12-03 10:37:54 +00004462void InputDispatcher::transformMotionEntryForInjectionLocked(MotionEntry& entry) const {
4463 const bool isRelativeMouseEvent = isFromSource(entry.source, AINPUT_SOURCE_MOUSE_RELATIVE);
4464 if (!isRelativeMouseEvent && !isFromSource(entry.source, AINPUT_SOURCE_CLASS_POINTER)) {
4465 return;
4466 }
4467
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004468 // Input injection works in the logical display coordinate space, but the input pipeline works
4469 // display space, so we need to transform the injected events accordingly.
4470 const auto it = mDisplayInfos.find(entry.displayId);
4471 if (it == mDisplayInfos.end()) return;
Alex Chau663fc832021-12-03 10:37:54 +00004472 const auto& transformToDisplay = it->second.transform.inverse();
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004473
4474 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4475 PointerCoords& pc = entry.pointerCoords[i];
Alex Chau663fc832021-12-03 10:37:54 +00004476 const auto xy = isRelativeMouseEvent
4477 ? transformWithoutTranslation(transformToDisplay, pc.getX(), pc.getY())
4478 : transformToDisplay.transform(pc.getXYValue());
4479 pc.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
4480 pc.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004481
Alex Chau663fc832021-12-03 10:37:54 +00004482 // Axes with relative values never represent points on a screen, so they should never have
4483 // translation applied. If a device does not report relative values, these values are always
4484 // 0, and will remain unaffected by the following operation.
4485 const auto rel =
4486 transformWithoutTranslation(transformToDisplay,
4487 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
4488 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4489 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, rel.x);
4490 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, rel.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004491 }
4492}
4493
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004494void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4495 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 if (injectionState) {
4497 injectionState->pendingForegroundDispatches += 1;
4498 }
4499}
4500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004501void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4502 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 if (injectionState) {
4504 injectionState->pendingForegroundDispatches -= 1;
4505
4506 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004507 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 }
4509 }
4510}
4511
chaviw98318de2021-05-19 16:45:23 -05004512const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004513 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004514 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004515 auto it = mWindowHandlesByDisplay.find(displayId);
4516 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004517}
4518
chaviw98318de2021-05-19 16:45:23 -05004519sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004520 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004521 if (windowHandleToken == nullptr) {
4522 return nullptr;
4523 }
4524
Arthur Hungb92218b2018-08-14 12:00:21 +08004525 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004526 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4527 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004528 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004529 return windowHandle;
4530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 }
4532 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004533 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534}
4535
chaviw98318de2021-05-19 16:45:23 -05004536sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4537 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004538 if (windowHandleToken == nullptr) {
4539 return nullptr;
4540 }
4541
chaviw98318de2021-05-19 16:45:23 -05004542 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004543 if (windowHandle->getToken() == windowHandleToken) {
4544 return windowHandle;
4545 }
4546 }
4547 return nullptr;
4548}
4549
chaviw98318de2021-05-19 16:45:23 -05004550sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4551 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004552 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004553 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4554 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004555 if (handle->getId() == windowHandle->getId() &&
4556 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004557 if (windowHandle->getInfo()->displayId != it.first) {
4558 ALOGE("Found window %s in display %" PRId32
4559 ", but it should belong to display %" PRId32,
4560 windowHandle->getName().c_str(), it.first,
4561 windowHandle->getInfo()->displayId);
4562 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004563 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 }
4566 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004567 return nullptr;
4568}
4569
chaviw98318de2021-05-19 16:45:23 -05004570sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004571 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4572 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573}
4574
chaviw98318de2021-05-19 16:45:23 -05004575bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004576 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4577 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004578 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004579 if (connection != nullptr && noInputChannel) {
4580 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4581 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4582 return false;
4583 }
4584
4585 if (connection == nullptr) {
4586 if (!noInputChannel) {
4587 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4588 }
4589 return false;
4590 }
4591 if (!connection->responsive) {
4592 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4593 return false;
4594 }
4595 return true;
4596}
4597
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004598std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4599 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004600 auto connectionIt = mConnectionsByToken.find(token);
4601 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004602 return nullptr;
4603 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004604 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004605}
4606
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004607void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004608 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4609 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004610 // Remove all handles on a display if there are no windows left.
4611 mWindowHandlesByDisplay.erase(displayId);
4612 return;
4613 }
4614
4615 // Since we compare the pointer of input window handles across window updates, we need
4616 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004617 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4618 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4619 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004620 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004621 }
4622
chaviw98318de2021-05-19 16:45:23 -05004623 std::vector<sp<WindowInfoHandle>> newHandles;
4624 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004625 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004626 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004627 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004628 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4629 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4630 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004631 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004632 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004633 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004634 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004635 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004636 }
4637
4638 if (info->displayId != displayId) {
4639 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4640 handle->getName().c_str(), displayId, info->displayId);
4641 continue;
4642 }
4643
Robert Carredd13602020-04-13 17:24:34 -07004644 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4645 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004646 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004647 oldHandle->updateFrom(handle);
4648 newHandles.push_back(oldHandle);
4649 } else {
4650 newHandles.push_back(handle);
4651 }
4652 }
4653
4654 // Insert or replace
4655 mWindowHandlesByDisplay[displayId] = newHandles;
4656}
4657
Arthur Hung72d8dc32020-03-28 00:48:39 +00004658void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004659 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004660 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004661 { // acquire lock
4662 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004663 for (const auto& [displayId, handles] : handlesPerDisplay) {
4664 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004665 }
4666 }
4667 // Wake up poll loop since it may need to make new input dispatching choices.
4668 mLooper->wake();
4669}
4670
Arthur Hungb92218b2018-08-14 12:00:21 +08004671/**
4672 * Called from InputManagerService, update window handle list by displayId that can receive input.
4673 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4674 * If set an empty list, remove all handles from the specific display.
4675 * For focused handle, check if need to change and send a cancel event to previous one.
4676 * For removed handle, check if need to send a cancel event if already in touch.
4677 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004678void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004679 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004680 if (DEBUG_FOCUS) {
4681 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004682 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004683 windowList += iwh->getName() + " ";
4684 }
4685 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004688 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004689 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004690 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004691 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004692 if (noInputWindow && window->getToken() != nullptr) {
4693 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4694 window->getName().c_str());
4695 window->releaseChannel();
4696 }
4697 }
4698
Arthur Hung72d8dc32020-03-28 00:48:39 +00004699 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004700 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004702 // Save the old windows' orientation by ID before it gets updated.
4703 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004704 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004705 oldWindowOrientations.emplace(handle->getId(),
4706 handle->getInfo()->transform.getOrientation());
4707 }
4708
chaviw98318de2021-05-19 16:45:23 -05004709 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004710
chaviw98318de2021-05-19 16:45:23 -05004711 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004712 if (mLastHoverWindowHandle &&
4713 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4714 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004715 mLastHoverWindowHandle = nullptr;
4716 }
4717
Vishnu Nairc519ff72021-01-21 08:23:08 -08004718 std::optional<FocusResolver::FocusChanges> changes =
4719 mFocusResolver.setInputWindows(displayId, windowHandles);
4720 if (changes) {
4721 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004724 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4725 mTouchStatesByDisplay.find(displayId);
4726 if (stateIt != mTouchStatesByDisplay.end()) {
4727 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728 for (size_t i = 0; i < state.windows.size();) {
4729 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004730 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004731 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004732 ALOGD("Touched window was removed: %s in display %" PRId32,
4733 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004734 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004735 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4737 if (touchedInputChannel != nullptr) {
4738 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4739 "touched window was removed");
4740 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004741 // Since we are about to drop the touch, cancel the events for the wallpaper as
4742 // well.
4743 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4744 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4745 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4746 if (wallpaper != nullptr) {
4747 sp<Connection> wallpaperConnection =
4748 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004749 if (wallpaperConnection != nullptr) {
4750 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4751 options);
4752 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004753 }
4754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004756 state.windows.erase(state.windows.begin() + i);
4757 } else {
4758 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 }
4760 }
arthurhungb89ccb02020-12-30 16:19:01 +08004761
arthurhung6d4bed92021-03-17 11:59:33 +08004762 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004763 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004764 if (mDragState &&
4765 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004766 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004767 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004768 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004769 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004770
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004771 // Determine if the orientation of any of the input windows have changed, and cancel all
4772 // pointer events if necessary.
4773 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4774 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4775 if (newWindowHandle != nullptr &&
4776 newWindowHandle->getInfo()->transform.getOrientation() !=
4777 oldWindowOrientations[oldWindowHandle->getId()]) {
4778 std::shared_ptr<InputChannel> inputChannel =
4779 getInputChannelLocked(newWindowHandle->getToken());
4780 if (inputChannel != nullptr) {
4781 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4782 "touched window's orientation changed");
4783 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004784 }
4785 }
4786 }
4787
Arthur Hung72d8dc32020-03-28 00:48:39 +00004788 // Release information for windows that are no longer present.
4789 // This ensures that unused input channels are released promptly.
4790 // Otherwise, they might stick around until the window handle is destroyed
4791 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004792 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004793 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004794 if (DEBUG_FOCUS) {
4795 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004796 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004797 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004798 // To avoid making too many calls into the compat framework, only
4799 // check for window flags when windows are going away.
4800 // TODO(b/157929241) : delete this. This is only needed temporarily
4801 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004802 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004803 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4804 oldWindowHandle->getName().c_str());
4805 if (mCompatService != nullptr) {
4806 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4807 oldWindowHandle->getInfo()->ownerUid);
4808 }
4809 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004810 }
chaviw291d88a2019-02-14 10:33:58 -08004811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812}
4813
4814void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004815 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004816 if (DEBUG_FOCUS) {
4817 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4818 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4819 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004820 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004821 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004822 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 } // release lock
4824
4825 // Wake up poll loop since it may need to make new input dispatching choices.
4826 mLooper->wake();
4827}
4828
Vishnu Nair599f1412021-06-21 10:39:58 -07004829void InputDispatcher::setFocusedApplicationLocked(
4830 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4831 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4832 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4833
4834 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4835 return; // This application is already focused. No need to wake up or change anything.
4836 }
4837
4838 // Set the new application handle.
4839 if (inputApplicationHandle != nullptr) {
4840 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4841 } else {
4842 mFocusedApplicationHandlesByDisplay.erase(displayId);
4843 }
4844
4845 // No matter what the old focused application was, stop waiting on it because it is
4846 // no longer focused.
4847 resetNoFocusedWindowTimeoutLocked();
4848}
4849
Tiger Huang721e26f2018-07-24 22:26:19 +08004850/**
4851 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4852 * the display not specified.
4853 *
4854 * We track any unreleased events for each window. If a window loses the ability to receive the
4855 * released event, we will send a cancel event to it. So when the focused display is changed, we
4856 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4857 * display. The display-specified events won't be affected.
4858 */
4859void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004860 if (DEBUG_FOCUS) {
4861 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4862 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004863 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004864 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004865
4866 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004867 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004868 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004869 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004870 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004871 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004872 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004873 CancelationOptions
4874 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4875 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004876 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004877 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4878 }
4879 }
4880 mFocusedDisplayId = displayId;
4881
Chris Ye3c2d6f52020-08-09 10:39:48 -07004882 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004883 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004884 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004885
Vishnu Nairad321cd2020-08-20 16:40:21 -07004886 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004887 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004888 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004889 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004890 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004891 }
4892 }
4893 }
4894
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004895 if (DEBUG_FOCUS) {
4896 logDispatchStateLocked();
4897 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004898 } // release lock
4899
4900 // Wake up poll loop since it may need to make new input dispatching choices.
4901 mLooper->wake();
4902}
4903
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004905 if (DEBUG_FOCUS) {
4906 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
4909 bool changed;
4910 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004911 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
4913 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4914 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004915 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 }
4917
4918 if (mDispatchEnabled && !enabled) {
4919 resetAndDropEverythingLocked("dispatcher is being disabled");
4920 }
4921
4922 mDispatchEnabled = enabled;
4923 mDispatchFrozen = frozen;
4924 changed = true;
4925 } else {
4926 changed = false;
4927 }
4928
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004929 if (DEBUG_FOCUS) {
4930 logDispatchStateLocked();
4931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 } // release lock
4933
4934 if (changed) {
4935 // Wake up poll loop since it may need to make new input dispatching choices.
4936 mLooper->wake();
4937 }
4938}
4939
4940void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004941 if (DEBUG_FOCUS) {
4942 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944
4945 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004946 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
4948 if (mInputFilterEnabled == enabled) {
4949 return;
4950 }
4951
4952 mInputFilterEnabled = enabled;
4953 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4954 } // release lock
4955
4956 // Wake up poll loop since there might be work to do to drop everything.
4957 mLooper->wake();
4958}
4959
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004960void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004961 bool needWake = false;
4962 {
4963 std::scoped_lock lock(mLock);
4964 if (mInTouchMode == inTouchMode) {
4965 return;
4966 }
4967 if (DEBUG_TOUCH_MODE) {
4968 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4969 toString(inTouchMode));
4970 // TODO(b/198487159): Also print the current last interacted apps.
4971 }
4972
4973 // TODO(b/198499018): Store touch mode per display.
4974 mInTouchMode = inTouchMode;
4975
4976 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4977 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4978 needWake = enqueueInboundEventLocked(std::move(entry));
4979 } // release lock
4980
4981 if (needWake) {
4982 mLooper->wake();
4983 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004984}
4985
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004986void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4987 if (opacity < 0 || opacity > 1) {
4988 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4989 return;
4990 }
4991
4992 std::scoped_lock lock(mLock);
4993 mMaximumObscuringOpacityForTouch = opacity;
4994}
4995
4996void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4997 std::scoped_lock lock(mLock);
4998 mBlockUntrustedTouchesMode = mode;
4999}
5000
Arthur Hungabbb9d82021-09-01 14:52:30 +00005001std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5002 const sp<IBinder>& token) {
5003 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5004 for (TouchedWindow& w : state.windows) {
5005 if (w.windowHandle->getToken() == token) {
5006 return std::make_pair(&state, &w);
5007 }
5008 }
5009 }
5010 return std::make_pair(nullptr, nullptr);
5011}
5012
arthurhungb89ccb02020-12-30 16:19:01 +08005013bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5014 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005015 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005016 if (DEBUG_FOCUS) {
5017 ALOGD("Trivial transfer to same window.");
5018 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005019 return true;
5020 }
5021
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005023 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024
Arthur Hungabbb9d82021-09-01 14:52:30 +00005025 // Find the target touch state and touched window by fromToken.
5026 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5027 if (state == nullptr || touchedWindow == nullptr) {
5028 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 return false;
5030 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005031
5032 const int32_t displayId = state->displayId;
5033 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5034 if (toWindowHandle == nullptr) {
5035 ALOGW("Cannot transfer focus because to window not found.");
5036 return false;
5037 }
5038
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005039 if (DEBUG_FOCUS) {
5040 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005041 touchedWindow->windowHandle->getName().c_str(),
5042 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 }
5044
Arthur Hungabbb9d82021-09-01 14:52:30 +00005045 // Erase old window.
5046 int32_t oldTargetFlags = touchedWindow->targetFlags;
5047 BitSet32 pointerIds = touchedWindow->pointerIds;
5048 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049
Arthur Hungabbb9d82021-09-01 14:52:30 +00005050 // Add new window.
5051 int32_t newTargetFlags = oldTargetFlags &
5052 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5053 InputTarget::FLAG_DISPATCH_AS_IS);
5054 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055
Arthur Hungabbb9d82021-09-01 14:52:30 +00005056 // Store the dragging window.
5057 if (isDragDrop) {
5058 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 }
5060
Arthur Hungabbb9d82021-09-01 14:52:30 +00005061 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005062 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5063 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005064 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005065 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005066 CancelationOptions
5067 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5068 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005070 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
5072
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005073 if (DEBUG_FOCUS) {
5074 logDispatchStateLocked();
5075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 } // release lock
5077
5078 // Wake up poll loop since it may need to make new input dispatching choices.
5079 mLooper->wake();
5080 return true;
5081}
5082
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005083// Binder call
5084bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5085 sp<IBinder> fromToken;
5086 { // acquire lock
5087 std::scoped_lock _l(mLock);
5088
Arthur Hungabbb9d82021-09-01 14:52:30 +00005089 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5090 [](const auto& pair) { return pair.second.windows.size() == 1; });
5091 if (it == mTouchStatesByDisplay.end()) {
5092 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5093 return false;
5094 }
5095 const int32_t displayId = it->first;
5096 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005097 if (toWindowHandle == nullptr) {
5098 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5099 return false;
5100 }
5101
Arthur Hungabbb9d82021-09-01 14:52:30 +00005102 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005103 const TouchedWindow& touchedWindow = state.windows[0];
5104 fromToken = touchedWindow.windowHandle->getToken();
5105 } // release lock
5106
5107 return transferTouchFocus(fromToken, destChannelToken);
5108}
5109
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005111 if (DEBUG_FOCUS) {
5112 ALOGD("Resetting and dropping all events (%s).", reason);
5113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114
5115 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5116 synthesizeCancelationEventsForAllConnectionsLocked(options);
5117
5118 resetKeyRepeatLocked();
5119 releasePendingEventLocked();
5120 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005123 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005124 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005126 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127}
5128
5129void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005130 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 dumpDispatchStateLocked(dump);
5132
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005133 std::istringstream stream(dump);
5134 std::string line;
5135
5136 while (std::getline(stream, line, '\n')) {
5137 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 }
5139}
5140
Prabir Pradhan99987712020-11-10 18:43:05 -08005141std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5142 std::string dump;
5143
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005144 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5145 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005146
5147 std::string windowName = "None";
5148 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005149 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005150 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5151 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5152 : "token has capture without window";
5153 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005154 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005155
5156 return dump;
5157}
5158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005159void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005160 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5161 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5162 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005163 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164
Tiger Huang721e26f2018-07-24 22:26:19 +08005165 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5166 dump += StringPrintf(INDENT "FocusedApplications:\n");
5167 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5168 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005169 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005170 const std::chrono::duration timeout =
5171 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005172 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005173 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005174 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005177 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005179
Vishnu Nairc519ff72021-01-21 08:23:08 -08005180 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005181 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005183 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005184 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005185 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5186 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005187 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005188 state.displayId, toString(state.down), toString(state.split),
5189 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005190 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005191 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005192 for (size_t i = 0; i < state.windows.size(); i++) {
5193 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005194 dump += StringPrintf(INDENT4
5195 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5196 i, touchedWindow.windowHandle->getName().c_str(),
5197 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005198 }
5199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005200 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 }
5203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005204 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 }
5206
arthurhung6d4bed92021-03-17 11:59:33 +08005207 if (mDragState) {
5208 dump += StringPrintf(INDENT "DragState:\n");
5209 mDragState->dump(dump, INDENT2);
5210 }
5211
Arthur Hungb92218b2018-08-14 12:00:21 +08005212 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005213 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5214 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5215 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5216 const auto& displayInfo = it->second;
5217 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5218 displayInfo.logicalHeight);
5219 displayInfo.transform.dump(dump, "transform", INDENT4);
5220 } else {
5221 dump += INDENT2 "No DisplayInfo found!\n";
5222 }
5223
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005224 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005225 dump += INDENT2 "Windows:\n";
5226 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005227 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5228 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005230 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005231 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005232 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005233 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005234 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005235 "applicationInfo.name=%s, "
5236 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005237 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005238 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005239 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005240 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005241 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005242 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005243 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005244 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005245 windowInfo->frameLeft, windowInfo->frameTop,
5246 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005247 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005248 windowInfo->applicationInfo.name.c_str(),
5249 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005250 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005251 dump += StringPrintf(", inputFeatures=%s",
5252 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005253 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005254 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005255 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005256 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005257 millis(windowInfo->dispatchingTimeout),
5258 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005259 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005260 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005261 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005262 }
5263 } else {
5264 dump += INDENT2 "Windows: <none>\n";
5265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 }
5267 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005268 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 }
5270
Michael Wright3dd60e22019-03-27 22:06:44 +00005271 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005272 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005273 const std::vector<Monitor>& monitors = it.second;
5274 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5275 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005276 }
5277 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005278 const std::vector<Monitor>& monitors = it.second;
5279 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5280 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005283 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 }
5285
5286 nsecs_t currentTime = now();
5287
5288 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005289 if (!mRecentQueue.empty()) {
5290 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005291 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005292 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005293 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005294 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 }
5296 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005297 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 }
5299
5300 // Dump event currently being dispatched.
5301 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005302 dump += INDENT "PendingEvent:\n";
5303 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005304 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005305 dump += StringPrintf(", age=%" PRId64 "ms\n",
5306 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 }
5310
5311 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005312 if (!mInboundQueue.empty()) {
5313 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005314 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005315 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005316 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005317 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 }
5319 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005320 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 }
5322
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005323 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005324 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005325 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5326 const KeyReplacement& replacement = pair.first;
5327 int32_t newKeyCode = pair.second;
5328 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005330 }
5331 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005332 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005333 }
5334
Prabir Pradhancef936d2021-07-21 16:17:52 +00005335 if (!mCommandQueue.empty()) {
5336 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5337 } else {
5338 dump += INDENT "CommandQueue: <empty>\n";
5339 }
5340
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005341 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005342 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005343 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005344 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005345 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005346 connection->inputChannel->getFd().get(),
5347 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005348 connection->getWindowName().c_str(),
5349 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005350 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005352 if (!connection->outboundQueue.empty()) {
5353 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5354 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005355 dump += dumpQueue(connection->outboundQueue, currentTime);
5356
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005358 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 }
5360
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005361 if (!connection->waitQueue.empty()) {
5362 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5363 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005364 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005366 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 }
5368 }
5369 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005370 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 }
5372
5373 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005374 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5375 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005377 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 }
5379
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005380 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005381 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5382 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5383 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005384 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005385 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386}
5387
Michael Wright3dd60e22019-03-27 22:06:44 +00005388void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5389 const size_t numMonitors = monitors.size();
5390 for (size_t i = 0; i < numMonitors; i++) {
5391 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005392 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005393 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5394 dump += "\n";
5395 }
5396}
5397
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005398class LooperEventCallback : public LooperCallback {
5399public:
5400 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5401 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5402
5403private:
5404 std::function<int(int events)> mCallback;
5405};
5406
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005407Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005408 if (DEBUG_CHANNEL_CREATION) {
5409 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005412 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005413 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005414 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005415
5416 if (result) {
5417 return base::Error(result) << "Failed to open input channel pair with name " << name;
5418 }
5419
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005421 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005422 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005423 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005424 sp<Connection> connection =
5425 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005427 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5428 ALOGE("Created a new connection, but the token %p is already known", token.get());
5429 }
5430 mConnectionsByToken.emplace(token, connection);
5431
5432 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5433 this, std::placeholders::_1, token);
5434
5435 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 } // release lock
5437
5438 // Wake the looper because some connections have changed.
5439 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005440 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441}
5442
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005443Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5444 bool isGestureMonitor,
5445 const std::string& name,
5446 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005447 std::shared_ptr<InputChannel> serverChannel;
5448 std::unique_ptr<InputChannel> clientChannel;
5449 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5450 if (result) {
5451 return base::Error(result) << "Failed to open input channel pair with name " << name;
5452 }
5453
Michael Wright3dd60e22019-03-27 22:06:44 +00005454 { // acquire lock
5455 std::scoped_lock _l(mLock);
5456
5457 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005458 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5459 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005460 }
5461
Garfield Tan15601662020-09-22 15:32:38 -07005462 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005463 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005464 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005465
5466 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5467 ALOGE("Created a new connection, but the token %p is already known", token.get());
5468 }
5469 mConnectionsByToken.emplace(token, connection);
5470 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5471 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005472
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005473 auto& monitorsByDisplay =
5474 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005475 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005476
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005477 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005478 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5479 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005480 }
Garfield Tan15601662020-09-22 15:32:38 -07005481
Michael Wright3dd60e22019-03-27 22:06:44 +00005482 // Wake the looper because some connections have changed.
5483 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005484 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005485}
5486
Garfield Tan15601662020-09-22 15:32:38 -07005487status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005489 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490
Garfield Tan15601662020-09-22 15:32:38 -07005491 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 if (status) {
5493 return status;
5494 }
5495 } // release lock
5496
5497 // Wake the poll loop because removing the connection may have changed the current
5498 // synchronization state.
5499 mLooper->wake();
5500 return OK;
5501}
5502
Garfield Tan15601662020-09-22 15:32:38 -07005503status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5504 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005505 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005506 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005507 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 return BAD_VALUE;
5509 }
5510
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005511 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005512
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005514 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 }
5516
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005517 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518
5519 nsecs_t currentTime = now();
5520 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5521
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005522 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 return OK;
5524}
5525
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005526void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5527 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5528 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005529}
5530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005531void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005532 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005533 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005534 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005535 std::vector<Monitor>& monitors = it->second;
5536 const size_t numMonitors = monitors.size();
5537 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005538 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005539 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5540 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005541 monitors.erase(monitors.begin() + i);
5542 break;
5543 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005544 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005545 if (monitors.empty()) {
5546 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005547 } else {
5548 ++it;
5549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 }
5551}
5552
Michael Wright3dd60e22019-03-27 22:06:44 +00005553status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5554 { // acquire lock
5555 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005556
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005557 TouchState* statePtr = nullptr;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005558 std::shared_ptr<InputChannel> requestingChannel;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005559 int32_t displayId;
5560 int32_t deviceId;
5561 const std::optional<int32_t> foundGestureMonitorDisplayId =
5562 findGestureMonitorDisplayByTokenLocked(token);
5563
5564 // TODO: Optimize this function for pilfering from windows when removing gesture monitors.
5565 if (foundGestureMonitorDisplayId) {
5566 // A gesture monitor has requested to pilfer pointers.
5567 displayId = *foundGestureMonitorDisplayId;
5568 auto stateIt = mTouchStatesByDisplay.find(displayId);
5569 if (stateIt == mTouchStatesByDisplay.end()) {
5570 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5571 return BAD_VALUE;
5572 }
5573 statePtr = &stateIt->second;
5574
5575 for (const auto& monitor : statePtr->gestureMonitors) {
5576 if (monitor.inputChannel->getConnectionToken() == token) {
5577 requestingChannel = monitor.inputChannel;
5578 deviceId = statePtr->deviceId;
5579 }
5580 }
5581 } else {
5582 // Check if a window has requested to pilfer pointers.
5583 for (auto& [curDisplayId, state] : mTouchStatesByDisplay) {
5584 const sp<WindowInfoHandle>& windowHandle = state.getWindow(token);
5585 if (windowHandle != nullptr) {
5586 displayId = curDisplayId;
5587 requestingChannel = getInputChannelLocked(token);
5588 deviceId = state.deviceId;
5589 statePtr = &state;
5590 break;
5591 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005592 }
5593 }
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005594
5595 if (requestingChannel == nullptr) {
5596 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5597 return BAD_VALUE;
5598 }
5599 TouchState& state = *statePtr;
5600 if (!state.down) {
5601 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005602 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005603 return BAD_VALUE;
5604 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005605
5606 // Send cancel events to all the input channels we're stealing from.
5607 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005608 "input channel stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005609 options.deviceId = deviceId;
5610 options.displayId = displayId;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005611 std::string canceledWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005612 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005613 std::shared_ptr<InputChannel> channel =
5614 getInputChannelLocked(window.windowHandle->getToken());
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005615 if (channel != nullptr && channel->getConnectionToken() != token) {
Michael Wright3a240c42019-12-10 20:53:41 +00005616 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005617 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5618 canceledWindows += channel->getName();
Michael Wright3a240c42019-12-10 20:53:41 +00005619 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005620 }
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005621 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5622 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005623 canceledWindows.c_str());
5624
Michael Wright3dd60e22019-03-27 22:06:44 +00005625 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hungfbfa5722021-11-16 02:45:54 +00005626 state.split = false;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08005627 state.filterWindowsExcept(token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005628 }
5629 return OK;
5630}
5631
Prabir Pradhan99987712020-11-10 18:43:05 -08005632void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5633 { // acquire lock
5634 std::scoped_lock _l(mLock);
5635 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005636 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005637 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5638 windowHandle != nullptr ? windowHandle->getName().c_str()
5639 : "token without window");
5640 }
5641
Vishnu Nairc519ff72021-01-21 08:23:08 -08005642 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005643 if (focusedToken != windowToken) {
5644 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5645 enabled ? "enable" : "disable");
5646 return;
5647 }
5648
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005649 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005650 ALOGW("Ignoring request to %s Pointer Capture: "
5651 "window has %s requested pointer capture.",
5652 enabled ? "enable" : "disable", enabled ? "already" : "not");
5653 return;
5654 }
5655
Prabir Pradhan99987712020-11-10 18:43:05 -08005656 setPointerCaptureLocked(enabled);
5657 } // release lock
5658
5659 // Wake the thread to process command entries.
5660 mLooper->wake();
5661}
5662
Michael Wright3dd60e22019-03-27 22:06:44 +00005663std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5664 const sp<IBinder>& token) {
5665 for (const auto& it : mGestureMonitorsByDisplay) {
5666 const std::vector<Monitor>& monitors = it.second;
5667 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005668 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005669 return it.first;
5670 }
5671 }
5672 }
5673 return std::nullopt;
5674}
5675
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005676std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5677 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5678 if (gesturePid.has_value()) {
5679 return gesturePid;
5680 }
5681 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5682}
5683
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005684sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005685 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005686 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005687 }
5688
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005689 for (const auto& [token, connection] : mConnectionsByToken) {
5690 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005691 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 }
5693 }
Robert Carr4e670e52018-08-15 13:26:12 -07005694
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005695 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696}
5697
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005698std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5699 sp<Connection> connection = getConnectionLocked(connectionToken);
5700 if (connection == nullptr) {
5701 return "<nullptr>";
5702 }
5703 return connection->getInputChannelName();
5704}
5705
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005706void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005707 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005708 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005709}
5710
Prabir Pradhancef936d2021-07-21 16:17:52 +00005711void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5712 const sp<Connection>& connection, uint32_t seq,
5713 bool handled, nsecs_t consumeTime) {
5714 // Handle post-event policy actions.
5715 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5716 if (dispatchEntryIt == connection->waitQueue.end()) {
5717 return;
5718 }
5719 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5720 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5721 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5722 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5723 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5724 }
5725 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5726 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5727 connection->inputChannel->getConnectionToken(),
5728 dispatchEntry->deliveryTime, consumeTime, finishTime);
5729 }
5730
5731 bool restartEvent;
5732 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5733 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5734 restartEvent =
5735 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5736 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5737 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5738 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5739 handled);
5740 } else {
5741 restartEvent = false;
5742 }
5743
5744 // Dequeue the event and start the next cycle.
5745 // Because the lock might have been released, it is possible that the
5746 // contents of the wait queue to have been drained, so we need to double-check
5747 // a few things.
5748 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5749 if (dispatchEntryIt != connection->waitQueue.end()) {
5750 dispatchEntry = *dispatchEntryIt;
5751 connection->waitQueue.erase(dispatchEntryIt);
5752 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5753 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5754 if (!connection->responsive) {
5755 connection->responsive = isConnectionResponsive(*connection);
5756 if (connection->responsive) {
5757 // The connection was unresponsive, and now it's responsive.
5758 processConnectionResponsiveLocked(*connection);
5759 }
5760 }
5761 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005762 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005763 connection->outboundQueue.push_front(dispatchEntry);
5764 traceOutboundQueueLength(*connection);
5765 } else {
5766 releaseDispatchEntry(dispatchEntry);
5767 }
5768 }
5769
5770 // Start the next dispatch cycle for this connection.
5771 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772}
5773
Prabir Pradhancef936d2021-07-21 16:17:52 +00005774void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5775 const sp<IBinder>& newToken) {
5776 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5777 scoped_unlock unlock(mLock);
5778 mPolicy->notifyFocusChanged(oldToken, newToken);
5779 };
5780 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781}
5782
Prabir Pradhancef936d2021-07-21 16:17:52 +00005783void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5784 auto command = [this, token, x, y]() REQUIRES(mLock) {
5785 scoped_unlock unlock(mLock);
5786 mPolicy->notifyDropWindow(token, x, y);
5787 };
5788 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005789}
5790
Prabir Pradhancef936d2021-07-21 16:17:52 +00005791void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5792 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5793 scoped_unlock unlock(mLock);
5794 mPolicy->notifyUntrustedTouch(obscuringPackage);
5795 };
5796 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005797}
5798
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005799void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5800 if (connection == nullptr) {
5801 LOG_ALWAYS_FATAL("Caller must check for nullness");
5802 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5804 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005805 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005806 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005807 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005808 return;
5809 }
5810 /**
5811 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5812 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5813 * has changed. This could cause newer entries to time out before the already dispatched
5814 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5815 * processes the events linearly. So providing information about the oldest entry seems to be
5816 * most useful.
5817 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005818 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005819 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5820 std::string reason =
5821 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005822 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005823 ns2ms(currentWait),
5824 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005825 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005826 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005827
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005828 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5829
5830 // Stop waking up for events on this connection, it is already unresponsive
5831 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005832}
5833
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005834void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5835 std::string reason =
5836 StringPrintf("%s does not have a focused window", application->getName().c_str());
5837 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005838
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5840 scoped_unlock unlock(mLock);
5841 mPolicy->notifyNoFocusedWindowAnr(application);
5842 };
5843 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005844}
5845
chaviw98318de2021-05-19 16:45:23 -05005846void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005847 const std::string& reason) {
5848 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5849 updateLastAnrStateLocked(windowLabel, reason);
5850}
5851
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005852void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5853 const std::string& reason) {
5854 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005855 updateLastAnrStateLocked(windowLabel, reason);
5856}
5857
5858void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5859 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005861 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862 struct tm tm;
5863 localtime_r(&t, &tm);
5864 char timestr[64];
5865 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005866 mLastAnrState.clear();
5867 mLastAnrState += INDENT "ANR:\n";
5868 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005869 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5870 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005871 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872}
5873
Prabir Pradhancef936d2021-07-21 16:17:52 +00005874void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5875 KeyEntry& entry) {
5876 const KeyEvent event = createKeyEvent(entry);
5877 nsecs_t delay = 0;
5878 { // release lock
5879 scoped_unlock unlock(mLock);
5880 android::base::Timer t;
5881 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5882 entry.policyFlags);
5883 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5884 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5885 std::to_string(t.duration().count()).c_str());
5886 }
5887 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888
5889 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005891 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005892 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005894 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5895 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897}
5898
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005900 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5901 scoped_unlock unlock(mLock);
5902 mPolicy->notifyMonitorUnresponsive(pid, reason);
5903 };
5904 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005905}
5906
Prabir Pradhancef936d2021-07-21 16:17:52 +00005907void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005908 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005909 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5910 scoped_unlock unlock(mLock);
5911 mPolicy->notifyWindowUnresponsive(token, reason);
5912 };
5913 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005914}
5915
5916void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005917 auto command = [this, pid]() REQUIRES(mLock) {
5918 scoped_unlock unlock(mLock);
5919 mPolicy->notifyMonitorResponsive(pid);
5920 };
5921 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005922}
5923
Prabir Pradhancef936d2021-07-21 16:17:52 +00005924void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5925 auto command = [this, connectionToken]() REQUIRES(mLock) {
5926 scoped_unlock unlock(mLock);
5927 mPolicy->notifyWindowResponsive(connectionToken);
5928 };
5929 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005930}
5931
5932/**
5933 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5934 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5935 * command entry to the command queue.
5936 */
5937void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5938 std::string reason) {
5939 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5940 if (connection.monitor) {
5941 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5942 reason.c_str());
5943 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5944 if (!pid.has_value()) {
5945 ALOGE("Could not find unresponsive monitor for connection %s",
5946 connection.inputChannel->getName().c_str());
5947 return;
5948 }
5949 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5950 return;
5951 }
5952 // If not a monitor, must be a window
5953 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5954 reason.c_str());
5955 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5956}
5957
5958/**
5959 * Tell the policy that a connection has become responsive so that it can stop ANR.
5960 */
5961void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5962 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5963 if (connection.monitor) {
5964 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5965 if (!pid.has_value()) {
5966 ALOGE("Could not find responsive monitor for connection %s",
5967 connection.inputChannel->getName().c_str());
5968 return;
5969 }
5970 sendMonitorResponsiveCommandLocked(pid.value());
5971 return;
5972 }
5973 // If not a monitor, must be a window
5974 sendWindowResponsiveCommandLocked(connectionToken);
5975}
5976
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005978 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005979 KeyEntry& keyEntry, bool handled) {
5980 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005981 if (!handled) {
5982 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005983 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005984 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985 return false;
5986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988 // Get the fallback key state.
5989 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005990 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005991 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005992 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 connection->inputState.removeFallbackKey(originalKeyCode);
5994 }
5995
5996 if (handled || !dispatchEntry->hasForegroundTarget()) {
5997 // If the application handles the original key for which we previously
5998 // generated a fallback or if the window is not a foreground window,
5999 // then cancel the associated fallback key, if any.
6000 if (fallbackKeyCode != -1) {
6001 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006002 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6003 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6004 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6005 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6006 keyEntry.policyFlags);
6007 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006008 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006009 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010
6011 mLock.unlock();
6012
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006013 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006014 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015
6016 mLock.lock();
6017
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018 // Cancel the fallback key.
6019 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006021 "application handled the original non-fallback key "
6022 "or is no longer a foreground target, "
6023 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 options.keyCode = fallbackKeyCode;
6025 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006027 connection->inputState.removeFallbackKey(originalKeyCode);
6028 }
6029 } else {
6030 // If the application did not handle a non-fallback key, first check
6031 // that we are in a good state to perform unhandled key event processing
6032 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006033 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006035 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6036 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6037 "since this is not an initial down. "
6038 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6039 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6040 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006041 return false;
6042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006045 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6046 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6047 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6048 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6049 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006050 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006051
6052 mLock.unlock();
6053
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006054 bool fallback =
6055 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006056 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006057
6058 mLock.lock();
6059
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006060 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061 connection->inputState.removeFallbackKey(originalKeyCode);
6062 return false;
6063 }
6064
6065 // Latch the fallback keycode for this key on an initial down.
6066 // The fallback keycode cannot change at any other point in the lifecycle.
6067 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 fallbackKeyCode = event.getKeyCode();
6070 } else {
6071 fallbackKeyCode = AKEYCODE_UNKNOWN;
6072 }
6073 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6074 }
6075
6076 ALOG_ASSERT(fallbackKeyCode != -1);
6077
6078 // Cancel the fallback key if the policy decides not to send it anymore.
6079 // We will continue to dispatch the key to the policy but we will no
6080 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006081 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6082 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006083 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6084 if (fallback) {
6085 ALOGD("Unhandled key event: Policy requested to send key %d"
6086 "as a fallback for %d, but on the DOWN it had requested "
6087 "to send %d instead. Fallback canceled.",
6088 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6089 } else {
6090 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6091 "but on the DOWN it had requested to send %d. "
6092 "Fallback canceled.",
6093 originalKeyCode, fallbackKeyCode);
6094 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006095 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096
6097 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6098 "canceling fallback, policy no longer desires it");
6099 options.keyCode = fallbackKeyCode;
6100 synthesizeCancelationEventsForConnectionLocked(connection, options);
6101
6102 fallback = false;
6103 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006104 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006105 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106 }
6107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006109 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6110 {
6111 std::string msg;
6112 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6113 connection->inputState.getFallbackKeys();
6114 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6115 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6116 }
6117 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6118 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006121
6122 if (fallback) {
6123 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006124 keyEntry.eventTime = event.getEventTime();
6125 keyEntry.deviceId = event.getDeviceId();
6126 keyEntry.source = event.getSource();
6127 keyEntry.displayId = event.getDisplayId();
6128 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6129 keyEntry.keyCode = fallbackKeyCode;
6130 keyEntry.scanCode = event.getScanCode();
6131 keyEntry.metaState = event.getMetaState();
6132 keyEntry.repeatCount = event.getRepeatCount();
6133 keyEntry.downTime = event.getDownTime();
6134 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006135
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006136 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6137 ALOGD("Unhandled key event: Dispatching fallback key. "
6138 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6139 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6140 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006141 return true; // restart the event
6142 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006143 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6144 ALOGD("Unhandled key event: No fallback key.");
6145 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006146
6147 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006148 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149 }
6150 }
6151 return false;
6152}
6153
Prabir Pradhancef936d2021-07-21 16:17:52 +00006154bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006155 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006156 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006157 return false;
6158}
6159
Michael Wrightd02c5b62014-02-10 15:10:22 -08006160void InputDispatcher::traceInboundQueueLengthLocked() {
6161 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006162 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163 }
6164}
6165
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006166void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 if (ATRACE_ENABLED()) {
6168 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006169 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6170 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171 }
6172}
6173
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006174void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 if (ATRACE_ENABLED()) {
6176 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006177 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6178 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 }
6180}
6181
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006182void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006183 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006185 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006186 dumpDispatchStateLocked(dump);
6187
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006188 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006189 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006190 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191 }
6192}
6193
6194void InputDispatcher::monitor() {
6195 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006196 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006197 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006198 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006199}
6200
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006201/**
6202 * Wake up the dispatcher and wait until it processes all events and commands.
6203 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6204 * this method can be safely called from any thread, as long as you've ensured that
6205 * the work you are interested in completing has already been queued.
6206 */
6207bool InputDispatcher::waitForIdle() {
6208 /**
6209 * Timeout should represent the longest possible time that a device might spend processing
6210 * events and commands.
6211 */
6212 constexpr std::chrono::duration TIMEOUT = 100ms;
6213 std::unique_lock lock(mLock);
6214 mLooper->wake();
6215 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6216 return result == std::cv_status::no_timeout;
6217}
6218
Vishnu Naire798b472020-07-23 13:52:21 -07006219/**
6220 * Sets focus to the window identified by the token. This must be called
6221 * after updating any input window handles.
6222 *
6223 * Params:
6224 * request.token - input channel token used to identify the window that should gain focus.
6225 * request.focusedToken - the token that the caller expects currently to be focused. If the
6226 * specified token does not match the currently focused window, this request will be dropped.
6227 * If the specified focused token matches the currently focused window, the call will succeed.
6228 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6229 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6230 * when requesting the focus change. This determines which request gets
6231 * precedence if there is a focus change request from another source such as pointer down.
6232 */
Vishnu Nair958da932020-08-21 17:12:37 -07006233void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6234 { // acquire lock
6235 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006236 std::optional<FocusResolver::FocusChanges> changes =
6237 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6238 if (changes) {
6239 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006240 }
6241 } // release lock
6242 // Wake up poll loop since it may need to make new input dispatching choices.
6243 mLooper->wake();
6244}
6245
Vishnu Nairc519ff72021-01-21 08:23:08 -08006246void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6247 if (changes.oldFocus) {
6248 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006249 if (focusedInputChannel) {
6250 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6251 "focus left window");
6252 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006253 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006254 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006255 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006256 if (changes.newFocus) {
6257 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006258 }
6259
Prabir Pradhan99987712020-11-10 18:43:05 -08006260 // If a window has pointer capture, then it must have focus. We need to ensure that this
6261 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6262 // If the window loses focus before it loses pointer capture, then the window can be in a state
6263 // where it has pointer capture but not focus, violating the contract. Therefore we must
6264 // dispatch the pointer capture event before the focus event. Since focus events are added to
6265 // the front of the queue (above), we add the pointer capture event to the front of the queue
6266 // after the focus events are added. This ensures the pointer capture event ends up at the
6267 // front.
6268 disablePointerCaptureForcedLocked();
6269
Vishnu Nairc519ff72021-01-21 08:23:08 -08006270 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006271 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006272 }
6273}
Vishnu Nair958da932020-08-21 17:12:37 -07006274
Prabir Pradhan99987712020-11-10 18:43:05 -08006275void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006276 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006277 return;
6278 }
6279
6280 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6281
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006282 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006283 setPointerCaptureLocked(false);
6284 }
6285
6286 if (!mWindowTokenWithPointerCapture) {
6287 // No need to send capture changes because no window has capture.
6288 return;
6289 }
6290
6291 if (mPendingEvent != nullptr) {
6292 // Move the pending event to the front of the queue. This will give the chance
6293 // for the pending event to be dropped if it is a captured event.
6294 mInboundQueue.push_front(mPendingEvent);
6295 mPendingEvent = nullptr;
6296 }
6297
6298 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006299 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006300 mInboundQueue.push_front(std::move(entry));
6301}
6302
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006303void InputDispatcher::setPointerCaptureLocked(bool enable) {
6304 mCurrentPointerCaptureRequest.enable = enable;
6305 mCurrentPointerCaptureRequest.seq++;
6306 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006308 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006309 };
6310 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006311}
6312
Vishnu Nair599f1412021-06-21 10:39:58 -07006313void InputDispatcher::displayRemoved(int32_t displayId) {
6314 { // acquire lock
6315 std::scoped_lock _l(mLock);
6316 // Set an empty list to remove all handles from the specific display.
6317 setInputWindowsLocked(/* window handles */ {}, displayId);
6318 setFocusedApplicationLocked(displayId, nullptr);
6319 // Call focus resolver to clean up stale requests. This must be called after input windows
6320 // have been removed for the removed display.
6321 mFocusResolver.displayRemoved(displayId);
6322 } // release lock
6323
6324 // Wake up poll loop since it may need to make new input dispatching choices.
6325 mLooper->wake();
6326}
6327
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006328void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6329 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006330 // The listener sends the windows as a flattened array. Separate the windows by display for
6331 // more convenient parsing.
6332 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006333 for (const auto& info : windowInfos) {
6334 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6335 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6336 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006337
6338 { // acquire lock
6339 std::scoped_lock _l(mLock);
6340 mDisplayInfos.clear();
6341 for (const auto& displayInfo : displayInfos) {
6342 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6343 }
6344
6345 for (const auto& [displayId, handles] : handlesPerDisplay) {
6346 setInputWindowsLocked(handles, displayId);
6347 }
6348 }
6349 // Wake up poll loop since it may need to make new input dispatching choices.
6350 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006351}
6352
Vishnu Nair062a8672021-09-03 16:07:44 -07006353bool InputDispatcher::shouldDropInput(
6354 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6355 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6356 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6357 isWindowObscuredLocked(windowHandle))) {
6358 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6359 "%" PRId32 ".",
6360 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6361 windowHandle->getInfo()->inputFeatures.string().c_str(),
6362 windowHandle->getInfo()->displayId);
6363 return true;
6364 }
6365 return false;
6366}
6367
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006368void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6369 const std::vector<gui::WindowInfo>& windowInfos,
6370 const std::vector<DisplayInfo>& displayInfos) {
6371 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6372}
6373
Garfield Tane84e6f92019-08-29 17:28:41 -07006374} // namespace android::inputdispatcher