blob: d6ae3cdc0b0de352cc047fc4b3e5a4add043c74a [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.
chaviw98318de2021-05-19 16:45:23 -05001054 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1055 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();
1061 if (windowAcceptsTouchAt(info, displayId, x, y)) {
1062 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
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001073void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 const char* reason;
1075 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001077 if (DEBUG_INBOUND_EVENT_DETAILS) {
1078 ALOGD("Dropped event because policy consumed it.");
1079 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 reason = "inbound event was dropped because the policy consumed it";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::DISABLED:
1083 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 ALOGI("Dropped event because input dispatch is disabled.");
1085 }
1086 reason = "inbound event was dropped because input dispatch is disabled";
1087 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001088 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 ALOGI("Dropped event because of pending overdue app switch.");
1090 reason = "inbound event was dropped because of pending overdue app switch";
1091 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001092 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 ALOGI("Dropped event because the current application is not responding and the user "
1094 "has started interacting with a different application.");
1095 reason = "inbound event was dropped because the current application is not responding "
1096 "and the user has started interacting with a different application";
1097 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001098 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 ALOGI("Dropped event because it is stale.");
1100 reason = "inbound event was dropped because it is stale";
1101 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001102 case DropReason::NO_POINTER_CAPTURE:
1103 ALOGI("Dropped event because there is no window with Pointer Capture.");
1104 reason = "inbound event was dropped because there is no window with Pointer Capture";
1105 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001106 case DropReason::NOT_DROPPED: {
1107 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 }
1111
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001112 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001113 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1115 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001118 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001119 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1120 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1122 synthesizeCancelationEventsForAllConnectionsLocked(options);
1123 } else {
1124 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1125 synthesizeCancelationEventsForAllConnectionsLocked(options);
1126 }
1127 break;
1128 }
Chris Yef59a2f42020-10-16 12:55:26 -07001129 case EventEntry::Type::SENSOR: {
1130 break;
1131 }
arthurhungb89ccb02020-12-30 16:19:01 +08001132 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1133 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001134 break;
1135 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001136 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001137 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001138 case EventEntry::Type::CONFIGURATION_CHANGED:
1139 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001140 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001141 break;
1142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144}
1145
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001146static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1148 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149}
1150
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001151bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1152 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1153 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1154 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155}
1156
1157bool InputDispatcher::isAppSwitchPendingLocked() {
1158 return mAppSwitchDueTime != LONG_LONG_MAX;
1159}
1160
1161void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1162 mAppSwitchDueTime = LONG_LONG_MAX;
1163
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001164 if (DEBUG_APP_SWITCH) {
1165 if (handled) {
1166 ALOGD("App switch has arrived.");
1167 } else {
1168 ALOGD("App switch was abandoned.");
1169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171}
1172
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001174 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175}
1176
Prabir Pradhancef936d2021-07-21 16:17:52 +00001177bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001178 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 return false;
1180 }
1181
1182 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001183 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001184 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001185 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1186 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001187 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 return true;
1189}
1190
Prabir Pradhancef936d2021-07-21 16:17:52 +00001191void InputDispatcher::postCommandLocked(Command&& command) {
1192 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193}
1194
1195void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001196 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001198 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 releaseInboundEventLocked(entry);
1200 }
1201 traceInboundQueueLengthLocked();
1202}
1203
1204void InputDispatcher::releasePendingEventLocked() {
1205 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001207 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 }
1209}
1210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001213 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001214 if (DEBUG_DISPATCH_CYCLE) {
1215 ALOGD("Injected inbound event was dropped.");
1216 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
1219 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001220 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 }
1222 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223}
1224
1225void InputDispatcher::resetKeyRepeatLocked() {
1226 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001227 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229}
1230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1232 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233
Michael Wright2e732952014-09-24 13:26:59 -07001234 uint32_t policyFlags = entry->policyFlags &
1235 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 std::shared_ptr<KeyEntry> newEntry =
1238 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1239 entry->source, entry->displayId, policyFlags, entry->action,
1240 entry->flags, entry->keyCode, entry->scanCode,
1241 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 newEntry->syntheticRepeat = true;
1244 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247}
1248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001251 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1252 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254
1255 // Reset key repeating in case a keyboard device was added or removed or something.
1256 resetKeyRepeatLocked();
1257
1258 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001259 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1260 scoped_unlock unlock(mLock);
1261 mPolicy->notifyConfigurationChanged(eventTime);
1262 };
1263 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 return true;
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1268 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001269 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1270 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1271 entry.deviceId);
1272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
liushenxiang42232912021-05-21 20:24:09 +08001274 // Reset key repeating in case a keyboard device was disabled or enabled.
1275 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1276 resetKeyRepeatLocked();
1277 }
1278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001279 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 synthesizeCancelationEventsForAllConnectionsLocked(options);
1282 return true;
1283}
1284
Vishnu Nairad321cd2020-08-20 16:40:21 -07001285void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001286 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001287 if (mPendingEvent != nullptr) {
1288 // Move the pending event to the front of the queue. This will give the chance
1289 // for the pending event to get dispatched to the newly focused window
1290 mInboundQueue.push_front(mPendingEvent);
1291 mPendingEvent = nullptr;
1292 }
1293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 std::unique_ptr<FocusEntry> focusEntry =
1295 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1296 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001297
1298 // This event should go to the front of the queue, but behind all other focus events
1299 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001301 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302 [](const std::shared_ptr<EventEntry>& event) {
1303 return event->type == EventEntry::Type::FOCUS;
1304 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001305
1306 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001308}
1309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001310void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001311 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001312 if (channel == nullptr) {
1313 return; // Window has gone away
1314 }
1315 InputTarget target;
1316 target.inputChannel = channel;
1317 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1318 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001319 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1320 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001321 std::string reason = std::string("reason=").append(entry->reason);
1322 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001323 dispatchEventLocked(currentTime, entry, {target});
1324}
1325
Prabir Pradhan99987712020-11-10 18:43:05 -08001326void InputDispatcher::dispatchPointerCaptureChangedLocked(
1327 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1328 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001329 dropReason = DropReason::NOT_DROPPED;
1330
Prabir Pradhan99987712020-11-10 18:43:05 -08001331 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001333
1334 if (entry->pointerCaptureRequest.enable) {
1335 // Enable Pointer Capture.
1336 if (haveWindowWithPointerCapture &&
1337 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1338 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1339 "to the window.");
1340 }
1341 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 // This can happen if a window requests capture and immediately releases capture.
1343 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001344 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001345 return;
1346 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001347 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1348 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1349 return;
1350 }
1351
Vishnu Nairc519ff72021-01-21 08:23:08 -08001352 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001353 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1354 mWindowTokenWithPointerCapture = token;
1355 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001356 // Disable Pointer Capture.
1357 // We do not check if the sequence number matches for requests to disable Pointer Capture
1358 // for two reasons:
1359 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1360 // to disable capture with the same sequence number: one generated by
1361 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1362 // Capture being disabled in InputReader.
1363 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1364 // actual Pointer Capture state that affects events being generated by input devices is
1365 // in InputReader.
1366 if (!haveWindowWithPointerCapture) {
1367 // Pointer capture was already forcefully disabled because of focus change.
1368 dropReason = DropReason::NOT_DROPPED;
1369 return;
1370 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001371 token = mWindowTokenWithPointerCapture;
1372 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001373 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001374 setPointerCaptureLocked(false);
1375 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 }
1377
1378 auto channel = getInputChannelLocked(token);
1379 if (channel == nullptr) {
1380 // Window has gone away, clean up Pointer Capture state.
1381 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001382 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001383 setPointerCaptureLocked(false);
1384 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001385 return;
1386 }
1387 InputTarget target;
1388 target.inputChannel = channel;
1389 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1390 entry->dispatchInProgress = true;
1391 dispatchEventLocked(currentTime, entry, {target});
1392
1393 dropReason = DropReason::NOT_DROPPED;
1394}
1395
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001396void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1397 const std::shared_ptr<TouchModeEntry>& entry) {
1398 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1399 getWindowHandlesLocked(mFocusedDisplayId);
1400 if (windowHandles.empty()) {
1401 return;
1402 }
1403 const std::vector<InputTarget> inputTargets =
1404 getInputTargetsFromWindowHandlesLocked(windowHandles);
1405 if (inputTargets.empty()) {
1406 return;
1407 }
1408 entry->dispatchInProgress = true;
1409 dispatchEventLocked(currentTime, entry, inputTargets);
1410}
1411
1412std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1413 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1414 std::vector<InputTarget> inputTargets;
1415 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1416 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1417 const sp<IBinder>& token = handle->getToken();
1418 if (token == nullptr) {
1419 continue;
1420 }
1421 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1422 if (channel == nullptr) {
1423 continue; // Window has gone away
1424 }
1425 InputTarget target;
1426 target.inputChannel = channel;
1427 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1428 inputTargets.push_back(target);
1429 }
1430 return inputTargets;
1431}
1432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001436 if (!entry->dispatchInProgress) {
1437 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1438 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1439 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1440 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001441 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 // We have seen two identical key downs in a row which indicates that the device
1443 // driver is automatically generating key repeats itself. We take note of the
1444 // repeat here, but we disable our own next key repeat timer since it is clear that
1445 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001446 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1447 // Make sure we don't get key down from a different device. If a different
1448 // device Id has same key pressed down, the new device Id will replace the
1449 // current one to hold the key repeat with repeat count reset.
1450 // In the future when got a KEY_UP on the device id, drop it and do not
1451 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1453 resetKeyRepeatLocked();
1454 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1455 } else {
1456 // Not a repeat. Save key down state in case we do see a repeat later.
1457 resetKeyRepeatLocked();
1458 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1459 }
1460 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001461 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1462 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001463 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001464 if (DEBUG_INBOUND_EVENT_DETAILS) {
1465 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1466 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 resetKeyRepeatLocked();
1469 }
1470
1471 if (entry->repeatCount == 1) {
1472 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1473 } else {
1474 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1475 }
1476
1477 entry->dispatchInProgress = true;
1478
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481
1482 // Handle case where the policy asked us to try again later last time.
1483 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1484 if (currentTime < entry->interceptKeyWakeupTime) {
1485 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1486 *nextWakeupTime = entry->interceptKeyWakeupTime;
1487 }
1488 return false; // wait until next wakeup
1489 }
1490 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1491 entry->interceptKeyWakeupTime = 0;
1492 }
1493
1494 // Give the policy a chance to intercept the key.
1495 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1496 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001497 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001499
1500 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1501 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1502 };
1503 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 return false; // wait for the command to run
1505 } else {
1506 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1507 }
1508 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001509 if (*dropReason == DropReason::NOT_DROPPED) {
1510 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512 }
1513
1514 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001515 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001517 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1518 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001519 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 return true;
1521 }
1522
1523 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001524 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001525 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001527 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 return false;
1529 }
1530
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001531 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 return true;
1534 }
1535
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001536 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001537 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538
1539 // Dispatch the key.
1540 dispatchEventLocked(currentTime, entry, inputTargets);
1541 return true;
1542}
1543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001545 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1546 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1547 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1548 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1549 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1550 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1551 entry.metaState, entry.repeatCount, entry.downTime);
1552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553}
1554
Prabir Pradhancef936d2021-07-21 16:17:52 +00001555void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1556 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001557 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001558 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1559 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1560 "source=0x%x, sensorType=%s",
1561 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001562 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001563 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001564 auto command = [this, entry]() REQUIRES(mLock) {
1565 scoped_unlock unlock(mLock);
1566
1567 if (entry->accuracyChanged) {
1568 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1569 }
1570 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1571 entry->hwTimestamp, entry->values);
1572 };
1573 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001574}
1575
1576bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001577 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1578 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001579 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001580 }
Chris Yef59a2f42020-10-16 12:55:26 -07001581 { // acquire lock
1582 std::scoped_lock _l(mLock);
1583
1584 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1585 std::shared_ptr<EventEntry> entry = *it;
1586 if (entry->type == EventEntry::Type::SENSOR) {
1587 it = mInboundQueue.erase(it);
1588 releaseInboundEventLocked(entry);
1589 }
1590 }
1591 }
1592 return true;
1593}
1594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001596 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001597 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001599 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 entry->dispatchInProgress = true;
1601
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001602 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 }
1604
1605 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001606 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001607 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001608 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1609 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 return true;
1611 }
1612
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001613 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614
1615 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001616 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617
1618 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001619 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 if (isPointerEvent) {
1621 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001622 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001624 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 } else {
1626 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001628 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001630 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 return false;
1632 }
1633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001634 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001635 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001636 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1637 return true;
1638 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001639 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001640 CancelationOptions::Mode mode(isPointerEvent
1641 ? CancelationOptions::CANCEL_POINTER_EVENTS
1642 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1643 CancelationOptions options(mode, "input event injection failed");
1644 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 return true;
1646 }
1647
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001648 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650
1651 // Dispatch the motion.
1652 if (conflictingPointerActions) {
1653 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001654 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 synthesizeCancelationEventsForAllConnectionsLocked(options);
1656 }
1657 dispatchEventLocked(currentTime, entry, inputTargets);
1658 return true;
1659}
1660
chaviw98318de2021-05-19 16:45:23 -05001661void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001662 bool isExiting, const MotionEntry& motionEntry) {
1663 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1664 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1665 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1666 PointerCoords pointerCoords;
1667 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1668 pointerCoords.transform(windowHandle->getInfo()->transform);
1669
1670 std::unique_ptr<DragEntry> dragEntry =
1671 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1672 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1673 pointerCoords.getY());
1674
1675 enqueueInboundEventLocked(std::move(dragEntry));
1676}
1677
1678void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1679 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1680 if (channel == nullptr) {
1681 return; // Window has gone away
1682 }
1683 InputTarget target;
1684 target.inputChannel = channel;
1685 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1686 entry->dispatchInProgress = true;
1687 dispatchEventLocked(currentTime, entry, {target});
1688}
1689
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001690void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001691 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1692 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1693 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001694 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001695 "metaState=0x%x, buttonState=0x%x,"
1696 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1697 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001698 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1699 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1700 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001702 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1703 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1704 "x=%f, y=%f, pressure=%f, size=%f, "
1705 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1706 "orientation=%f",
1707 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1708 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1709 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1710 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1711 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1712 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1713 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1714 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719}
1720
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001721void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1722 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001723 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001724 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001725 if (DEBUG_DISPATCH_CYCLE) {
1726 ALOGD("dispatchEventToCurrentInputTargets");
1727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001729 updateInteractionTokensLocked(*eventEntry, inputTargets);
1730
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1732
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001735 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001736 sp<Connection> connection =
1737 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001738 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001739 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001741 if (DEBUG_FOCUS) {
1742 ALOGD("Dropping event delivery to target with channel '%s' because it "
1743 "is no longer registered with the input dispatcher.",
1744 inputTarget.inputChannel->getName().c_str());
1745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 }
1747 }
1748}
1749
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001750void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1751 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1752 // If the policy decides to close the app, we will get a channel removal event via
1753 // unregisterInputChannel, and will clean up the connection that way. We are already not
1754 // sending new pointers to the connection when it blocked, but focused events will continue to
1755 // pile up.
1756 ALOGW("Canceling events for %s because it is unresponsive",
1757 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001758 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001759 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1760 "application not responding");
1761 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 }
1763}
1764
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001766 if (DEBUG_FOCUS) {
1767 ALOGD("Resetting ANR timeouts.");
1768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769
1770 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001771 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001772 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773}
1774
Tiger Huang721e26f2018-07-24 22:26:19 +08001775/**
1776 * Get the display id that the given event should go to. If this event specifies a valid display id,
1777 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1778 * Focused display is the display that the user most recently interacted with.
1779 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001780int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001781 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001782 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001783 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001784 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1785 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 break;
1787 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001788 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1790 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 break;
1792 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001793 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001794 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001795 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001796 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001797 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001798 case EventEntry::Type::SENSOR:
1799 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001800 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 return ADISPLAY_ID_NONE;
1802 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001803 }
1804 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1805}
1806
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001807bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1808 const char* focusedWindowName) {
1809 if (mAnrTracker.empty()) {
1810 // already processed all events that we waited for
1811 mKeyIsWaitingForEventsTimeout = std::nullopt;
1812 return false;
1813 }
1814
1815 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1816 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001817 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001818 mKeyIsWaitingForEventsTimeout = currentTime +
1819 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1820 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001821 return true;
1822 }
1823
1824 // We still have pending events, and already started the timer
1825 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1826 return true; // Still waiting
1827 }
1828
1829 // Waited too long, and some connection still hasn't processed all motions
1830 // Just send the key to the focused window
1831 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1832 focusedWindowName);
1833 mKeyIsWaitingForEventsTimeout = std::nullopt;
1834 return false;
1835}
1836
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1838 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1839 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001840 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841
Tiger Huang721e26f2018-07-24 22:26:19 +08001842 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001843 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001844 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001845 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1846
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 // If there is no currently focused window and no focused application
1848 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1850 ALOGI("Dropping %s event because there is no focused window or focused application in "
1851 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001852 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001853 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 }
1855
Vishnu Nair062a8672021-09-03 16:07:44 -07001856 // Drop key events if requested by input feature
1857 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1858 return InputEventInjectionResult::FAILED;
1859 }
1860
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001861 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1862 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1863 // start interacting with another application via touch (app switch). This code can be removed
1864 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1865 // an app is expected to have a focused window.
1866 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1867 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1868 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001869 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1870 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1871 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001872 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001873 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001874 ALOGW("Waiting because no window has focus but %s may eventually add a "
1875 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001876 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001877 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1880 // Already raised ANR. Drop the event
1881 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001882 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001883 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 } else {
1885 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001887 }
1888 }
1889
1890 // we have a valid, non-null focused window
1891 resetNoFocusedWindowTimeoutLocked();
1892
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001894 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 }
1897
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 if (focusedWindowHandle->getInfo()->paused) {
1899 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001901 }
1902
1903 // If the event is a key event, then we must wait for all previous events to
1904 // complete before delivering it because previous events may have the
1905 // side-effect of transferring focus to a different window and we want to
1906 // ensure that the following keys are sent to the new window.
1907 //
1908 // Suppose the user touches a button in a window then immediately presses "A".
1909 // If the button causes a pop-up window to appear then we want to ensure that
1910 // the "A" key is delivered to the new pop-up window. This is because users
1911 // often anticipate pending UI changes when typing on a keyboard.
1912 // To obtain this behavior, we must serialize key events with respect to all
1913 // prior input events.
1914 if (entry.type == EventEntry::Type::KEY) {
1915 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1916 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 }
1920
1921 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001922 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001923 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1924 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925
1926 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928}
1929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930/**
1931 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1932 * that are currently unresponsive.
1933 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001934std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1935 const std::vector<Monitor>& monitors) const {
1936 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001937 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001938 [this](const Monitor& monitor) REQUIRES(mLock) {
1939 sp<Connection> connection =
1940 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 if (connection == nullptr) {
1942 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001943 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 return false;
1945 }
1946 if (!connection->responsive) {
1947 ALOGW("Unresponsive monitor %s will not get the new gesture",
1948 connection->inputChannel->getName().c_str());
1949 return false;
1950 }
1951 return true;
1952 });
1953 return responsiveMonitors;
1954}
1955
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001956InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1957 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1958 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 enum InjectionPermission {
1961 INJECTION_PERMISSION_UNKNOWN,
1962 INJECTION_PERMISSION_GRANTED,
1963 INJECTION_PERMISSION_DENIED
1964 };
1965
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 // For security reasons, we defer updating the touch state until we are sure that
1967 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001968 const int32_t displayId = entry.displayId;
1969 const int32_t action = entry.action;
1970 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
1972 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001973 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001975 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1976 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001978 // Copy current touch state into tempTouchState.
1979 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1980 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001981 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001982 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001983 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1984 oldState = &(it->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001985 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001986 }
1987
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 bool isSplit = tempTouchState.split;
1989 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1990 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1991 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001992
1993 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1994 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1995 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1996 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1997 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001998 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 bool wrongDevice = false;
2000 if (newGesture) {
2001 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002002 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002003 ALOGI("Dropping event because a pointer for a different device is already down "
2004 "in display %" PRId32,
2005 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002006 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002007 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 switchedDevice = false;
2009 wrongDevice = true;
2010 goto Failed;
2011 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002012 tempTouchState.reset();
2013 tempTouchState.down = down;
2014 tempTouchState.deviceId = entry.deviceId;
2015 tempTouchState.source = entry.source;
2016 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002018 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002019 ALOGI("Dropping move event because a pointer for a different device is already active "
2020 "in display %" PRId32,
2021 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002022 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002023 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002024 switchedDevice = false;
2025 wrongDevice = true;
2026 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 }
2028
2029 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2030 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2031
Garfield Tan00f511d2019-06-12 16:55:40 -07002032 int32_t x;
2033 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002034 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002035 // Always dispatch mouse events to cursor position.
2036 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002037 x = int32_t(entry.xCursorPosition);
2038 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002039 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002040 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2041 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002042 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002043 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002044 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2045 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002046
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002048 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002049 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2050 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002052 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 }
2054
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002055 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002057 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2058 // New window supports splitting, but we should never split mouse events.
2059 isSplit = !isFromMouse;
2060 } else if (isSplit) {
2061 // New window does not support splitting but we have already split events.
2062 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002063 newTouchedWindowHandle = nullptr;
2064 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002065 } else {
2066 // No window is touched, so set split to true. This will allow the next pointer down to
2067 // be delivered to a new window which supports split touch.
2068 tempTouchState.split = isSplit = true;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 }
2070
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002071 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002073 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2074 newHoverWindowHandle = nullptr;
2075 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002076 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002078 }
2079
2080 std::vector<sp<WindowInfoHandle>> newTouchedWindows;
2081 if (newTouchedWindowHandle != nullptr) {
2082 newTouchedWindows.push_back(newTouchedWindowHandle);
2083 }
2084
2085 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2086 const WindowInfo& info = *windowHandle->getInfo();
2087
2088 if (info.paused) {
2089 ALOGI("Not sending touch event to %s because it is paused",
2090 windowHandle->getName().c_str());
2091 continue;
2092 }
2093
2094 // Ensure the window has a connection and the connection is responsive
2095 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2096 if (!isResponsive) {
2097 ALOGW("Not sending touch gesture to %s because it is not responsive",
2098 windowHandle->getName().c_str());
2099 continue;
2100 }
2101
2102 // Drop events that can't be trusted due to occlusion
2103 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2104 TouchOcclusionInfo occlusionInfo =
2105 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2106 if (!isTouchTrustedLocked(occlusionInfo)) {
2107 if (DEBUG_TOUCH_OCCLUSION) {
2108 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2109 for (const auto& log : occlusionInfo.debugInfo) {
2110 ALOGD("%s", log.c_str());
2111 }
2112 }
2113 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2114 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2115 ALOGW("Dropping untrusted touch event due to %s/%d",
2116 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2117 continue;
2118 }
2119 }
2120 }
2121
2122 // Drop touch events if requested by input feature
2123 if (shouldDropInput(entry, windowHandle)) {
2124 continue;
2125 }
2126
2127 // Set target flags.
2128 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2129
2130 // There should only be one new foreground (non-spy) window at this location.
2131 targetFlags |= InputTarget::FLAG_FOREGROUND;
2132
2133 if (isSplit) {
2134 targetFlags |= InputTarget::FLAG_SPLIT;
2135 }
2136 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2137 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2138 } else if (isWindowObscuredLocked(windowHandle)) {
2139 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2140 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002141
2142 // Update the temporary touch state.
2143 BitSet32 pointerIds;
2144 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002146 pointerIds.markBit(pointerId);
2147 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148
2149 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002151
2152 const std::vector<Monitor> newGestureMonitors = isDown
2153 ? selectResponsiveMonitorsLocked(
2154 getValueByKey(mGestureMonitorsByDisplay, displayId))
2155 : std::vector<Monitor>{};
2156
2157 if (newTouchedWindows.empty() && newGestureMonitors.empty() &&
2158 tempTouchState.gestureMonitors.empty()) {
2159 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
2160 "(%d, %d) in display %" PRId32 ".",
2161 x, y, displayId);
2162 injectionResult = InputEventInjectionResult::FAILED;
2163 goto Failed;
Arthur Hung2ea44b92021-11-23 07:42:21 +00002164 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165
2166 tempTouchState.addGestureMonitors(newGestureMonitors);
2167
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 } else {
2169 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2170
2171 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002172 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002173 if (DEBUG_FOCUS) {
2174 ALOGD("Dropping event because the pointer is not down or we previously "
2175 "dropped the pointer down event in display %" PRId32,
2176 displayId);
2177 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002178 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 goto Failed;
2180 }
2181
arthurhung6d4bed92021-03-17 11:59:33 +08002182 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002183
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002185 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002186 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002187 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2188 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189
chaviw98318de2021-05-19 16:45:23 -05002190 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002191 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002192 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002193
2194 // Drop touch events if requested by input feature
2195 if (newTouchedWindowHandle != nullptr &&
2196 shouldDropInput(entry, newTouchedWindowHandle)) {
2197 newTouchedWindowHandle = nullptr;
2198 }
2199
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002200 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2201 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002202 if (DEBUG_FOCUS) {
2203 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2204 oldTouchedWindowHandle->getName().c_str(),
2205 newTouchedWindowHandle->getName().c_str(), displayId);
2206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002208 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2209 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2210 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211
2212 // Make a slippery entrance into the new window.
2213 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2214 isSplit = true;
2215 }
2216
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 int32_t targetFlags =
2218 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 if (isSplit) {
2220 targetFlags |= InputTarget::FLAG_SPLIT;
2221 }
2222 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2223 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002224 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2225 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
2227
2228 BitSet32 pointerIds;
2229 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002230 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002232 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 }
2234 }
2235 }
2236
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002237 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002239 // Let the previous window know that the hover sequence is over, unless we already did
2240 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002241 if (mLastHoverWindowHandle != nullptr &&
2242 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2243 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002244 if (DEBUG_HOVER) {
2245 ALOGD("Sending hover exit event to window %s.",
2246 mLastHoverWindowHandle->getName().c_str());
2247 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002248 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2249 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 }
2251
Garfield Tandf26e862020-07-01 20:18:19 -07002252 // Let the new window know that the hover sequence is starting, unless we already did it
2253 // when dispatching it as is to newTouchedWindowHandle.
2254 if (newHoverWindowHandle != nullptr &&
2255 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2256 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002257 if (DEBUG_HOVER) {
2258 ALOGD("Sending hover enter event to window %s.",
2259 newHoverWindowHandle->getName().c_str());
2260 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002261 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2262 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2263 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 }
2265 }
2266
2267 // Check permission to inject into all touched foreground windows and ensure there
2268 // is at least one touched foreground window.
2269 {
2270 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002271 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2273 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002274 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002275 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 injectionPermission = INJECTION_PERMISSION_DENIED;
2277 goto Failed;
2278 }
2279 }
2280 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002283 ALOGI("Dropping event because there is no touched foreground window in display "
2284 "%" PRId32 " or gesture monitor to receive it.",
2285 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002286 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 goto Failed;
2288 }
2289
2290 // Permission granted to injection into all touched foreground windows.
2291 injectionPermission = INJECTION_PERMISSION_GRANTED;
2292 }
2293
2294 // Check whether windows listening for outside touches are owned by the same UID. If it is
2295 // set the policy flag that we will not reveal coordinate information to this window.
2296 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002297 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002298 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002299 if (foregroundWindowHandle) {
2300 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002301 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002302 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002303 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2304 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2305 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002306 InputTarget::FLAG_ZERO_COORDS,
2307 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
2310 }
2311 }
2312 }
2313
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // If this is the first pointer going down and the touched window has a wallpaper
2315 // then also add the touched wallpaper windows so they are locked in for the duration
2316 // of the touch gesture.
2317 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2318 // engine only supports touch events. We would need to add a mechanism similar
2319 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2320 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002321 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002323 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002324 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002325 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002326 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2327 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002329 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002330 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 .addOrUpdateWindow(windowHandle,
2332 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2333 InputTarget::
2334 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2335 InputTarget::FLAG_DISPATCH_AS_IS,
2336 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 }
2338 }
2339 }
2340 }
2341
2342 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002343 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002345 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
2349
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002350 for (const auto& monitor : tempTouchState.gestureMonitors) {
2351 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002352 }
2353
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 // Drop the outside or hover touch windows since we will not care about them
2355 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002356 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357
2358Failed:
2359 // Check injection permission once and for all.
2360 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002361 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 injectionPermission = INJECTION_PERMISSION_GRANTED;
2363 } else {
2364 injectionPermission = INJECTION_PERMISSION_DENIED;
2365 }
2366 }
2367
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002368 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2369 return injectionResult;
2370 }
2371
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002373 if (!wrongDevice) {
2374 if (switchedDevice) {
2375 if (DEBUG_FOCUS) {
2376 ALOGD("Conflicting pointer actions: Switched to a different device.");
2377 }
2378 *outConflictingPointerActions = true;
2379 }
2380
2381 if (isHoverAction) {
2382 // Started hovering, therefore no longer down.
2383 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002384 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002385 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2386 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 *outConflictingPointerActions = true;
2389 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002390 tempTouchState.reset();
2391 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2392 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2393 tempTouchState.deviceId = entry.deviceId;
2394 tempTouchState.source = entry.source;
2395 tempTouchState.displayId = displayId;
2396 }
2397 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2398 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2399 // All pointers up or canceled.
2400 tempTouchState.reset();
2401 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2402 // First pointer went down.
2403 if (oldState && oldState->down) {
2404 if (DEBUG_FOCUS) {
2405 ALOGD("Conflicting pointer actions: Down received while already down.");
2406 }
2407 *outConflictingPointerActions = true;
2408 }
2409 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2410 // One pointer went up.
2411 if (isSplit) {
2412 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2413 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002415 for (size_t i = 0; i < tempTouchState.windows.size();) {
2416 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2417 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2418 touchedWindow.pointerIds.clearBit(pointerId);
2419 if (touchedWindow.pointerIds.isEmpty()) {
2420 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2421 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002424 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002426 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002427 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002428
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002429 // Save changes unless the action was scroll in which case the temporary touch
2430 // state was only valid for this one action.
2431 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2432 if (tempTouchState.displayId >= 0) {
2433 mTouchStatesByDisplay[displayId] = tempTouchState;
2434 } else {
2435 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002439 // Update hover state.
2440 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 return injectionResult;
2444}
2445
arthurhung6d4bed92021-03-17 11:59:33 +08002446void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002447 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002448 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002449 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002450 if (dropWindow) {
2451 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002452 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002453 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002454 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002455 }
2456 mDragState.reset();
2457}
2458
2459void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2460 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002461 return;
2462 }
2463
arthurhung6d4bed92021-03-17 11:59:33 +08002464 if (!mDragState->isStartDrag) {
2465 mDragState->isStartDrag = true;
2466 mDragState->isStylusButtonDownAtStart =
2467 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2468 }
2469
arthurhungb89ccb02020-12-30 16:19:01 +08002470 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2471 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2472 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2473 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002474 // Handle the special case : stylus button no longer pressed.
2475 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2476 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2477 finishDragAndDrop(entry.displayId, x, y);
2478 return;
2479 }
2480
chaviw98318de2021-05-19 16:45:23 -05002481 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002482 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002483 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002484 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002485 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2486 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2487 if (mDragState->dragHoverWindowHandle != nullptr) {
2488 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2489 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002490 }
arthurhung6d4bed92021-03-17 11:59:33 +08002491 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002492 }
2493 // enqueue drag location if needed.
2494 if (hoverWindowHandle != nullptr) {
2495 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2496 }
arthurhung6d4bed92021-03-17 11:59:33 +08002497 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2498 finishDragAndDrop(entry.displayId, x, y);
2499 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002500 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002501 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002502 }
2503}
2504
chaviw98318de2021-05-19 16:45:23 -05002505void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 int32_t targetFlags, BitSet32 pointerIds,
2507 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002508 std::vector<InputTarget>::iterator it =
2509 std::find_if(inputTargets.begin(), inputTargets.end(),
2510 [&windowHandle](const InputTarget& inputTarget) {
2511 return inputTarget.inputChannel->getConnectionToken() ==
2512 windowHandle->getToken();
2513 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002514
chaviw98318de2021-05-19 16:45:23 -05002515 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002516
2517 if (it == inputTargets.end()) {
2518 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002519 std::shared_ptr<InputChannel> inputChannel =
2520 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002521 if (inputChannel == nullptr) {
2522 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2523 return;
2524 }
2525 inputTarget.inputChannel = inputChannel;
2526 inputTarget.flags = targetFlags;
2527 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002528 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2529 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002530 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002531 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002532 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002533 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002534 inputTargets.push_back(inputTarget);
2535 it = inputTargets.end() - 1;
2536 }
2537
2538 ALOG_ASSERT(it->flags == targetFlags);
2539 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2540
chaviw1ff3d1e2020-07-01 15:53:47 -07002541 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542}
2543
Michael Wright3dd60e22019-03-27 22:06:44 +00002544void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002545 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002546 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2547 mGlobalMonitorsByDisplay.find(displayId);
2548
2549 if (it != mGlobalMonitorsByDisplay.end()) {
2550 const std::vector<Monitor>& monitors = it->second;
2551 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002552 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 }
2555}
2556
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002557void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002558 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002559 InputTarget target;
2560 target.inputChannel = monitor.inputChannel;
2561 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002562 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002563 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002564 const auto& displayTransform = it->second.transform;
2565 target.displayTransform = displayTransform;
2566 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002567 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002568 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002569 inputTargets.push_back(target);
2570}
2571
chaviw98318de2021-05-19 16:45:23 -05002572bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 const InjectionState* injectionState) {
2574 if (injectionState &&
2575 (windowHandle == nullptr ||
2576 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2577 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002578 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002580 "owned by uid %d",
2581 injectionState->injectorPid, injectionState->injectorUid,
2582 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 } else {
2584 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 }
2587 return false;
2588 }
2589 return true;
2590}
2591
Robert Carrc9bf1d32020-04-13 17:21:08 -07002592/**
2593 * Indicate whether one window handle should be considered as obscuring
2594 * another window handle. We only check a few preconditions. Actually
2595 * checking the bounds is left to the caller.
2596 */
chaviw98318de2021-05-19 16:45:23 -05002597static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2598 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002599 // Compare by token so cloned layers aren't counted
2600 if (haveSameToken(windowHandle, otherHandle)) {
2601 return false;
2602 }
2603 auto info = windowHandle->getInfo();
2604 auto otherInfo = otherHandle->getInfo();
2605 if (!otherInfo->visible) {
2606 return false;
chaviw98318de2021-05-19 16:45:23 -05002607 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002608 // Those act as if they were invisible, so we don't need to flag them.
2609 // We do want to potentially flag touchable windows even if they have 0
2610 // opacity, since they can consume touches and alter the effects of the
2611 // user interaction (eg. apps that rely on
2612 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2613 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2614 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002615 } else if (info->ownerUid == otherInfo->ownerUid) {
2616 // If ownerUid is the same we don't generate occlusion events as there
2617 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002618 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002619 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002620 return false;
2621 } else if (otherInfo->displayId != info->displayId) {
2622 return false;
2623 }
2624 return true;
2625}
2626
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002627/**
2628 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2629 * untrusted, one should check:
2630 *
2631 * 1. If result.hasBlockingOcclusion is true.
2632 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2633 * BLOCK_UNTRUSTED.
2634 *
2635 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2636 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2637 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2638 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2639 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2640 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2641 *
2642 * If neither of those is true, then it means the touch can be allowed.
2643 */
2644InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002645 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2646 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002647 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002648 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002649 TouchOcclusionInfo info;
2650 info.hasBlockingOcclusion = false;
2651 info.obscuringOpacity = 0;
2652 info.obscuringUid = -1;
2653 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002654 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002655 if (windowHandle == otherHandle) {
2656 break; // All future windows are below us. Exit early.
2657 }
chaviw98318de2021-05-19 16:45:23 -05002658 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002659 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2660 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002661 if (DEBUG_TOUCH_OCCLUSION) {
2662 info.debugInfo.push_back(
2663 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2664 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002665 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2666 // we perform the checks below to see if the touch can be propagated or not based on the
2667 // window's touch occlusion mode
2668 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2669 info.hasBlockingOcclusion = true;
2670 info.obscuringUid = otherInfo->ownerUid;
2671 info.obscuringPackage = otherInfo->packageName;
2672 break;
2673 }
2674 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2675 uint32_t uid = otherInfo->ownerUid;
2676 float opacity =
2677 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2678 // Given windows A and B:
2679 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2680 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2681 opacityByUid[uid] = opacity;
2682 if (opacity > info.obscuringOpacity) {
2683 info.obscuringOpacity = opacity;
2684 info.obscuringUid = uid;
2685 info.obscuringPackage = otherInfo->packageName;
2686 }
2687 }
2688 }
2689 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002690 if (DEBUG_TOUCH_OCCLUSION) {
2691 info.debugInfo.push_back(
2692 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2693 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002694 return info;
2695}
2696
chaviw98318de2021-05-19 16:45:23 -05002697std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002698 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002699 return StringPrintf(INDENT2
2700 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2701 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2702 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2703 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002704 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002705 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002706 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2707 info->frameTop, info->frameRight, info->frameBottom,
2708 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002709 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2710 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2711 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002712}
2713
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002714bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2715 if (occlusionInfo.hasBlockingOcclusion) {
2716 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2717 occlusionInfo.obscuringUid);
2718 return false;
2719 }
2720 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2721 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2722 "%.2f, maximum allowed = %.2f)",
2723 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2724 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2725 return false;
2726 }
2727 return true;
2728}
2729
chaviw98318de2021-05-19 16:45:23 -05002730bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002733 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2734 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002735 if (windowHandle == otherHandle) {
2736 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 }
chaviw98318de2021-05-19 16:45:23 -05002738 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002739 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002740 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 return true;
2742 }
2743 }
2744 return false;
2745}
2746
chaviw98318de2021-05-19 16:45:23 -05002747bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002748 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002749 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2750 const WindowInfo* windowInfo = windowHandle->getInfo();
2751 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002752 if (windowHandle == otherHandle) {
2753 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002754 }
chaviw98318de2021-05-19 16:45:23 -05002755 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002756 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002757 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002758 return true;
2759 }
2760 }
2761 return false;
2762}
2763
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002764std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002765 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002766 if (applicationHandle != nullptr) {
2767 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002768 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 } else {
2770 return applicationHandle->getName();
2771 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002772 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002773 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002775 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 }
2777}
2778
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002779void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002780 if (!isUserActivityEvent(eventEntry)) {
2781 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002782 return;
2783 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002784 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002785 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002786 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002787 const WindowInfo* info = focusedWindowHandle->getInfo();
2788 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002789 if (DEBUG_DISPATCH_CYCLE) {
2790 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 return;
2793 }
2794 }
2795
2796 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002797 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002798 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002799 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2800 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 return;
2802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002804 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 eventType = USER_ACTIVITY_EVENT_TOUCH;
2806 }
2807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002809 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002810 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2811 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002812 return;
2813 }
2814 eventType = USER_ACTIVITY_EVENT_BUTTON;
2815 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002817 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002818 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002819 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002820 break;
2821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
2823
Prabir Pradhancef936d2021-07-21 16:17:52 +00002824 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2825 REQUIRES(mLock) {
2826 scoped_unlock unlock(mLock);
2827 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2828 };
2829 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830}
2831
2832void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002834 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002835 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002836 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002838 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002839 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002840 ATRACE_NAME(message.c_str());
2841 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002842 if (DEBUG_DISPATCH_CYCLE) {
2843 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2844 "globalScaleFactor=%f, pointerIds=0x%x %s",
2845 connection->getInputChannelName().c_str(), inputTarget.flags,
2846 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2847 inputTarget.getPointerInfoString().c_str());
2848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
2850 // Skip this event if the connection status is not normal.
2851 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002852 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002853 if (DEBUG_DISPATCH_CYCLE) {
2854 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002855 connection->getInputChannelName().c_str(),
2856 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 return;
2859 }
2860
2861 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002862 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2863 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2864 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002865 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002867 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002868 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002869 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002870 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 if (!splitMotionEntry) {
2872 return; // split event was dropped
2873 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002874 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2875 std::string reason = std::string("reason=pointer cancel on split window");
2876 android_log_event_list(LOGTAG_INPUT_CANCEL)
2877 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2878 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002879 if (DEBUG_FOCUS) {
2880 ALOGD("channel '%s' ~ Split motion event.",
2881 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002882 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002883 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002884 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2885 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 return;
2887 }
2888 }
2889
2890 // Not splitting. Enqueue dispatch entries for the event as is.
2891 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2892}
2893
2894void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002896 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002897 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002898 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002900 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002901 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002902 ATRACE_NAME(message.c_str());
2903 }
2904
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002905 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906
2907 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002908 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002910 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002912 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002914 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002916 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002918 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
2921 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002922 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 startDispatchCycleLocked(currentTime, connection);
2924 }
2925}
2926
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002928 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002929 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002931 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2933 connection->getInputChannelName().c_str(),
2934 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002935 ATRACE_NAME(message.c_str());
2936 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002937 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 if (!(inputTargetFlags & dispatchMode)) {
2939 return;
2940 }
2941 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2942
2943 // This is a new event.
2944 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002945 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002946 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002948 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2949 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002950 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002953 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002955 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 dispatchEntry->resolvedAction = keyEntry.action;
2957 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2960 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002961 if (DEBUG_DISPATCH_CYCLE) {
2962 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2963 "event",
2964 connection->getInputChannelName().c_str());
2965 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 return; // skip the inconsistent event
2967 }
2968 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002971 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002972 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002973 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2974 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2975 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2976 static_cast<int32_t>(IdGenerator::Source::OTHER);
2977 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2979 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2980 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2981 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2982 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2984 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2985 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2986 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2987 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2988 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002989 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002990 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 }
2992 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002993 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2994 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002995 if (DEBUG_DISPATCH_CYCLE) {
2996 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2997 "enter event",
2998 connection->getInputChannelName().c_str());
2999 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003000 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3001 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003005 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3007 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3008 }
3009 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3010 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3014 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003015 if (DEBUG_DISPATCH_CYCLE) {
3016 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3017 "event",
3018 connection->getInputChannelName().c_str());
3019 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003020 return; // skip the inconsistent event
3021 }
3022
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003023 dispatchEntry->resolvedEventId =
3024 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3025 ? mIdGenerator.nextId()
3026 : motionEntry.id;
3027 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3028 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3029 ") to MotionEvent(id=0x%" PRIx32 ").",
3030 motionEntry.id, dispatchEntry->resolvedEventId);
3031 ATRACE_NAME(message.c_str());
3032 }
3033
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003034 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3035 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3036 // Skip reporting pointer down outside focus to the policy.
3037 break;
3038 }
3039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003041 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042
3043 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003045 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003046 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003047 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3048 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003049 break;
3050 }
Chris Yef59a2f42020-10-16 12:55:26 -07003051 case EventEntry::Type::SENSOR: {
3052 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3053 break;
3054 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003055 case EventEntry::Type::CONFIGURATION_CHANGED:
3056 case EventEntry::Type::DEVICE_RESET: {
3057 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003058 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003059 break;
3060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 }
3062
3063 // Remember that we are waiting for this dispatch to complete.
3064 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003065 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 }
3067
3068 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003069 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003070 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003071}
3072
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003073/**
3074 * This function is purely for debugging. It helps us understand where the user interaction
3075 * was taking place. For example, if user is touching launcher, we will see a log that user
3076 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3077 * We will see both launcher and wallpaper in that list.
3078 * Once the interaction with a particular set of connections starts, no new logs will be printed
3079 * until the set of interacted connections changes.
3080 *
3081 * The following items are skipped, to reduce the logspam:
3082 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3083 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3084 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3085 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3086 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003087 */
3088void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3089 const std::vector<InputTarget>& targets) {
3090 // Skip ACTION_UP events, and all events other than keys and motions
3091 if (entry.type == EventEntry::Type::KEY) {
3092 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3093 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3094 return;
3095 }
3096 } else if (entry.type == EventEntry::Type::MOTION) {
3097 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3098 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3099 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3100 return;
3101 }
3102 } else {
3103 return; // Not a key or a motion
3104 }
3105
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003106 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003107 std::vector<sp<Connection>> newConnections;
3108 for (const InputTarget& target : targets) {
3109 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3110 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3111 continue; // Skip windows that receive ACTION_OUTSIDE
3112 }
3113
3114 sp<IBinder> token = target.inputChannel->getConnectionToken();
3115 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003116 if (connection == nullptr) {
3117 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003118 }
3119 newConnectionTokens.insert(std::move(token));
3120 newConnections.emplace_back(connection);
3121 }
3122 if (newConnectionTokens == mInteractionConnectionTokens) {
3123 return; // no change
3124 }
3125 mInteractionConnectionTokens = newConnectionTokens;
3126
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003127 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003128 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003129 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003130 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003131 std::string message = "Interaction with: " + targetList;
3132 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003133 message += "<none>";
3134 }
3135 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3136}
3137
chaviwfd6d3512019-03-25 13:23:49 -07003138void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003139 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003140 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003141 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3142 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003143 return;
3144 }
3145
Vishnu Nairc519ff72021-01-21 08:23:08 -08003146 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003147 if (focusedToken == token) {
3148 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003149 return;
3150 }
3151
Prabir Pradhancef936d2021-07-21 16:17:52 +00003152 auto command = [this, token]() REQUIRES(mLock) {
3153 scoped_unlock unlock(mLock);
3154 mPolicy->onPointerDownOutsideFocus(token);
3155 };
3156 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157}
3158
3159void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003161 if (ATRACE_ENABLED()) {
3162 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003164 ATRACE_NAME(message.c_str());
3165 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003166 if (DEBUG_DISPATCH_CYCLE) {
3167 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003170 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003171 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003173 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003174 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003175 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176
3177 // Publish the event.
3178 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003179 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3180 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003182 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3183 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003186 status = connection->inputPublisher
3187 .publishKeyEvent(dispatchEntry->seq,
3188 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3189 keyEntry.source, keyEntry.displayId,
3190 std::move(hmac), dispatchEntry->resolvedAction,
3191 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3192 keyEntry.scanCode, keyEntry.metaState,
3193 keyEntry.repeatCount, keyEntry.downTime,
3194 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 }
3197
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003198 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003199 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003202 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203
chaviw82357092020-01-28 13:13:06 -08003204 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003205 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3207 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003208 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003209 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3210 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003211 // Don't apply window scale here since we don't want scale to affect raw
3212 // coordinates. The scale will be sent back to the client and applied
3213 // later when requesting relative coordinates.
3214 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3215 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003216 }
3217 usingCoords = scaledCoords;
3218 }
3219 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 // We don't want the dispatch target to know.
3221 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003222 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 scaledCoords[i].clear();
3224 }
3225 usingCoords = scaledCoords;
3226 }
3227 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003228
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003229 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003230
3231 // Publish the motion event.
3232 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003233 .publishMotionEvent(dispatchEntry->seq,
3234 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003235 motionEntry.deviceId, motionEntry.source,
3236 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003237 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003238 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 motionEntry.edgeFlags, motionEntry.metaState,
3241 motionEntry.buttonState,
3242 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003243 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003244 motionEntry.xPrecision, motionEntry.yPrecision,
3245 motionEntry.xCursorPosition,
3246 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003247 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003248 motionEntry.downTime, motionEntry.eventTime,
3249 motionEntry.pointerCount,
3250 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 break;
3252 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003253
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003254 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003255 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003256 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003258 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003259 break;
3260 }
3261
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003262 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3263 const TouchModeEntry& touchModeEntry =
3264 static_cast<const TouchModeEntry&>(eventEntry);
3265 status = connection->inputPublisher
3266 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3267 touchModeEntry.inTouchMode);
3268
3269 break;
3270 }
3271
Prabir Pradhan99987712020-11-10 18:43:05 -08003272 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3273 const auto& captureEntry =
3274 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3275 status = connection->inputPublisher
3276 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003277 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003278 break;
3279 }
3280
arthurhungb89ccb02020-12-30 16:19:01 +08003281 case EventEntry::Type::DRAG: {
3282 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3283 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3284 dragEntry.id, dragEntry.x,
3285 dragEntry.y,
3286 dragEntry.isExiting);
3287 break;
3288 }
3289
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003290 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003291 case EventEntry::Type::DEVICE_RESET:
3292 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003293 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003294 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 }
3298
3299 // Check the result.
3300 if (status) {
3301 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003302 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 "This is unexpected because the wait queue is empty, so the pipe "
3305 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003306 "event to it, status=%s(%d)",
3307 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3308 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3310 } else {
3311 // Pipe is full and we are waiting for the app to finish process some events
3312 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003313 if (DEBUG_DISPATCH_CYCLE) {
3314 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3315 "waiting for the application to catch up",
3316 connection->getInputChannelName().c_str());
3317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 }
3319 } else {
3320 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003321 "status=%s(%d)",
3322 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3323 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3325 }
3326 return;
3327 }
3328
3329 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003330 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3331 connection->outboundQueue.end(),
3332 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003333 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003334 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003335 if (connection->responsive) {
3336 mAnrTracker.insert(dispatchEntry->timeoutTime,
3337 connection->inputChannel->getConnectionToken());
3338 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003339 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
3341}
3342
chaviw09c8d2d2020-08-24 15:48:26 -07003343std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3344 size_t size;
3345 switch (event.type) {
3346 case VerifiedInputEvent::Type::KEY: {
3347 size = sizeof(VerifiedKeyEvent);
3348 break;
3349 }
3350 case VerifiedInputEvent::Type::MOTION: {
3351 size = sizeof(VerifiedMotionEvent);
3352 break;
3353 }
3354 }
3355 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3356 return mHmacKeyManager.sign(start, size);
3357}
3358
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003359const std::array<uint8_t, 32> InputDispatcher::getSignature(
3360 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003361 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3362 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003363 // Only sign events up and down events as the purely move events
3364 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003365 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003366 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003367
3368 VerifiedMotionEvent verifiedEvent =
3369 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3370 verifiedEvent.actionMasked = actionMasked;
3371 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3372 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003373}
3374
3375const std::array<uint8_t, 32> InputDispatcher::getSignature(
3376 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3377 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3378 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3379 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003380 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003381}
3382
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003385 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003386 if (DEBUG_DISPATCH_CYCLE) {
3387 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3388 connection->getInputChannelName().c_str(), seq, toString(handled));
3389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003391 if (connection->status == Connection::Status::BROKEN ||
3392 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 return;
3394 }
3395
3396 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003397 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3398 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3399 };
3400 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401}
3402
3403void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 const sp<Connection>& connection,
3405 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003406 if (DEBUG_DISPATCH_CYCLE) {
3407 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3408 connection->getInputChannelName().c_str(), toString(notify));
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410
3411 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003412 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003413 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003414 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003415 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
3417 // The connection appears to be unrecoverably broken.
3418 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003419 if (connection->status == Connection::Status::NORMAL) {
3420 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
3422 if (notify) {
3423 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003424 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3425 connection->getInputChannelName().c_str());
3426
3427 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003428 scoped_unlock unlock(mLock);
3429 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3430 };
3431 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433 }
3434}
3435
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003436void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3437 while (!queue.empty()) {
3438 DispatchEntry* dispatchEntry = queue.front();
3439 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003440 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
3442}
3443
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003444void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003446 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
3448 delete dispatchEntry;
3449}
3450
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003451int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3452 std::scoped_lock _l(mLock);
3453 sp<Connection> connection = getConnectionLocked(connectionToken);
3454 if (connection == nullptr) {
3455 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3456 connectionToken.get(), events);
3457 return 0; // remove the callback
3458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003460 bool notify;
3461 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3462 if (!(events & ALOOPER_EVENT_INPUT)) {
3463 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3464 "events=0x%x",
3465 connection->getInputChannelName().c_str(), events);
3466 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
3468
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003469 nsecs_t currentTime = now();
3470 bool gotOne = false;
3471 status_t status = OK;
3472 for (;;) {
3473 Result<InputPublisher::ConsumerResponse> result =
3474 connection->inputPublisher.receiveConsumerResponse();
3475 if (!result.ok()) {
3476 status = result.error().code();
3477 break;
3478 }
3479
3480 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3481 const InputPublisher::Finished& finish =
3482 std::get<InputPublisher::Finished>(*result);
3483 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3484 finish.consumeTime);
3485 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003486 if (shouldReportMetricsForConnection(*connection)) {
3487 const InputPublisher::Timeline& timeline =
3488 std::get<InputPublisher::Timeline>(*result);
3489 mLatencyTracker
3490 .trackGraphicsLatency(timeline.inputEventId,
3491 connection->inputChannel->getConnectionToken(),
3492 std::move(timeline.graphicsTimeline));
3493 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003494 }
3495 gotOne = true;
3496 }
3497 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003498 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003499 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 return 1;
3501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
3503
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003504 notify = status != DEAD_OBJECT || !connection->monitor;
3505 if (notify) {
3506 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3507 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3508 status);
3509 }
3510 } else {
3511 // Monitor channels are never explicitly unregistered.
3512 // We do it automatically when the remote endpoint is closed so don't warn about them.
3513 const bool stillHaveWindowHandle =
3514 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3515 notify = !connection->monitor && stillHaveWindowHandle;
3516 if (notify) {
3517 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3518 connection->getInputChannelName().c_str(), events);
3519 }
3520 }
3521
3522 // Remove the channel.
3523 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3524 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525}
3526
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003529 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003530 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
3532}
3533
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003534void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003535 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003536 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3537 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3538}
3539
3540void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3541 const CancelationOptions& options,
3542 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3543 for (const auto& it : monitorsByDisplay) {
3544 const std::vector<Monitor>& monitors = it.second;
3545 for (const Monitor& monitor : monitors) {
3546 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003547 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003548 }
3549}
3550
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003552 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003553 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003554 if (connection == nullptr) {
3555 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003557
3558 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559}
3560
3561void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3562 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003563 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 return;
3565 }
3566
3567 nsecs_t currentTime = now();
3568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003569 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003570 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003572 if (cancelationEvents.empty()) {
3573 return;
3574 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003575 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3576 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3577 "with reality: %s, mode=%d.",
3578 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3579 options.mode);
3580 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003581
Arthur Hungb3307ee2021-10-14 10:57:37 +00003582 std::string reason = std::string("reason=").append(options.reason);
3583 android_log_event_list(LOGTAG_INPUT_CANCEL)
3584 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3585
Svet Ganov5d3bc372020-01-26 23:11:07 -08003586 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003587 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003588 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3589 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003590 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003591 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003592 target.globalScaleFactor = windowInfo->globalScaleFactor;
3593 }
3594 target.inputChannel = connection->inputChannel;
3595 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3596
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003597 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003599 switch (cancelationEventEntry->type) {
3600 case EventEntry::Type::KEY: {
3601 logOutboundKeyDetails("cancel - ",
3602 static_cast<const KeyEntry&>(*cancelationEventEntry));
3603 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003605 case EventEntry::Type::MOTION: {
3606 logOutboundMotionDetails("cancel - ",
3607 static_cast<const MotionEntry&>(*cancelationEventEntry));
3608 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003610 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003611 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003612 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3613 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003614 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003615 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003616 break;
3617 }
3618 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003619 case EventEntry::Type::DEVICE_RESET:
3620 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003621 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003622 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003623 break;
3624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003627 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3628 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003630
3631 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632}
3633
Svet Ganov5d3bc372020-01-26 23:11:07 -08003634void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3635 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003636 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003637 return;
3638 }
3639
3640 nsecs_t currentTime = now();
3641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003642 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003643 connection->inputState.synthesizePointerDownEvents(currentTime);
3644
3645 if (downEvents.empty()) {
3646 return;
3647 }
3648
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003649 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003650 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3651 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003652 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003653
3654 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003655 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003656 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3657 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003658 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003659 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003660 target.globalScaleFactor = windowInfo->globalScaleFactor;
3661 }
3662 target.inputChannel = connection->inputChannel;
3663 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3664
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003665 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003666 switch (downEventEntry->type) {
3667 case EventEntry::Type::MOTION: {
3668 logOutboundMotionDetails("down - ",
3669 static_cast<const MotionEntry&>(*downEventEntry));
3670 break;
3671 }
3672
3673 case EventEntry::Type::KEY:
3674 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003675 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003677 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003678 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003679 case EventEntry::Type::SENSOR:
3680 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003681 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003682 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003683 break;
3684 }
3685 }
3686
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003687 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3688 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003689 }
3690
3691 startDispatchCycleLocked(currentTime, connection);
3692}
3693
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3695 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 ALOG_ASSERT(pointerIds.value != 0);
3697
3698 uint32_t splitPointerIndexMap[MAX_POINTERS];
3699 PointerProperties splitPointerProperties[MAX_POINTERS];
3700 PointerCoords splitPointerCoords[MAX_POINTERS];
3701
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003702 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 uint32_t splitPointerCount = 0;
3704
3705 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003706 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003708 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 uint32_t pointerId = uint32_t(pointerProperties.id);
3710 if (pointerIds.hasBit(pointerId)) {
3711 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3712 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3713 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003714 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 splitPointerCount += 1;
3716 }
3717 }
3718
3719 if (splitPointerCount != pointerIds.count()) {
3720 // This is bad. We are missing some of the pointers that we expected to deliver.
3721 // Most likely this indicates that we received an ACTION_MOVE events that has
3722 // different pointer ids than we expected based on the previous ACTION_DOWN
3723 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3724 // in this way.
3725 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003726 "we expected there to be %d pointers. This probably means we received "
3727 "a broken sequence of pointer ids from the input device.",
3728 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003729 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 }
3731
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003732 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003734 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3735 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3737 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003738 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 uint32_t pointerId = uint32_t(pointerProperties.id);
3740 if (pointerIds.hasBit(pointerId)) {
3741 if (pointerIds.count() == 1) {
3742 // The first/last pointer went down/up.
3743 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003744 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003745 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3746 ? AMOTION_EVENT_ACTION_CANCEL
3747 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 } else {
3749 // A secondary pointer went down/up.
3750 uint32_t splitPointerIndex = 0;
3751 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3752 splitPointerIndex += 1;
3753 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 action = maskedAction |
3755 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
3757 } else {
3758 // An unrelated pointer changed.
3759 action = AMOTION_EVENT_ACTION_MOVE;
3760 }
3761 }
3762
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003763 int32_t newId = mIdGenerator.nextId();
3764 if (ATRACE_ENABLED()) {
3765 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3766 ") to MotionEvent(id=0x%" PRIx32 ").",
3767 originalMotionEntry.id, newId);
3768 ATRACE_NAME(message.c_str());
3769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003770 std::unique_ptr<MotionEntry> splitMotionEntry =
3771 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3772 originalMotionEntry.deviceId, originalMotionEntry.source,
3773 originalMotionEntry.displayId,
3774 originalMotionEntry.policyFlags, action,
3775 originalMotionEntry.actionButton,
3776 originalMotionEntry.flags, originalMotionEntry.metaState,
3777 originalMotionEntry.buttonState,
3778 originalMotionEntry.classification,
3779 originalMotionEntry.edgeFlags,
3780 originalMotionEntry.xPrecision,
3781 originalMotionEntry.yPrecision,
3782 originalMotionEntry.xCursorPosition,
3783 originalMotionEntry.yCursorPosition,
3784 originalMotionEntry.downTime, splitPointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00003785 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003787 if (originalMotionEntry.injectionState) {
3788 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 splitMotionEntry->injectionState->refCount += 1;
3790 }
3791
3792 return splitMotionEntry;
3793}
3794
3795void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003796 if (DEBUG_INBOUND_EVENT_DETAILS) {
3797 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799
Antonio Kantekf16f2832021-09-28 04:39:20 +00003800 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003802 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003804 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3805 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3806 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 } // release lock
3808
3809 if (needWake) {
3810 mLooper->wake();
3811 }
3812}
3813
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003814/**
3815 * If one of the meta shortcuts is detected, process them here:
3816 * Meta + Backspace -> generate BACK
3817 * Meta + Enter -> generate HOME
3818 * This will potentially overwrite keyCode and metaState.
3819 */
3820void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003822 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3823 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3824 if (keyCode == AKEYCODE_DEL) {
3825 newKeyCode = AKEYCODE_BACK;
3826 } else if (keyCode == AKEYCODE_ENTER) {
3827 newKeyCode = AKEYCODE_HOME;
3828 }
3829 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003830 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003831 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003832 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003833 keyCode = newKeyCode;
3834 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3835 }
3836 } else if (action == AKEY_EVENT_ACTION_UP) {
3837 // In order to maintain a consistent stream of up and down events, check to see if the key
3838 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3839 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003840 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003841 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003842 auto replacementIt = mReplacedKeys.find(replacement);
3843 if (replacementIt != mReplacedKeys.end()) {
3844 keyCode = replacementIt->second;
3845 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003846 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3847 }
3848 }
3849}
3850
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003852 if (DEBUG_INBOUND_EVENT_DETAILS) {
3853 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3854 "policyFlags=0x%x, action=0x%x, "
3855 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3856 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3857 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3858 args->downTime);
3859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 if (!validateKeyEvent(args->action)) {
3861 return;
3862 }
3863
3864 uint32_t policyFlags = args->policyFlags;
3865 int32_t flags = args->flags;
3866 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003867 // InputDispatcher tracks and generates key repeats on behalf of
3868 // whatever notifies it, so repeatCount should always be set to 0
3869 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3871 policyFlags |= POLICY_FLAG_VIRTUAL;
3872 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 if (policyFlags & POLICY_FLAG_FUNCTION) {
3875 metaState |= AMETA_FUNCTION_ON;
3876 }
3877
3878 policyFlags |= POLICY_FLAG_TRUSTED;
3879
Michael Wright78f24442014-08-06 15:55:28 -07003880 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003881 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003882
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003884 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003885 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3886 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Michael Wright2b3c3302018-03-02 17:19:13 +00003888 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003890 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3891 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003892 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
Antonio Kantekf16f2832021-09-28 04:39:20 +00003895 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 { // acquire lock
3897 mLock.lock();
3898
3899 if (shouldSendKeyToInputFilterLocked(args)) {
3900 mLock.unlock();
3901
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003902 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3904 return; // event was consumed by the filter
3905 }
3906
3907 mLock.lock();
3908 }
3909
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003910 std::unique_ptr<KeyEntry> newEntry =
3911 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3912 args->displayId, policyFlags, args->action, flags,
3913 keyCode, args->scanCode, metaState, repeatCount,
3914 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003916 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 mLock.unlock();
3918 } // release lock
3919
3920 if (needWake) {
3921 mLooper->wake();
3922 }
3923}
3924
3925bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3926 return mInputFilterEnabled;
3927}
3928
3929void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003930 if (DEBUG_INBOUND_EVENT_DETAILS) {
3931 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3932 "displayId=%" PRId32 ", policyFlags=0x%x, "
3933 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3934 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3935 "yCursorPosition=%f, downTime=%" PRId64,
3936 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3937 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3938 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3939 args->xCursorPosition, args->yCursorPosition, args->downTime);
3940 for (uint32_t i = 0; i < args->pointerCount; i++) {
3941 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3942 "x=%f, y=%f, pressure=%f, size=%f, "
3943 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3944 "orientation=%f",
3945 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3946 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3948 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3949 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3950 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3951 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3952 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3953 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3954 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3958 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 return;
3960 }
3961
3962 uint32_t policyFlags = args->policyFlags;
3963 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003964
3965 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003966 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003967 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3968 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003969 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
Antonio Kantekf16f2832021-09-28 04:39:20 +00003972 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 { // acquire lock
3974 mLock.lock();
3975
3976 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003977 ui::Transform displayTransform;
3978 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3979 displayTransform = it->second.transform;
3980 }
3981
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 mLock.unlock();
3983
3984 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003985 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3986 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003987 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003988 displayTransform, args->xPrecision, args->yPrecision,
3989 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003990 args->downTime, args->eventTime, args->pointerCount,
3991 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
3993 policyFlags |= POLICY_FLAG_FILTERED;
3994 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3995 return; // event was consumed by the filter
3996 }
3997
3998 mLock.lock();
3999 }
4000
4001 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::unique_ptr<MotionEntry> newEntry =
4003 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4004 args->source, args->displayId, policyFlags,
4005 args->action, args->actionButton, args->flags,
4006 args->metaState, args->buttonState,
4007 args->classification, args->edgeFlags,
4008 args->xPrecision, args->yPrecision,
4009 args->xCursorPosition, args->yCursorPosition,
4010 args->downTime, args->pointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00004011 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004013 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4014 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4015 !mInputFilterEnabled) {
4016 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4017 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4018 }
4019
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004020 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 mLock.unlock();
4022 } // release lock
4023
4024 if (needWake) {
4025 mLooper->wake();
4026 }
4027}
4028
Chris Yef59a2f42020-10-16 12:55:26 -07004029void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004030 if (DEBUG_INBOUND_EVENT_DETAILS) {
4031 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4032 " sensorType=%s",
4033 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004034 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004035 }
Chris Yef59a2f42020-10-16 12:55:26 -07004036
Antonio Kantekf16f2832021-09-28 04:39:20 +00004037 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004038 { // acquire lock
4039 mLock.lock();
4040
4041 // Just enqueue a new sensor event.
4042 std::unique_ptr<SensorEntry> newEntry =
4043 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4044 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4045 args->sensorType, args->accuracy,
4046 args->accuracyChanged, args->values);
4047
4048 needWake = enqueueInboundEventLocked(std::move(newEntry));
4049 mLock.unlock();
4050 } // release lock
4051
4052 if (needWake) {
4053 mLooper->wake();
4054 }
4055}
4056
Chris Yefb552902021-02-03 17:18:37 -08004057void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004058 if (DEBUG_INBOUND_EVENT_DETAILS) {
4059 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4060 args->deviceId, args->isOn);
4061 }
Chris Yefb552902021-02-03 17:18:37 -08004062 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4063}
4064
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004066 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067}
4068
4069void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004070 if (DEBUG_INBOUND_EVENT_DETAILS) {
4071 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4072 "switchMask=0x%08x",
4073 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075
4076 uint32_t policyFlags = args->policyFlags;
4077 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004078 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079}
4080
4081void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004082 if (DEBUG_INBOUND_EVENT_DETAILS) {
4083 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4084 args->deviceId);
4085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Antonio Kantekf16f2832021-09-28 04:39:20 +00004087 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004089 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004091 std::unique_ptr<DeviceResetEntry> newEntry =
4092 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4093 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 } // release lock
4095
4096 if (needWake) {
4097 mLooper->wake();
4098 }
4099}
4100
Prabir Pradhan7e186182020-11-10 13:56:45 -08004101void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004102 if (DEBUG_INBOUND_EVENT_DETAILS) {
4103 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004104 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004105 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004106
Antonio Kantekf16f2832021-09-28 04:39:20 +00004107 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004108 { // acquire lock
4109 std::scoped_lock _l(mLock);
4110 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004111 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004112 needWake = enqueueInboundEventLocked(std::move(entry));
4113 } // release lock
4114
4115 if (needWake) {
4116 mLooper->wake();
4117 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004118}
4119
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004120InputEventInjectionResult InputDispatcher::injectInputEvent(
4121 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4122 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004123 if (DEBUG_INBOUND_EVENT_DETAILS) {
4124 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4125 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4126 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4127 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004128 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
4130 policyFlags |= POLICY_FLAG_INJECTED;
4131 if (hasInjectionPermission(injectorPid, injectorUid)) {
4132 policyFlags |= POLICY_FLAG_TRUSTED;
4133 }
4134
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004135 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004136 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4137 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4138 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4139 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4140 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004141 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004142 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004143 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004144 }
4145
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004149 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4150 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004155 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004156 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4157 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4158 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004159 int32_t keyCode = incomingKey.getKeyCode();
4160 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004161 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004163 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004164 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004165 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4166 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4167 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004169 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4170 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004171 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172
4173 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4174 android::base::Timer t;
4175 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4176 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4177 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4178 std::to_string(t.duration().count()).c_str());
4179 }
4180 }
4181
4182 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004183 std::unique_ptr<KeyEntry> injectedEntry =
4184 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004185 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004186 incomingKey.getDisplayId(), policyFlags, action,
4187 flags, keyCode, incomingKey.getScanCode(), metaState,
4188 incomingKey.getRepeatCount(),
4189 incomingKey.getDownTime());
4190 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004195 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004196 const int32_t action = motionEvent.getAction();
4197 const bool isPointerEvent =
4198 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4199 // If a pointer event has no displayId specified, inject it to the default display.
4200 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4201 ? ADISPLAY_ID_DEFAULT
4202 : event->getDisplayId();
4203 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004204 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004205 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004206 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004208 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 }
4210
4211 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004212 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 android::base::Timer t;
4214 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4215 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4216 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4217 std::to_string(t.duration().count()).c_str());
4218 }
4219 }
4220
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004221 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4222 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4223 }
4224
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004226 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4227 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004228 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004229 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4230 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004231 displayId, policyFlags, action, actionButton,
4232 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 motionEvent.getButtonState(),
4234 motionEvent.getClassification(),
4235 motionEvent.getEdgeFlags(),
4236 motionEvent.getXPrecision(),
4237 motionEvent.getYPrecision(),
4238 motionEvent.getRawXCursorPosition(),
4239 motionEvent.getRawYCursorPosition(),
4240 motionEvent.getDownTime(), uint32_t(pointerCount),
Alex Chau663fc832021-12-03 10:37:54 +00004241 pointerProperties, samplePointerCoords,
4242 motionEvent.getXOffset(),
4243 motionEvent.getYOffset());
4244 transformMotionEntryForInjectionLocked(*injectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 sampleEventTimes += 1;
4248 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004249 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004250 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4251 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004252 displayId, policyFlags, action, actionButton,
4253 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004254 motionEvent.getButtonState(),
4255 motionEvent.getClassification(),
4256 motionEvent.getEdgeFlags(),
4257 motionEvent.getXPrecision(),
4258 motionEvent.getYPrecision(),
4259 motionEvent.getRawXCursorPosition(),
4260 motionEvent.getRawYCursorPosition(),
4261 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004262 uint32_t(pointerCount), pointerProperties,
Alex Chau663fc832021-12-03 10:37:54 +00004263 samplePointerCoords, motionEvent.getXOffset(),
4264 motionEvent.getYOffset());
4265 transformMotionEntryForInjectionLocked(*nextInjectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004266 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 }
4268 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004272 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004273 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 }
4275
4276 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004277 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 injectionState->injectionIsAsync = true;
4279 }
4280
4281 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004282 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283
4284 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004285 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004286 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004287 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 }
4289
4290 mLock.unlock();
4291
4292 if (needWake) {
4293 mLooper->wake();
4294 }
4295
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004298 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004300 if (syncMode == InputEventInjectionSync::NONE) {
4301 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 } else {
4303 for (;;) {
4304 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 break;
4307 }
4308
4309 nsecs_t remainingTimeout = endTime - now();
4310 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004311 if (DEBUG_INJECTION) {
4312 ALOGD("injectInputEvent - Timed out waiting for injection result "
4313 "to become available.");
4314 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004315 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 break;
4317 }
4318
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004319 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
4321
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004322 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4323 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004325 if (DEBUG_INJECTION) {
4326 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4327 injectionState->pendingForegroundDispatches);
4328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 nsecs_t remainingTimeout = endTime - now();
4330 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004331 if (DEBUG_INJECTION) {
4332 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4333 "dispatches to finish.");
4334 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004335 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 break;
4337 }
4338
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004339 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341 }
4342 }
4343
4344 injectionState->release();
4345 } // release lock
4346
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004347 if (DEBUG_INJECTION) {
4348 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4349 injectionResult, injectorPid, injectorUid);
4350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351
4352 return injectionResult;
4353}
4354
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004355std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004356 std::array<uint8_t, 32> calculatedHmac;
4357 std::unique_ptr<VerifiedInputEvent> result;
4358 switch (event.getType()) {
4359 case AINPUT_EVENT_TYPE_KEY: {
4360 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4361 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4362 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004363 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004364 break;
4365 }
4366 case AINPUT_EVENT_TYPE_MOTION: {
4367 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4368 VerifiedMotionEvent verifiedMotionEvent =
4369 verifiedMotionEventFromMotionEvent(motionEvent);
4370 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004371 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004372 break;
4373 }
4374 default: {
4375 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4376 return nullptr;
4377 }
4378 }
4379 if (calculatedHmac == INVALID_HMAC) {
4380 return nullptr;
4381 }
4382 if (calculatedHmac != event.getHmac()) {
4383 return nullptr;
4384 }
4385 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004386}
4387
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 return injectorUid == 0 ||
4390 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391}
4392
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004393void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004394 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004395 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004397 if (DEBUG_INJECTION) {
4398 ALOGD("Setting input event injection result to %d. "
4399 "injectorPid=%d, injectorUid=%d",
4400 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004403 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 // Log the outcome since the injector did not wait for the injection result.
4405 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 ALOGV("Asynchronous input event injection succeeded.");
4408 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004409 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 ALOGW("Asynchronous input event injection failed.");
4411 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004413 ALOGW("Asynchronous input event injection permission denied.");
4414 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004415 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 ALOGW("Asynchronous input event injection timed out.");
4417 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004418 case InputEventInjectionResult::PENDING:
4419 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4420 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422 }
4423
4424 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004425 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 }
4427}
4428
Alex Chau663fc832021-12-03 10:37:54 +00004429void InputDispatcher::transformMotionEntryForInjectionLocked(MotionEntry& entry) const {
4430 const bool isRelativeMouseEvent = isFromSource(entry.source, AINPUT_SOURCE_MOUSE_RELATIVE);
4431 if (!isRelativeMouseEvent && !isFromSource(entry.source, AINPUT_SOURCE_CLASS_POINTER)) {
4432 return;
4433 }
4434
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004435 // Input injection works in the logical display coordinate space, but the input pipeline works
4436 // display space, so we need to transform the injected events accordingly.
4437 const auto it = mDisplayInfos.find(entry.displayId);
4438 if (it == mDisplayInfos.end()) return;
Alex Chau663fc832021-12-03 10:37:54 +00004439 const auto& transformToDisplay = it->second.transform.inverse();
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004440
4441 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4442 PointerCoords& pc = entry.pointerCoords[i];
Alex Chau663fc832021-12-03 10:37:54 +00004443 const auto xy = isRelativeMouseEvent
4444 ? transformWithoutTranslation(transformToDisplay, pc.getX(), pc.getY())
4445 : transformToDisplay.transform(pc.getXYValue());
4446 pc.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
4447 pc.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004448
Alex Chau663fc832021-12-03 10:37:54 +00004449 // Axes with relative values never represent points on a screen, so they should never have
4450 // translation applied. If a device does not report relative values, these values are always
4451 // 0, and will remain unaffected by the following operation.
4452 const auto rel =
4453 transformWithoutTranslation(transformToDisplay,
4454 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
4455 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4456 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, rel.x);
4457 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, rel.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004458 }
4459}
4460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004461void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4462 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 if (injectionState) {
4464 injectionState->pendingForegroundDispatches += 1;
4465 }
4466}
4467
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004468void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4469 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 if (injectionState) {
4471 injectionState->pendingForegroundDispatches -= 1;
4472
4473 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004474 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 }
4476 }
4477}
4478
chaviw98318de2021-05-19 16:45:23 -05004479const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004480 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004481 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004482 auto it = mWindowHandlesByDisplay.find(displayId);
4483 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004484}
4485
chaviw98318de2021-05-19 16:45:23 -05004486sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004487 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004488 if (windowHandleToken == nullptr) {
4489 return nullptr;
4490 }
4491
Arthur Hungb92218b2018-08-14 12:00:21 +08004492 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004493 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4494 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004495 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004496 return windowHandle;
4497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 }
4499 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004500 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501}
4502
chaviw98318de2021-05-19 16:45:23 -05004503sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4504 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004505 if (windowHandleToken == nullptr) {
4506 return nullptr;
4507 }
4508
chaviw98318de2021-05-19 16:45:23 -05004509 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004510 if (windowHandle->getToken() == windowHandleToken) {
4511 return windowHandle;
4512 }
4513 }
4514 return nullptr;
4515}
4516
chaviw98318de2021-05-19 16:45:23 -05004517sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4518 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004519 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004520 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4521 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004522 if (handle->getId() == windowHandle->getId() &&
4523 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004524 if (windowHandle->getInfo()->displayId != it.first) {
4525 ALOGE("Found window %s in display %" PRId32
4526 ", but it should belong to display %" PRId32,
4527 windowHandle->getName().c_str(), it.first,
4528 windowHandle->getInfo()->displayId);
4529 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004530 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 }
4533 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004534 return nullptr;
4535}
4536
chaviw98318de2021-05-19 16:45:23 -05004537sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004538 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4539 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540}
4541
chaviw98318de2021-05-19 16:45:23 -05004542bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004543 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4544 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004545 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004546 if (connection != nullptr && noInputChannel) {
4547 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4548 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4549 return false;
4550 }
4551
4552 if (connection == nullptr) {
4553 if (!noInputChannel) {
4554 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4555 }
4556 return false;
4557 }
4558 if (!connection->responsive) {
4559 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4560 return false;
4561 }
4562 return true;
4563}
4564
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004565std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4566 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004567 auto connectionIt = mConnectionsByToken.find(token);
4568 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004569 return nullptr;
4570 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004571 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004572}
4573
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004574void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004575 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4576 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004577 // Remove all handles on a display if there are no windows left.
4578 mWindowHandlesByDisplay.erase(displayId);
4579 return;
4580 }
4581
4582 // Since we compare the pointer of input window handles across window updates, we need
4583 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004584 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4585 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4586 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004587 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004588 }
4589
chaviw98318de2021-05-19 16:45:23 -05004590 std::vector<sp<WindowInfoHandle>> newHandles;
4591 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004592 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004593 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004594 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004595 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4596 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4597 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004598 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004599 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004600 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004601 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004602 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004603 }
4604
4605 if (info->displayId != displayId) {
4606 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4607 handle->getName().c_str(), displayId, info->displayId);
4608 continue;
4609 }
4610
Robert Carredd13602020-04-13 17:24:34 -07004611 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4612 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004613 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004614 oldHandle->updateFrom(handle);
4615 newHandles.push_back(oldHandle);
4616 } else {
4617 newHandles.push_back(handle);
4618 }
4619 }
4620
4621 // Insert or replace
4622 mWindowHandlesByDisplay[displayId] = newHandles;
4623}
4624
Arthur Hung72d8dc32020-03-28 00:48:39 +00004625void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004626 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004627 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004628 { // acquire lock
4629 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004630 for (const auto& [displayId, handles] : handlesPerDisplay) {
4631 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004632 }
4633 }
4634 // Wake up poll loop since it may need to make new input dispatching choices.
4635 mLooper->wake();
4636}
4637
Arthur Hungb92218b2018-08-14 12:00:21 +08004638/**
4639 * Called from InputManagerService, update window handle list by displayId that can receive input.
4640 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4641 * If set an empty list, remove all handles from the specific display.
4642 * For focused handle, check if need to change and send a cancel event to previous one.
4643 * For removed handle, check if need to send a cancel event if already in touch.
4644 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004645void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004646 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004647 if (DEBUG_FOCUS) {
4648 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004649 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004650 windowList += iwh->getName() + " ";
4651 }
4652 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004655 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004656 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004657 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004658 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004659 if (noInputWindow && window->getToken() != nullptr) {
4660 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4661 window->getName().c_str());
4662 window->releaseChannel();
4663 }
4664 }
4665
Arthur Hung72d8dc32020-03-28 00:48:39 +00004666 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004667 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004669 // Save the old windows' orientation by ID before it gets updated.
4670 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004671 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004672 oldWindowOrientations.emplace(handle->getId(),
4673 handle->getInfo()->transform.getOrientation());
4674 }
4675
chaviw98318de2021-05-19 16:45:23 -05004676 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004677
chaviw98318de2021-05-19 16:45:23 -05004678 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004679 if (mLastHoverWindowHandle &&
4680 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4681 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004682 mLastHoverWindowHandle = nullptr;
4683 }
4684
Vishnu Nairc519ff72021-01-21 08:23:08 -08004685 std::optional<FocusResolver::FocusChanges> changes =
4686 mFocusResolver.setInputWindows(displayId, windowHandles);
4687 if (changes) {
4688 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004691 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4692 mTouchStatesByDisplay.find(displayId);
4693 if (stateIt != mTouchStatesByDisplay.end()) {
4694 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004695 for (size_t i = 0; i < state.windows.size();) {
4696 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004697 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004698 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004699 ALOGD("Touched window was removed: %s in display %" PRId32,
4700 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004701 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004702 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004703 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4704 if (touchedInputChannel != nullptr) {
4705 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4706 "touched window was removed");
4707 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004708 // Since we are about to drop the touch, cancel the events for the wallpaper as
4709 // well.
4710 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4711 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4712 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4713 if (wallpaper != nullptr) {
4714 sp<Connection> wallpaperConnection =
4715 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004716 if (wallpaperConnection != nullptr) {
4717 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4718 options);
4719 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004720 }
4721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004723 state.windows.erase(state.windows.begin() + i);
4724 } else {
4725 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 }
4727 }
arthurhungb89ccb02020-12-30 16:19:01 +08004728
arthurhung6d4bed92021-03-17 11:59:33 +08004729 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004730 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004731 if (mDragState &&
4732 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004733 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004734 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004735 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004737
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004738 // Determine if the orientation of any of the input windows have changed, and cancel all
4739 // pointer events if necessary.
4740 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4741 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4742 if (newWindowHandle != nullptr &&
4743 newWindowHandle->getInfo()->transform.getOrientation() !=
4744 oldWindowOrientations[oldWindowHandle->getId()]) {
4745 std::shared_ptr<InputChannel> inputChannel =
4746 getInputChannelLocked(newWindowHandle->getToken());
4747 if (inputChannel != nullptr) {
4748 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4749 "touched window's orientation changed");
4750 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004751 }
4752 }
4753 }
4754
Arthur Hung72d8dc32020-03-28 00:48:39 +00004755 // Release information for windows that are no longer present.
4756 // This ensures that unused input channels are released promptly.
4757 // Otherwise, they might stick around until the window handle is destroyed
4758 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004759 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004760 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004761 if (DEBUG_FOCUS) {
4762 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004763 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004764 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004765 // To avoid making too many calls into the compat framework, only
4766 // check for window flags when windows are going away.
4767 // TODO(b/157929241) : delete this. This is only needed temporarily
4768 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004769 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004770 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4771 oldWindowHandle->getName().c_str());
4772 if (mCompatService != nullptr) {
4773 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4774 oldWindowHandle->getInfo()->ownerUid);
4775 }
4776 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004777 }
chaviw291d88a2019-02-14 10:33:58 -08004778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779}
4780
4781void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004782 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004783 if (DEBUG_FOCUS) {
4784 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4785 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4786 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004787 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004788 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004789 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 } // release lock
4791
4792 // Wake up poll loop since it may need to make new input dispatching choices.
4793 mLooper->wake();
4794}
4795
Vishnu Nair599f1412021-06-21 10:39:58 -07004796void InputDispatcher::setFocusedApplicationLocked(
4797 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4798 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4799 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4800
4801 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4802 return; // This application is already focused. No need to wake up or change anything.
4803 }
4804
4805 // Set the new application handle.
4806 if (inputApplicationHandle != nullptr) {
4807 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4808 } else {
4809 mFocusedApplicationHandlesByDisplay.erase(displayId);
4810 }
4811
4812 // No matter what the old focused application was, stop waiting on it because it is
4813 // no longer focused.
4814 resetNoFocusedWindowTimeoutLocked();
4815}
4816
Tiger Huang721e26f2018-07-24 22:26:19 +08004817/**
4818 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4819 * the display not specified.
4820 *
4821 * We track any unreleased events for each window. If a window loses the ability to receive the
4822 * released event, we will send a cancel event to it. So when the focused display is changed, we
4823 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4824 * display. The display-specified events won't be affected.
4825 */
4826void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004827 if (DEBUG_FOCUS) {
4828 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4829 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004830 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004831 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004832
4833 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004834 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004835 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004836 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004837 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004838 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004839 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840 CancelationOptions
4841 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4842 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004843 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004844 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4845 }
4846 }
4847 mFocusedDisplayId = displayId;
4848
Chris Ye3c2d6f52020-08-09 10:39:48 -07004849 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004850 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004851 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004852
Vishnu Nairad321cd2020-08-20 16:40:21 -07004853 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004854 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004855 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004856 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004857 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004858 }
4859 }
4860 }
4861
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004862 if (DEBUG_FOCUS) {
4863 logDispatchStateLocked();
4864 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004865 } // release lock
4866
4867 // Wake up poll loop since it may need to make new input dispatching choices.
4868 mLooper->wake();
4869}
4870
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004872 if (DEBUG_FOCUS) {
4873 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875
4876 bool changed;
4877 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004878 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879
4880 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4881 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004882 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883 }
4884
4885 if (mDispatchEnabled && !enabled) {
4886 resetAndDropEverythingLocked("dispatcher is being disabled");
4887 }
4888
4889 mDispatchEnabled = enabled;
4890 mDispatchFrozen = frozen;
4891 changed = true;
4892 } else {
4893 changed = false;
4894 }
4895
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004896 if (DEBUG_FOCUS) {
4897 logDispatchStateLocked();
4898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 } // release lock
4900
4901 if (changed) {
4902 // Wake up poll loop since it may need to make new input dispatching choices.
4903 mLooper->wake();
4904 }
4905}
4906
4907void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004908 if (DEBUG_FOCUS) {
4909 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911
4912 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004913 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
4915 if (mInputFilterEnabled == enabled) {
4916 return;
4917 }
4918
4919 mInputFilterEnabled = enabled;
4920 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4921 } // release lock
4922
4923 // Wake up poll loop since there might be work to do to drop everything.
4924 mLooper->wake();
4925}
4926
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004927void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004928 bool needWake = false;
4929 {
4930 std::scoped_lock lock(mLock);
4931 if (mInTouchMode == inTouchMode) {
4932 return;
4933 }
4934 if (DEBUG_TOUCH_MODE) {
4935 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4936 toString(inTouchMode));
4937 // TODO(b/198487159): Also print the current last interacted apps.
4938 }
4939
4940 // TODO(b/198499018): Store touch mode per display.
4941 mInTouchMode = inTouchMode;
4942
4943 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4944 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4945 needWake = enqueueInboundEventLocked(std::move(entry));
4946 } // release lock
4947
4948 if (needWake) {
4949 mLooper->wake();
4950 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004951}
4952
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004953void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4954 if (opacity < 0 || opacity > 1) {
4955 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4956 return;
4957 }
4958
4959 std::scoped_lock lock(mLock);
4960 mMaximumObscuringOpacityForTouch = opacity;
4961}
4962
4963void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4964 std::scoped_lock lock(mLock);
4965 mBlockUntrustedTouchesMode = mode;
4966}
4967
Arthur Hungabbb9d82021-09-01 14:52:30 +00004968std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4969 const sp<IBinder>& token) {
4970 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4971 for (TouchedWindow& w : state.windows) {
4972 if (w.windowHandle->getToken() == token) {
4973 return std::make_pair(&state, &w);
4974 }
4975 }
4976 }
4977 return std::make_pair(nullptr, nullptr);
4978}
4979
arthurhungb89ccb02020-12-30 16:19:01 +08004980bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4981 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004982 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004983 if (DEBUG_FOCUS) {
4984 ALOGD("Trivial transfer to same window.");
4985 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004986 return true;
4987 }
4988
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004990 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991
Arthur Hungabbb9d82021-09-01 14:52:30 +00004992 // Find the target touch state and touched window by fromToken.
4993 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4994 if (state == nullptr || touchedWindow == nullptr) {
4995 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 return false;
4997 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004998
4999 const int32_t displayId = state->displayId;
5000 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5001 if (toWindowHandle == nullptr) {
5002 ALOGW("Cannot transfer focus because to window not found.");
5003 return false;
5004 }
5005
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005006 if (DEBUG_FOCUS) {
5007 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005008 touchedWindow->windowHandle->getName().c_str(),
5009 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010 }
5011
Arthur Hungabbb9d82021-09-01 14:52:30 +00005012 // Erase old window.
5013 int32_t oldTargetFlags = touchedWindow->targetFlags;
5014 BitSet32 pointerIds = touchedWindow->pointerIds;
5015 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016
Arthur Hungabbb9d82021-09-01 14:52:30 +00005017 // Add new window.
5018 int32_t newTargetFlags = oldTargetFlags &
5019 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5020 InputTarget::FLAG_DISPATCH_AS_IS);
5021 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022
Arthur Hungabbb9d82021-09-01 14:52:30 +00005023 // Store the dragging window.
5024 if (isDragDrop) {
5025 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026 }
5027
Arthur Hungabbb9d82021-09-01 14:52:30 +00005028 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005029 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5030 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005031 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005032 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005033 CancelationOptions
5034 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5035 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005037 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005040 if (DEBUG_FOCUS) {
5041 logDispatchStateLocked();
5042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 } // release lock
5044
5045 // Wake up poll loop since it may need to make new input dispatching choices.
5046 mLooper->wake();
5047 return true;
5048}
5049
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005050// Binder call
5051bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5052 sp<IBinder> fromToken;
5053 { // acquire lock
5054 std::scoped_lock _l(mLock);
5055
Arthur Hungabbb9d82021-09-01 14:52:30 +00005056 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5057 [](const auto& pair) { return pair.second.windows.size() == 1; });
5058 if (it == mTouchStatesByDisplay.end()) {
5059 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5060 return false;
5061 }
5062 const int32_t displayId = it->first;
5063 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005064 if (toWindowHandle == nullptr) {
5065 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5066 return false;
5067 }
5068
Arthur Hungabbb9d82021-09-01 14:52:30 +00005069 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005070 const TouchedWindow& touchedWindow = state.windows[0];
5071 fromToken = touchedWindow.windowHandle->getToken();
5072 } // release lock
5073
5074 return transferTouchFocus(fromToken, destChannelToken);
5075}
5076
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005078 if (DEBUG_FOCUS) {
5079 ALOGD("Resetting and dropping all events (%s).", reason);
5080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081
5082 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5083 synthesizeCancelationEventsForAllConnectionsLocked(options);
5084
5085 resetKeyRepeatLocked();
5086 releasePendingEventLocked();
5087 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005090 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005091 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005093 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094}
5095
5096void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005097 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 dumpDispatchStateLocked(dump);
5099
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005100 std::istringstream stream(dump);
5101 std::string line;
5102
5103 while (std::getline(stream, line, '\n')) {
5104 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 }
5106}
5107
Prabir Pradhan99987712020-11-10 18:43:05 -08005108std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5109 std::string dump;
5110
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005111 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5112 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005113
5114 std::string windowName = "None";
5115 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005116 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005117 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5118 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5119 : "token has capture without window";
5120 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005121 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005122
5123 return dump;
5124}
5125
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005126void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005127 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5128 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5129 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005130 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Tiger Huang721e26f2018-07-24 22:26:19 +08005132 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5133 dump += StringPrintf(INDENT "FocusedApplications:\n");
5134 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5135 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005136 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005137 const std::chrono::duration timeout =
5138 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005139 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005140 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005141 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005144 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005146
Vishnu Nairc519ff72021-01-21 08:23:08 -08005147 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005148 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005150 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005151 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005152 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5153 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005154 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005155 state.displayId, toString(state.down), toString(state.split),
5156 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005157 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005158 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005159 for (size_t i = 0; i < state.windows.size(); i++) {
5160 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005161 dump += StringPrintf(INDENT4
5162 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5163 i, touchedWindow.windowHandle->getName().c_str(),
5164 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005165 }
5166 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005167 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 }
5170 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005171 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 }
5173
arthurhung6d4bed92021-03-17 11:59:33 +08005174 if (mDragState) {
5175 dump += StringPrintf(INDENT "DragState:\n");
5176 mDragState->dump(dump, INDENT2);
5177 }
5178
Arthur Hungb92218b2018-08-14 12:00:21 +08005179 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005180 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5181 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5182 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5183 const auto& displayInfo = it->second;
5184 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5185 displayInfo.logicalHeight);
5186 displayInfo.transform.dump(dump, "transform", INDENT4);
5187 } else {
5188 dump += INDENT2 "No DisplayInfo found!\n";
5189 }
5190
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005191 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005192 dump += INDENT2 "Windows:\n";
5193 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005194 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5195 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005197 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005198 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005199 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005200 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005201 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005202 "applicationInfo.name=%s, "
5203 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005204 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005205 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005206 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005207 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005208 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005209 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005210 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005211 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005212 windowInfo->frameLeft, windowInfo->frameTop,
5213 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005214 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005215 windowInfo->applicationInfo.name.c_str(),
5216 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005217 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005218 dump += StringPrintf(", inputFeatures=%s",
5219 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005220 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005221 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005222 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005223 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005224 millis(windowInfo->dispatchingTimeout),
5225 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005226 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005227 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005228 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005229 }
5230 } else {
5231 dump += INDENT2 "Windows: <none>\n";
5232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 }
5234 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005235 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 }
5237
Michael Wright3dd60e22019-03-27 22:06:44 +00005238 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005239 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005240 const std::vector<Monitor>& monitors = it.second;
5241 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5242 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005243 }
5244 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005245 const std::vector<Monitor>& monitors = it.second;
5246 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5247 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005250 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251 }
5252
5253 nsecs_t currentTime = now();
5254
5255 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005256 if (!mRecentQueue.empty()) {
5257 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005258 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005259 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005260 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005261 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
5263 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005264 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265 }
5266
5267 // Dump event currently being dispatched.
5268 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005269 dump += INDENT "PendingEvent:\n";
5270 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005271 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005272 dump += StringPrintf(", age=%" PRId64 "ms\n",
5273 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005275 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277
5278 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005279 if (!mInboundQueue.empty()) {
5280 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005281 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005282 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005283 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005284 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005287 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
5289
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005290 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005291 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005292 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5293 const KeyReplacement& replacement = pair.first;
5294 int32_t newKeyCode = pair.second;
5295 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005297 }
5298 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005299 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005300 }
5301
Prabir Pradhancef936d2021-07-21 16:17:52 +00005302 if (!mCommandQueue.empty()) {
5303 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5304 } else {
5305 dump += INDENT "CommandQueue: <empty>\n";
5306 }
5307
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005308 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005309 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005310 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005311 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005312 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005313 connection->inputChannel->getFd().get(),
5314 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005315 connection->getWindowName().c_str(),
5316 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005317 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005319 if (!connection->outboundQueue.empty()) {
5320 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5321 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005322 dump += dumpQueue(connection->outboundQueue, currentTime);
5323
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005325 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 }
5327
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005328 if (!connection->waitQueue.empty()) {
5329 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5330 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005331 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005333 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 }
5335 }
5336 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005337 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 }
5339
5340 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005341 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5342 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005344 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 }
5346
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005347 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005348 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5349 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5350 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005351 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005352 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353}
5354
Michael Wright3dd60e22019-03-27 22:06:44 +00005355void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5356 const size_t numMonitors = monitors.size();
5357 for (size_t i = 0; i < numMonitors; i++) {
5358 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005359 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005360 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5361 dump += "\n";
5362 }
5363}
5364
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005365class LooperEventCallback : public LooperCallback {
5366public:
5367 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5368 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5369
5370private:
5371 std::function<int(int events)> mCallback;
5372};
5373
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005374Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005375 if (DEBUG_CHANNEL_CREATION) {
5376 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005379 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005380 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005381 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005382
5383 if (result) {
5384 return base::Error(result) << "Failed to open input channel pair with name " << name;
5385 }
5386
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005388 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005389 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005390 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005391 sp<Connection> connection =
5392 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005394 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5395 ALOGE("Created a new connection, but the token %p is already known", token.get());
5396 }
5397 mConnectionsByToken.emplace(token, connection);
5398
5399 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5400 this, std::placeholders::_1, token);
5401
5402 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 } // release lock
5404
5405 // Wake the looper because some connections have changed.
5406 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005407 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408}
5409
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005410Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5411 bool isGestureMonitor,
5412 const std::string& name,
5413 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005414 std::shared_ptr<InputChannel> serverChannel;
5415 std::unique_ptr<InputChannel> clientChannel;
5416 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5417 if (result) {
5418 return base::Error(result) << "Failed to open input channel pair with name " << name;
5419 }
5420
Michael Wright3dd60e22019-03-27 22:06:44 +00005421 { // acquire lock
5422 std::scoped_lock _l(mLock);
5423
5424 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005425 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5426 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005427 }
5428
Garfield Tan15601662020-09-22 15:32:38 -07005429 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005430 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005431 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005432
5433 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5434 ALOGE("Created a new connection, but the token %p is already known", token.get());
5435 }
5436 mConnectionsByToken.emplace(token, connection);
5437 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5438 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005439
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005440 auto& monitorsByDisplay =
5441 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005442 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005443
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005444 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005445 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5446 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005447 }
Garfield Tan15601662020-09-22 15:32:38 -07005448
Michael Wright3dd60e22019-03-27 22:06:44 +00005449 // Wake the looper because some connections have changed.
5450 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005451 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005452}
5453
Garfield Tan15601662020-09-22 15:32:38 -07005454status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005456 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457
Garfield Tan15601662020-09-22 15:32:38 -07005458 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 if (status) {
5460 return status;
5461 }
5462 } // release lock
5463
5464 // Wake the poll loop because removing the connection may have changed the current
5465 // synchronization state.
5466 mLooper->wake();
5467 return OK;
5468}
5469
Garfield Tan15601662020-09-22 15:32:38 -07005470status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5471 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005472 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005473 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005474 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 return BAD_VALUE;
5476 }
5477
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005478 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005479
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005481 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005484 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
5486 nsecs_t currentTime = now();
5487 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5488
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005489 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 return OK;
5491}
5492
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005493void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5494 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5495 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005496}
5497
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005498void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005499 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005500 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005501 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005502 std::vector<Monitor>& monitors = it->second;
5503 const size_t numMonitors = monitors.size();
5504 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005505 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005506 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5507 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005508 monitors.erase(monitors.begin() + i);
5509 break;
5510 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005511 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005512 if (monitors.empty()) {
5513 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005514 } else {
5515 ++it;
5516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 }
5518}
5519
Michael Wright3dd60e22019-03-27 22:06:44 +00005520status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5521 { // acquire lock
5522 std::scoped_lock _l(mLock);
5523 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5524
5525 if (!foundDisplayId) {
5526 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5527 return BAD_VALUE;
5528 }
5529 int32_t displayId = foundDisplayId.value();
5530
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005531 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5532 mTouchStatesByDisplay.find(displayId);
5533 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005534 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5535 return BAD_VALUE;
5536 }
5537
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005538 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005539 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005540 std::optional<int32_t> foundDeviceId;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07005541 for (const auto& monitor : state.gestureMonitors) {
5542 if (monitor.inputChannel->getConnectionToken() == token) {
5543 requestingChannel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005544 foundDeviceId = state.deviceId;
5545 }
5546 }
5547 if (!foundDeviceId || !state.down) {
5548 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005549 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005550 return BAD_VALUE;
5551 }
5552 int32_t deviceId = foundDeviceId.value();
5553
5554 // Send cancel events to all the input channels we're stealing from.
5555 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005556 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005557 options.deviceId = deviceId;
5558 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005559 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005560 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005561 std::shared_ptr<InputChannel> channel =
5562 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005563 if (channel != nullptr) {
5564 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005565 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005566 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005567 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005568 canceledWindows += "]";
5569 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5570 canceledWindows.c_str());
5571
Michael Wright3dd60e22019-03-27 22:06:44 +00005572 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hungfbfa5722021-11-16 02:45:54 +00005573 state.split = false;
Michael Wright3dd60e22019-03-27 22:06:44 +00005574 state.filterNonMonitors();
5575 }
5576 return OK;
5577}
5578
Prabir Pradhan99987712020-11-10 18:43:05 -08005579void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5580 { // acquire lock
5581 std::scoped_lock _l(mLock);
5582 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005583 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005584 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5585 windowHandle != nullptr ? windowHandle->getName().c_str()
5586 : "token without window");
5587 }
5588
Vishnu Nairc519ff72021-01-21 08:23:08 -08005589 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005590 if (focusedToken != windowToken) {
5591 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5592 enabled ? "enable" : "disable");
5593 return;
5594 }
5595
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005596 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005597 ALOGW("Ignoring request to %s Pointer Capture: "
5598 "window has %s requested pointer capture.",
5599 enabled ? "enable" : "disable", enabled ? "already" : "not");
5600 return;
5601 }
5602
Prabir Pradhan99987712020-11-10 18:43:05 -08005603 setPointerCaptureLocked(enabled);
5604 } // release lock
5605
5606 // Wake the thread to process command entries.
5607 mLooper->wake();
5608}
5609
Michael Wright3dd60e22019-03-27 22:06:44 +00005610std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5611 const sp<IBinder>& token) {
5612 for (const auto& it : mGestureMonitorsByDisplay) {
5613 const std::vector<Monitor>& monitors = it.second;
5614 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005615 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005616 return it.first;
5617 }
5618 }
5619 }
5620 return std::nullopt;
5621}
5622
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005623std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5624 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5625 if (gesturePid.has_value()) {
5626 return gesturePid;
5627 }
5628 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5629}
5630
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005631sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005632 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005633 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005634 }
5635
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005636 for (const auto& [token, connection] : mConnectionsByToken) {
5637 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005638 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 }
5640 }
Robert Carr4e670e52018-08-15 13:26:12 -07005641
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005642 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643}
5644
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005645std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5646 sp<Connection> connection = getConnectionLocked(connectionToken);
5647 if (connection == nullptr) {
5648 return "<nullptr>";
5649 }
5650 return connection->getInputChannelName();
5651}
5652
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005653void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005654 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005655 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005656}
5657
Prabir Pradhancef936d2021-07-21 16:17:52 +00005658void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5659 const sp<Connection>& connection, uint32_t seq,
5660 bool handled, nsecs_t consumeTime) {
5661 // Handle post-event policy actions.
5662 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5663 if (dispatchEntryIt == connection->waitQueue.end()) {
5664 return;
5665 }
5666 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5667 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5668 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5669 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5670 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5671 }
5672 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5673 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5674 connection->inputChannel->getConnectionToken(),
5675 dispatchEntry->deliveryTime, consumeTime, finishTime);
5676 }
5677
5678 bool restartEvent;
5679 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5680 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5681 restartEvent =
5682 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5683 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5684 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5685 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5686 handled);
5687 } else {
5688 restartEvent = false;
5689 }
5690
5691 // Dequeue the event and start the next cycle.
5692 // Because the lock might have been released, it is possible that the
5693 // contents of the wait queue to have been drained, so we need to double-check
5694 // a few things.
5695 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5696 if (dispatchEntryIt != connection->waitQueue.end()) {
5697 dispatchEntry = *dispatchEntryIt;
5698 connection->waitQueue.erase(dispatchEntryIt);
5699 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5700 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5701 if (!connection->responsive) {
5702 connection->responsive = isConnectionResponsive(*connection);
5703 if (connection->responsive) {
5704 // The connection was unresponsive, and now it's responsive.
5705 processConnectionResponsiveLocked(*connection);
5706 }
5707 }
5708 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005709 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005710 connection->outboundQueue.push_front(dispatchEntry);
5711 traceOutboundQueueLength(*connection);
5712 } else {
5713 releaseDispatchEntry(dispatchEntry);
5714 }
5715 }
5716
5717 // Start the next dispatch cycle for this connection.
5718 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719}
5720
Prabir Pradhancef936d2021-07-21 16:17:52 +00005721void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5722 const sp<IBinder>& newToken) {
5723 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5724 scoped_unlock unlock(mLock);
5725 mPolicy->notifyFocusChanged(oldToken, newToken);
5726 };
5727 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728}
5729
Prabir Pradhancef936d2021-07-21 16:17:52 +00005730void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5731 auto command = [this, token, x, y]() REQUIRES(mLock) {
5732 scoped_unlock unlock(mLock);
5733 mPolicy->notifyDropWindow(token, x, y);
5734 };
5735 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005736}
5737
Prabir Pradhancef936d2021-07-21 16:17:52 +00005738void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5739 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5740 scoped_unlock unlock(mLock);
5741 mPolicy->notifyUntrustedTouch(obscuringPackage);
5742 };
5743 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005744}
5745
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005746void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5747 if (connection == nullptr) {
5748 LOG_ALWAYS_FATAL("Caller must check for nullness");
5749 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005750 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5751 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005752 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005754 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005755 return;
5756 }
5757 /**
5758 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5759 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5760 * has changed. This could cause newer entries to time out before the already dispatched
5761 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5762 * processes the events linearly. So providing information about the oldest entry seems to be
5763 * most useful.
5764 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005765 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005766 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5767 std::string reason =
5768 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005769 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005770 ns2ms(currentWait),
5771 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005772 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005773 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005774
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005775 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5776
5777 // Stop waking up for events on this connection, it is already unresponsive
5778 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005779}
5780
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005781void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5782 std::string reason =
5783 StringPrintf("%s does not have a focused window", application->getName().c_str());
5784 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005785
Prabir Pradhancef936d2021-07-21 16:17:52 +00005786 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5787 scoped_unlock unlock(mLock);
5788 mPolicy->notifyNoFocusedWindowAnr(application);
5789 };
5790 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005791}
5792
chaviw98318de2021-05-19 16:45:23 -05005793void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005794 const std::string& reason) {
5795 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5796 updateLastAnrStateLocked(windowLabel, reason);
5797}
5798
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005799void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5800 const std::string& reason) {
5801 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005802 updateLastAnrStateLocked(windowLabel, reason);
5803}
5804
5805void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5806 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005808 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809 struct tm tm;
5810 localtime_r(&t, &tm);
5811 char timestr[64];
5812 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005813 mLastAnrState.clear();
5814 mLastAnrState += INDENT "ANR:\n";
5815 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005816 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5817 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005818 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819}
5820
Prabir Pradhancef936d2021-07-21 16:17:52 +00005821void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5822 KeyEntry& entry) {
5823 const KeyEvent event = createKeyEvent(entry);
5824 nsecs_t delay = 0;
5825 { // release lock
5826 scoped_unlock unlock(mLock);
5827 android::base::Timer t;
5828 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5829 entry.policyFlags);
5830 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5831 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5832 std::to_string(t.duration().count()).c_str());
5833 }
5834 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835
5836 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005837 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005838 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005839 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005841 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5842 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844}
5845
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005846void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005847 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5848 scoped_unlock unlock(mLock);
5849 mPolicy->notifyMonitorUnresponsive(pid, reason);
5850 };
5851 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005852}
5853
Prabir Pradhancef936d2021-07-21 16:17:52 +00005854void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005855 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5857 scoped_unlock unlock(mLock);
5858 mPolicy->notifyWindowUnresponsive(token, reason);
5859 };
5860 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005861}
5862
5863void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005864 auto command = [this, pid]() REQUIRES(mLock) {
5865 scoped_unlock unlock(mLock);
5866 mPolicy->notifyMonitorResponsive(pid);
5867 };
5868 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005869}
5870
Prabir Pradhancef936d2021-07-21 16:17:52 +00005871void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5872 auto command = [this, connectionToken]() REQUIRES(mLock) {
5873 scoped_unlock unlock(mLock);
5874 mPolicy->notifyWindowResponsive(connectionToken);
5875 };
5876 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005877}
5878
5879/**
5880 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5881 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5882 * command entry to the command queue.
5883 */
5884void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5885 std::string reason) {
5886 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5887 if (connection.monitor) {
5888 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5889 reason.c_str());
5890 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5891 if (!pid.has_value()) {
5892 ALOGE("Could not find unresponsive monitor for connection %s",
5893 connection.inputChannel->getName().c_str());
5894 return;
5895 }
5896 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5897 return;
5898 }
5899 // If not a monitor, must be a window
5900 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5901 reason.c_str());
5902 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5903}
5904
5905/**
5906 * Tell the policy that a connection has become responsive so that it can stop ANR.
5907 */
5908void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5909 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5910 if (connection.monitor) {
5911 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5912 if (!pid.has_value()) {
5913 ALOGE("Could not find responsive monitor for connection %s",
5914 connection.inputChannel->getName().c_str());
5915 return;
5916 }
5917 sendMonitorResponsiveCommandLocked(pid.value());
5918 return;
5919 }
5920 // If not a monitor, must be a window
5921 sendWindowResponsiveCommandLocked(connectionToken);
5922}
5923
Prabir Pradhancef936d2021-07-21 16:17:52 +00005924bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005925 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005926 KeyEntry& keyEntry, bool handled) {
5927 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005928 if (!handled) {
5929 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005930 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005931 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005932 return false;
5933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005935 // Get the fallback key state.
5936 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005937 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005938 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005939 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 connection->inputState.removeFallbackKey(originalKeyCode);
5941 }
5942
5943 if (handled || !dispatchEntry->hasForegroundTarget()) {
5944 // If the application handles the original key for which we previously
5945 // generated a fallback or if the window is not a foreground window,
5946 // then cancel the associated fallback key, if any.
5947 if (fallbackKeyCode != -1) {
5948 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005949 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5950 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5951 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5952 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5953 keyEntry.policyFlags);
5954 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005955 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957
5958 mLock.unlock();
5959
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005960 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005961 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962
5963 mLock.lock();
5964
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005965 // Cancel the fallback key.
5966 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005968 "application handled the original non-fallback key "
5969 "or is no longer a foreground target, "
5970 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 options.keyCode = fallbackKeyCode;
5972 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005974 connection->inputState.removeFallbackKey(originalKeyCode);
5975 }
5976 } else {
5977 // If the application did not handle a non-fallback key, first check
5978 // that we are in a good state to perform unhandled key event processing
5979 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005980 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005981 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005982 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5983 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5984 "since this is not an initial down. "
5985 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5986 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5987 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988 return false;
5989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005991 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005992 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5993 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5994 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5995 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5996 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005997 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005998
5999 mLock.unlock();
6000
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006001 bool fallback =
6002 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006003 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006004
6005 mLock.lock();
6006
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006007 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006008 connection->inputState.removeFallbackKey(originalKeyCode);
6009 return false;
6010 }
6011
6012 // Latch the fallback keycode for this key on an initial down.
6013 // The fallback keycode cannot change at any other point in the lifecycle.
6014 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006016 fallbackKeyCode = event.getKeyCode();
6017 } else {
6018 fallbackKeyCode = AKEYCODE_UNKNOWN;
6019 }
6020 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6021 }
6022
6023 ALOG_ASSERT(fallbackKeyCode != -1);
6024
6025 // Cancel the fallback key if the policy decides not to send it anymore.
6026 // We will continue to dispatch the key to the policy but we will no
6027 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006028 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6029 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006030 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6031 if (fallback) {
6032 ALOGD("Unhandled key event: Policy requested to send key %d"
6033 "as a fallback for %d, but on the DOWN it had requested "
6034 "to send %d instead. Fallback canceled.",
6035 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6036 } else {
6037 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6038 "but on the DOWN it had requested to send %d. "
6039 "Fallback canceled.",
6040 originalKeyCode, fallbackKeyCode);
6041 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043
6044 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6045 "canceling fallback, policy no longer desires it");
6046 options.keyCode = fallbackKeyCode;
6047 synthesizeCancelationEventsForConnectionLocked(connection, options);
6048
6049 fallback = false;
6050 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006051 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006052 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 }
6054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006056 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6057 {
6058 std::string msg;
6059 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6060 connection->inputState.getFallbackKeys();
6061 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6062 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6063 }
6064 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6065 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006068
6069 if (fallback) {
6070 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006071 keyEntry.eventTime = event.getEventTime();
6072 keyEntry.deviceId = event.getDeviceId();
6073 keyEntry.source = event.getSource();
6074 keyEntry.displayId = event.getDisplayId();
6075 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6076 keyEntry.keyCode = fallbackKeyCode;
6077 keyEntry.scanCode = event.getScanCode();
6078 keyEntry.metaState = event.getMetaState();
6079 keyEntry.repeatCount = event.getRepeatCount();
6080 keyEntry.downTime = event.getDownTime();
6081 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006082
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006083 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6084 ALOGD("Unhandled key event: Dispatching fallback key. "
6085 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6086 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6087 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088 return true; // restart the event
6089 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006090 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6091 ALOGD("Unhandled key event: No fallback key.");
6092 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006093
6094 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006095 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 }
6097 }
6098 return false;
6099}
6100
Prabir Pradhancef936d2021-07-21 16:17:52 +00006101bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006102 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006103 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104 return false;
6105}
6106
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107void InputDispatcher::traceInboundQueueLengthLocked() {
6108 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006109 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 }
6111}
6112
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006113void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114 if (ATRACE_ENABLED()) {
6115 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006116 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6117 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118 }
6119}
6120
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006121void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006122 if (ATRACE_ENABLED()) {
6123 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006124 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6125 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006126 }
6127}
6128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006129void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006130 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006132 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133 dumpDispatchStateLocked(dump);
6134
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006135 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006136 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006137 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006138 }
6139}
6140
6141void InputDispatcher::monitor() {
6142 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006143 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006144 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006145 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146}
6147
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006148/**
6149 * Wake up the dispatcher and wait until it processes all events and commands.
6150 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6151 * this method can be safely called from any thread, as long as you've ensured that
6152 * the work you are interested in completing has already been queued.
6153 */
6154bool InputDispatcher::waitForIdle() {
6155 /**
6156 * Timeout should represent the longest possible time that a device might spend processing
6157 * events and commands.
6158 */
6159 constexpr std::chrono::duration TIMEOUT = 100ms;
6160 std::unique_lock lock(mLock);
6161 mLooper->wake();
6162 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6163 return result == std::cv_status::no_timeout;
6164}
6165
Vishnu Naire798b472020-07-23 13:52:21 -07006166/**
6167 * Sets focus to the window identified by the token. This must be called
6168 * after updating any input window handles.
6169 *
6170 * Params:
6171 * request.token - input channel token used to identify the window that should gain focus.
6172 * request.focusedToken - the token that the caller expects currently to be focused. If the
6173 * specified token does not match the currently focused window, this request will be dropped.
6174 * If the specified focused token matches the currently focused window, the call will succeed.
6175 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6176 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6177 * when requesting the focus change. This determines which request gets
6178 * precedence if there is a focus change request from another source such as pointer down.
6179 */
Vishnu Nair958da932020-08-21 17:12:37 -07006180void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6181 { // acquire lock
6182 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006183 std::optional<FocusResolver::FocusChanges> changes =
6184 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6185 if (changes) {
6186 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006187 }
6188 } // release lock
6189 // Wake up poll loop since it may need to make new input dispatching choices.
6190 mLooper->wake();
6191}
6192
Vishnu Nairc519ff72021-01-21 08:23:08 -08006193void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6194 if (changes.oldFocus) {
6195 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006196 if (focusedInputChannel) {
6197 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6198 "focus left window");
6199 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006200 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006201 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006202 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006203 if (changes.newFocus) {
6204 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006205 }
6206
Prabir Pradhan99987712020-11-10 18:43:05 -08006207 // If a window has pointer capture, then it must have focus. We need to ensure that this
6208 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6209 // If the window loses focus before it loses pointer capture, then the window can be in a state
6210 // where it has pointer capture but not focus, violating the contract. Therefore we must
6211 // dispatch the pointer capture event before the focus event. Since focus events are added to
6212 // the front of the queue (above), we add the pointer capture event to the front of the queue
6213 // after the focus events are added. This ensures the pointer capture event ends up at the
6214 // front.
6215 disablePointerCaptureForcedLocked();
6216
Vishnu Nairc519ff72021-01-21 08:23:08 -08006217 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006218 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006219 }
6220}
Vishnu Nair958da932020-08-21 17:12:37 -07006221
Prabir Pradhan99987712020-11-10 18:43:05 -08006222void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006223 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006224 return;
6225 }
6226
6227 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6228
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006229 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006230 setPointerCaptureLocked(false);
6231 }
6232
6233 if (!mWindowTokenWithPointerCapture) {
6234 // No need to send capture changes because no window has capture.
6235 return;
6236 }
6237
6238 if (mPendingEvent != nullptr) {
6239 // Move the pending event to the front of the queue. This will give the chance
6240 // for the pending event to be dropped if it is a captured event.
6241 mInboundQueue.push_front(mPendingEvent);
6242 mPendingEvent = nullptr;
6243 }
6244
6245 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006246 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006247 mInboundQueue.push_front(std::move(entry));
6248}
6249
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006250void InputDispatcher::setPointerCaptureLocked(bool enable) {
6251 mCurrentPointerCaptureRequest.enable = enable;
6252 mCurrentPointerCaptureRequest.seq++;
6253 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006254 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006255 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256 };
6257 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006258}
6259
Vishnu Nair599f1412021-06-21 10:39:58 -07006260void InputDispatcher::displayRemoved(int32_t displayId) {
6261 { // acquire lock
6262 std::scoped_lock _l(mLock);
6263 // Set an empty list to remove all handles from the specific display.
6264 setInputWindowsLocked(/* window handles */ {}, displayId);
6265 setFocusedApplicationLocked(displayId, nullptr);
6266 // Call focus resolver to clean up stale requests. This must be called after input windows
6267 // have been removed for the removed display.
6268 mFocusResolver.displayRemoved(displayId);
6269 } // release lock
6270
6271 // Wake up poll loop since it may need to make new input dispatching choices.
6272 mLooper->wake();
6273}
6274
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006275void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6276 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006277 // The listener sends the windows as a flattened array. Separate the windows by display for
6278 // more convenient parsing.
6279 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006280 for (const auto& info : windowInfos) {
6281 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6282 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6283 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006284
6285 { // acquire lock
6286 std::scoped_lock _l(mLock);
6287 mDisplayInfos.clear();
6288 for (const auto& displayInfo : displayInfos) {
6289 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6290 }
6291
6292 for (const auto& [displayId, handles] : handlesPerDisplay) {
6293 setInputWindowsLocked(handles, displayId);
6294 }
6295 }
6296 // Wake up poll loop since it may need to make new input dispatching choices.
6297 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006298}
6299
Vishnu Nair062a8672021-09-03 16:07:44 -07006300bool InputDispatcher::shouldDropInput(
6301 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6302 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6303 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6304 isWindowObscuredLocked(windowHandle))) {
6305 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6306 "%" PRId32 ".",
6307 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6308 windowHandle->getInfo()->inputFeatures.string().c_str(),
6309 windowHandle->getInfo()->displayId);
6310 return true;
6311 }
6312 return false;
6313}
6314
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006315void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6316 const std::vector<gui::WindowInfo>& windowInfos,
6317 const std::vector<DisplayInfo>& displayInfos) {
6318 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6319}
6320
Garfield Tane84e6f92019-08-29 17:28:41 -07006321} // namespace android::inputdispatcher