blob: f50c9e104317278dd8f2a5b3105ecb6fe191ff67 [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
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002067 // be delivered to a new window which supports split touch. Pointers from a mouse device
2068 // should never be split.
2069 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002070 }
2071
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002072 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002073 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002074 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2075 newHoverWindowHandle = nullptr;
2076 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002078 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002079 }
2080
2081 std::vector<sp<WindowInfoHandle>> newTouchedWindows;
2082 if (newTouchedWindowHandle != nullptr) {
2083 newTouchedWindows.push_back(newTouchedWindowHandle);
2084 }
2085
2086 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2087 const WindowInfo& info = *windowHandle->getInfo();
2088
2089 if (info.paused) {
2090 ALOGI("Not sending touch event to %s because it is paused",
2091 windowHandle->getName().c_str());
2092 continue;
2093 }
2094
2095 // Ensure the window has a connection and the connection is responsive
2096 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2097 if (!isResponsive) {
2098 ALOGW("Not sending touch gesture to %s because it is not responsive",
2099 windowHandle->getName().c_str());
2100 continue;
2101 }
2102
2103 // Drop events that can't be trusted due to occlusion
2104 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2105 TouchOcclusionInfo occlusionInfo =
2106 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2107 if (!isTouchTrustedLocked(occlusionInfo)) {
2108 if (DEBUG_TOUCH_OCCLUSION) {
2109 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2110 for (const auto& log : occlusionInfo.debugInfo) {
2111 ALOGD("%s", log.c_str());
2112 }
2113 }
2114 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2115 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2116 ALOGW("Dropping untrusted touch event due to %s/%d",
2117 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2118 continue;
2119 }
2120 }
2121 }
2122
2123 // Drop touch events if requested by input feature
2124 if (shouldDropInput(entry, windowHandle)) {
2125 continue;
2126 }
2127
2128 // Set target flags.
2129 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2130
2131 // There should only be one new foreground (non-spy) window at this location.
2132 targetFlags |= InputTarget::FLAG_FOREGROUND;
2133
2134 if (isSplit) {
2135 targetFlags |= InputTarget::FLAG_SPLIT;
2136 }
2137 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2138 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2139 } else if (isWindowObscuredLocked(windowHandle)) {
2140 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2141 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002142
2143 // Update the temporary touch state.
2144 BitSet32 pointerIds;
2145 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002146 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002147 pointerIds.markBit(pointerId);
2148 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002149
2150 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002152
2153 const std::vector<Monitor> newGestureMonitors = isDown
2154 ? selectResponsiveMonitorsLocked(
2155 getValueByKey(mGestureMonitorsByDisplay, displayId))
2156 : std::vector<Monitor>{};
2157
2158 if (newTouchedWindows.empty() && newGestureMonitors.empty() &&
2159 tempTouchState.gestureMonitors.empty()) {
2160 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
2161 "(%d, %d) in display %" PRId32 ".",
2162 x, y, displayId);
2163 injectionResult = InputEventInjectionResult::FAILED;
2164 goto Failed;
Arthur Hung2ea44b92021-11-23 07:42:21 +00002165 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166
2167 tempTouchState.addGestureMonitors(newGestureMonitors);
2168
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 } else {
2170 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2171
2172 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002174 if (DEBUG_FOCUS) {
2175 ALOGD("Dropping event because the pointer is not down or we previously "
2176 "dropped the pointer down event in display %" PRId32,
2177 displayId);
2178 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002179 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 goto Failed;
2181 }
2182
arthurhung6d4bed92021-03-17 11:59:33 +08002183 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002184
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002186 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002187 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002188 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2189 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190
chaviw98318de2021-05-19 16:45:23 -05002191 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002192 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002193 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002194
2195 // Drop touch events if requested by input feature
2196 if (newTouchedWindowHandle != nullptr &&
2197 shouldDropInput(entry, newTouchedWindowHandle)) {
2198 newTouchedWindowHandle = nullptr;
2199 }
2200
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002201 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2202 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002203 if (DEBUG_FOCUS) {
2204 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2205 oldTouchedWindowHandle->getName().c_str(),
2206 newTouchedWindowHandle->getName().c_str(), displayId);
2207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002209 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2210 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2211 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212
2213 // Make a slippery entrance into the new window.
2214 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002215 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002218 int32_t targetFlags =
2219 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 if (isSplit) {
2221 targetFlags |= InputTarget::FLAG_SPLIT;
2222 }
2223 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2224 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002225 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2226 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228
2229 BitSet32 pointerIds;
2230 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002231 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002233 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235 }
2236 }
2237
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002238 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002240 // Let the previous window know that the hover sequence is over, unless we already did
2241 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002242 if (mLastHoverWindowHandle != nullptr &&
2243 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2244 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002245 if (DEBUG_HOVER) {
2246 ALOGD("Sending hover exit event to window %s.",
2247 mLastHoverWindowHandle->getName().c_str());
2248 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002249 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2250 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
2252
Garfield Tandf26e862020-07-01 20:18:19 -07002253 // Let the new window know that the hover sequence is starting, unless we already did it
2254 // when dispatching it as is to newTouchedWindowHandle.
2255 if (newHoverWindowHandle != nullptr &&
2256 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2257 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002258 if (DEBUG_HOVER) {
2259 ALOGD("Sending hover enter event to window %s.",
2260 newHoverWindowHandle->getName().c_str());
2261 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002262 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2263 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2264 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266 }
2267
2268 // Check permission to inject into all touched foreground windows and ensure there
2269 // is at least one touched foreground window.
2270 {
2271 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2274 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002275 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002276 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 injectionPermission = INJECTION_PERMISSION_DENIED;
2278 goto Failed;
2279 }
2280 }
2281 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002282 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002283 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002284 ALOGI("Dropping event because there is no touched foreground window in display "
2285 "%" PRId32 " or gesture monitor to receive it.",
2286 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002287 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 goto Failed;
2289 }
2290
2291 // Permission granted to injection into all touched foreground windows.
2292 injectionPermission = INJECTION_PERMISSION_GRANTED;
2293 }
2294
2295 // Check whether windows listening for outside touches are owned by the same UID. If it is
2296 // set the policy flag that we will not reveal coordinate information to this window.
2297 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002298 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002299 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002300 if (foregroundWindowHandle) {
2301 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002302 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002304 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2305 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2306 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 InputTarget::FLAG_ZERO_COORDS,
2308 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311 }
2312 }
2313 }
2314
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 // If this is the first pointer going down and the touched window has a wallpaper
2316 // then also add the touched wallpaper windows so they are locked in for the duration
2317 // of the touch gesture.
2318 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2319 // engine only supports touch events. We would need to add a mechanism similar
2320 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2321 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002322 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002323 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002324 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002325 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002326 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002327 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2328 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002329 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002330 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002331 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 .addOrUpdateWindow(windowHandle,
2333 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2334 InputTarget::
2335 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2336 InputTarget::FLAG_DISPATCH_AS_IS,
2337 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
2339 }
2340 }
2341 }
2342
2343 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002344 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002346 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 }
2350
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002351 for (const auto& monitor : tempTouchState.gestureMonitors) {
2352 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002353 }
2354
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 // Drop the outside or hover touch windows since we will not care about them
2356 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002357 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
2359Failed:
2360 // Check injection permission once and for all.
2361 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002362 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 injectionPermission = INJECTION_PERMISSION_GRANTED;
2364 } else {
2365 injectionPermission = INJECTION_PERMISSION_DENIED;
2366 }
2367 }
2368
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002369 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2370 return injectionResult;
2371 }
2372
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002374 if (!wrongDevice) {
2375 if (switchedDevice) {
2376 if (DEBUG_FOCUS) {
2377 ALOGD("Conflicting pointer actions: Switched to a different device.");
2378 }
2379 *outConflictingPointerActions = true;
2380 }
2381
2382 if (isHoverAction) {
2383 // Started hovering, therefore no longer down.
2384 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002385 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002386 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2387 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 *outConflictingPointerActions = true;
2390 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002391 tempTouchState.reset();
2392 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2393 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2394 tempTouchState.deviceId = entry.deviceId;
2395 tempTouchState.source = entry.source;
2396 tempTouchState.displayId = displayId;
2397 }
2398 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2399 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2400 // All pointers up or canceled.
2401 tempTouchState.reset();
2402 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2403 // First pointer went down.
2404 if (oldState && oldState->down) {
2405 if (DEBUG_FOCUS) {
2406 ALOGD("Conflicting pointer actions: Down received while already down.");
2407 }
2408 *outConflictingPointerActions = true;
2409 }
2410 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2411 // One pointer went up.
2412 if (isSplit) {
2413 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2414 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002416 for (size_t i = 0; i < tempTouchState.windows.size();) {
2417 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2418 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2419 touchedWindow.pointerIds.clearBit(pointerId);
2420 if (touchedWindow.pointerIds.isEmpty()) {
2421 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2422 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002425 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002427 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002428 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002429
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002430 // Save changes unless the action was scroll in which case the temporary touch
2431 // state was only valid for this one action.
2432 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2433 if (tempTouchState.displayId >= 0) {
2434 mTouchStatesByDisplay[displayId] = tempTouchState;
2435 } else {
2436 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002440 // Update hover state.
2441 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
2443
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 return injectionResult;
2445}
2446
arthurhung6d4bed92021-03-17 11:59:33 +08002447void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002448 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002449 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002450 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002451 if (dropWindow) {
2452 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002453 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002454 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002455 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002456 }
2457 mDragState.reset();
2458}
2459
2460void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2461 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002462 return;
2463 }
2464
arthurhung6d4bed92021-03-17 11:59:33 +08002465 if (!mDragState->isStartDrag) {
2466 mDragState->isStartDrag = true;
2467 mDragState->isStylusButtonDownAtStart =
2468 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2469 }
2470
arthurhungb89ccb02020-12-30 16:19:01 +08002471 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2472 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2473 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2474 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002475 // Handle the special case : stylus button no longer pressed.
2476 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2477 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2478 finishDragAndDrop(entry.displayId, x, y);
2479 return;
2480 }
2481
chaviw98318de2021-05-19 16:45:23 -05002482 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002483 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002484 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002485 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002486 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2487 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2488 if (mDragState->dragHoverWindowHandle != nullptr) {
2489 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2490 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002491 }
arthurhung6d4bed92021-03-17 11:59:33 +08002492 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002493 }
2494 // enqueue drag location if needed.
2495 if (hoverWindowHandle != nullptr) {
2496 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2497 }
arthurhung6d4bed92021-03-17 11:59:33 +08002498 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2499 finishDragAndDrop(entry.displayId, x, y);
2500 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002501 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002502 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002503 }
2504}
2505
chaviw98318de2021-05-19 16:45:23 -05002506void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002507 int32_t targetFlags, BitSet32 pointerIds,
2508 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002509 std::vector<InputTarget>::iterator it =
2510 std::find_if(inputTargets.begin(), inputTargets.end(),
2511 [&windowHandle](const InputTarget& inputTarget) {
2512 return inputTarget.inputChannel->getConnectionToken() ==
2513 windowHandle->getToken();
2514 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002515
chaviw98318de2021-05-19 16:45:23 -05002516 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002517
2518 if (it == inputTargets.end()) {
2519 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002520 std::shared_ptr<InputChannel> inputChannel =
2521 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002522 if (inputChannel == nullptr) {
2523 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2524 return;
2525 }
2526 inputTarget.inputChannel = inputChannel;
2527 inputTarget.flags = targetFlags;
2528 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002529 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2530 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002531 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002532 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002533 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002534 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002535 inputTargets.push_back(inputTarget);
2536 it = inputTargets.end() - 1;
2537 }
2538
2539 ALOG_ASSERT(it->flags == targetFlags);
2540 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2541
chaviw1ff3d1e2020-07-01 15:53:47 -07002542 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543}
2544
Michael Wright3dd60e22019-03-27 22:06:44 +00002545void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002546 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002547 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2548 mGlobalMonitorsByDisplay.find(displayId);
2549
2550 if (it != mGlobalMonitorsByDisplay.end()) {
2551 const std::vector<Monitor>& monitors = it->second;
2552 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002553 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 }
2556}
2557
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002558void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002559 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002560 InputTarget target;
2561 target.inputChannel = monitor.inputChannel;
2562 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002563 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002564 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002565 const auto& displayTransform = it->second.transform;
2566 target.displayTransform = displayTransform;
2567 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002568 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002569 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002570 inputTargets.push_back(target);
2571}
2572
chaviw98318de2021-05-19 16:45:23 -05002573bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 const InjectionState* injectionState) {
2575 if (injectionState &&
2576 (windowHandle == nullptr ||
2577 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2578 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002579 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 "owned by uid %d",
2582 injectionState->injectorPid, injectionState->injectorUid,
2583 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 } else {
2585 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
2588 return false;
2589 }
2590 return true;
2591}
2592
Robert Carrc9bf1d32020-04-13 17:21:08 -07002593/**
2594 * Indicate whether one window handle should be considered as obscuring
2595 * another window handle. We only check a few preconditions. Actually
2596 * checking the bounds is left to the caller.
2597 */
chaviw98318de2021-05-19 16:45:23 -05002598static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2599 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002600 // Compare by token so cloned layers aren't counted
2601 if (haveSameToken(windowHandle, otherHandle)) {
2602 return false;
2603 }
2604 auto info = windowHandle->getInfo();
2605 auto otherInfo = otherHandle->getInfo();
2606 if (!otherInfo->visible) {
2607 return false;
chaviw98318de2021-05-19 16:45:23 -05002608 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002609 // Those act as if they were invisible, so we don't need to flag them.
2610 // We do want to potentially flag touchable windows even if they have 0
2611 // opacity, since they can consume touches and alter the effects of the
2612 // user interaction (eg. apps that rely on
2613 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2614 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2615 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002616 } else if (info->ownerUid == otherInfo->ownerUid) {
2617 // If ownerUid is the same we don't generate occlusion events as there
2618 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002619 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002620 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002621 return false;
2622 } else if (otherInfo->displayId != info->displayId) {
2623 return false;
2624 }
2625 return true;
2626}
2627
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002628/**
2629 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2630 * untrusted, one should check:
2631 *
2632 * 1. If result.hasBlockingOcclusion is true.
2633 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2634 * BLOCK_UNTRUSTED.
2635 *
2636 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2637 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2638 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2639 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2640 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2641 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2642 *
2643 * If neither of those is true, then it means the touch can be allowed.
2644 */
2645InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002646 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2647 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002648 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002649 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002650 TouchOcclusionInfo info;
2651 info.hasBlockingOcclusion = false;
2652 info.obscuringOpacity = 0;
2653 info.obscuringUid = -1;
2654 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002655 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002656 if (windowHandle == otherHandle) {
2657 break; // All future windows are below us. Exit early.
2658 }
chaviw98318de2021-05-19 16:45:23 -05002659 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002660 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2661 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002662 if (DEBUG_TOUCH_OCCLUSION) {
2663 info.debugInfo.push_back(
2664 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2665 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002666 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2667 // we perform the checks below to see if the touch can be propagated or not based on the
2668 // window's touch occlusion mode
2669 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2670 info.hasBlockingOcclusion = true;
2671 info.obscuringUid = otherInfo->ownerUid;
2672 info.obscuringPackage = otherInfo->packageName;
2673 break;
2674 }
2675 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2676 uint32_t uid = otherInfo->ownerUid;
2677 float opacity =
2678 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2679 // Given windows A and B:
2680 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2681 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2682 opacityByUid[uid] = opacity;
2683 if (opacity > info.obscuringOpacity) {
2684 info.obscuringOpacity = opacity;
2685 info.obscuringUid = uid;
2686 info.obscuringPackage = otherInfo->packageName;
2687 }
2688 }
2689 }
2690 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002691 if (DEBUG_TOUCH_OCCLUSION) {
2692 info.debugInfo.push_back(
2693 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2694 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002695 return info;
2696}
2697
chaviw98318de2021-05-19 16:45:23 -05002698std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002699 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002700 return StringPrintf(INDENT2
2701 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2702 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2703 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2704 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002705 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002706 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002707 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2708 info->frameTop, info->frameRight, info->frameBottom,
2709 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002710 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2711 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2712 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002713}
2714
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002715bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2716 if (occlusionInfo.hasBlockingOcclusion) {
2717 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2718 occlusionInfo.obscuringUid);
2719 return false;
2720 }
2721 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2722 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2723 "%.2f, maximum allowed = %.2f)",
2724 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2725 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2726 return false;
2727 }
2728 return true;
2729}
2730
chaviw98318de2021-05-19 16:45:23 -05002731bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002734 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2735 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002736 if (windowHandle == otherHandle) {
2737 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 }
chaviw98318de2021-05-19 16:45:23 -05002739 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002740 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002741 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 return true;
2743 }
2744 }
2745 return false;
2746}
2747
chaviw98318de2021-05-19 16:45:23 -05002748bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002749 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002750 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2751 const WindowInfo* windowInfo = windowHandle->getInfo();
2752 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002753 if (windowHandle == otherHandle) {
2754 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002755 }
chaviw98318de2021-05-19 16:45:23 -05002756 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002757 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002758 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002759 return true;
2760 }
2761 }
2762 return false;
2763}
2764
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002765std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002766 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002767 if (applicationHandle != nullptr) {
2768 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002769 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 } else {
2771 return applicationHandle->getName();
2772 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002773 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002774 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002776 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 }
2778}
2779
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002780void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002781 if (!isUserActivityEvent(eventEntry)) {
2782 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002783 return;
2784 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002785 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002786 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002787 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002788 const WindowInfo* info = focusedWindowHandle->getInfo();
2789 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002790 if (DEBUG_DISPATCH_CYCLE) {
2791 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 return;
2794 }
2795 }
2796
2797 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002798 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002799 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002800 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2801 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002802 return;
2803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002805 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002806 eventType = USER_ACTIVITY_EVENT_TOUCH;
2807 }
2808 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002810 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002811 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2812 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002813 return;
2814 }
2815 eventType = USER_ACTIVITY_EVENT_BUTTON;
2816 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002818 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002819 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002820 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002821 break;
2822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
2824
Prabir Pradhancef936d2021-07-21 16:17:52 +00002825 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2826 REQUIRES(mLock) {
2827 scoped_unlock unlock(mLock);
2828 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2829 };
2830 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831}
2832
2833void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002834 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002835 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002836 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002837 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002839 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002840 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002841 ATRACE_NAME(message.c_str());
2842 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002843 if (DEBUG_DISPATCH_CYCLE) {
2844 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2845 "globalScaleFactor=%f, pointerIds=0x%x %s",
2846 connection->getInputChannelName().c_str(), inputTarget.flags,
2847 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2848 inputTarget.getPointerInfoString().c_str());
2849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850
2851 // Skip this event if the connection status is not normal.
2852 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002853 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002854 if (DEBUG_DISPATCH_CYCLE) {
2855 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002856 connection->getInputChannelName().c_str(),
2857 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 return;
2860 }
2861
2862 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002863 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2864 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2865 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002866 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002868 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002869 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002870 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002871 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 if (!splitMotionEntry) {
2873 return; // split event was dropped
2874 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002875 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2876 std::string reason = std::string("reason=pointer cancel on split window");
2877 android_log_event_list(LOGTAG_INPUT_CANCEL)
2878 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2879 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002880 if (DEBUG_FOCUS) {
2881 ALOGD("channel '%s' ~ Split motion event.",
2882 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002883 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002884 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002885 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2886 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 return;
2888 }
2889 }
2890
2891 // Not splitting. Enqueue dispatch entries for the event as is.
2892 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2893}
2894
2895void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002897 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002898 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002899 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002901 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002902 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002903 ATRACE_NAME(message.c_str());
2904 }
2905
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002906 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907
2908 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002909 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002911 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002913 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002915 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002917 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002919 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921
2922 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002923 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 startDispatchCycleLocked(currentTime, connection);
2925 }
2926}
2927
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002929 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002930 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002932 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2934 connection->getInputChannelName().c_str(),
2935 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002936 ATRACE_NAME(message.c_str());
2937 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002938 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 if (!(inputTargetFlags & dispatchMode)) {
2940 return;
2941 }
2942 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2943
2944 // This is a new event.
2945 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002946 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002947 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002949 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2950 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002951 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002954 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002956 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 dispatchEntry->resolvedAction = keyEntry.action;
2958 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2961 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002962 if (DEBUG_DISPATCH_CYCLE) {
2963 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2964 "event",
2965 connection->getInputChannelName().c_str());
2966 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 return; // skip the inconsistent event
2968 }
2969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002972 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002974 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2975 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2976 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2977 static_cast<int32_t>(IdGenerator::Source::OTHER);
2978 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2980 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2981 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2982 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2983 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2984 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2985 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2986 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2987 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2988 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2989 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002990 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002991 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 }
2993 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002994 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2995 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002996 if (DEBUG_DISPATCH_CYCLE) {
2997 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2998 "enter event",
2999 connection->getInputChannelName().c_str());
3000 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003001 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3002 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3008 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3009 }
3010 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3011 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3015 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003016 if (DEBUG_DISPATCH_CYCLE) {
3017 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3018 "event",
3019 connection->getInputChannelName().c_str());
3020 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 return; // skip the inconsistent event
3022 }
3023
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003024 dispatchEntry->resolvedEventId =
3025 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3026 ? mIdGenerator.nextId()
3027 : motionEntry.id;
3028 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3029 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3030 ") to MotionEvent(id=0x%" PRIx32 ").",
3031 motionEntry.id, dispatchEntry->resolvedEventId);
3032 ATRACE_NAME(message.c_str());
3033 }
3034
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003035 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3036 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3037 // Skip reporting pointer down outside focus to the policy.
3038 break;
3039 }
3040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003041 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003042 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003043
3044 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003046 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003047 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003048 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3049 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003050 break;
3051 }
Chris Yef59a2f42020-10-16 12:55:26 -07003052 case EventEntry::Type::SENSOR: {
3053 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3054 break;
3055 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003056 case EventEntry::Type::CONFIGURATION_CHANGED:
3057 case EventEntry::Type::DEVICE_RESET: {
3058 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003059 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003060 break;
3061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 }
3063
3064 // Remember that we are waiting for this dispatch to complete.
3065 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003066 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
3068
3069 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003070 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003071 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003072}
3073
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003074/**
3075 * This function is purely for debugging. It helps us understand where the user interaction
3076 * was taking place. For example, if user is touching launcher, we will see a log that user
3077 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3078 * We will see both launcher and wallpaper in that list.
3079 * Once the interaction with a particular set of connections starts, no new logs will be printed
3080 * until the set of interacted connections changes.
3081 *
3082 * The following items are skipped, to reduce the logspam:
3083 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3084 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3085 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3086 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3087 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003088 */
3089void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3090 const std::vector<InputTarget>& targets) {
3091 // Skip ACTION_UP events, and all events other than keys and motions
3092 if (entry.type == EventEntry::Type::KEY) {
3093 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3094 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3095 return;
3096 }
3097 } else if (entry.type == EventEntry::Type::MOTION) {
3098 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3099 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3100 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3101 return;
3102 }
3103 } else {
3104 return; // Not a key or a motion
3105 }
3106
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003107 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003108 std::vector<sp<Connection>> newConnections;
3109 for (const InputTarget& target : targets) {
3110 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3111 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3112 continue; // Skip windows that receive ACTION_OUTSIDE
3113 }
3114
3115 sp<IBinder> token = target.inputChannel->getConnectionToken();
3116 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003117 if (connection == nullptr) {
3118 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003119 }
3120 newConnectionTokens.insert(std::move(token));
3121 newConnections.emplace_back(connection);
3122 }
3123 if (newConnectionTokens == mInteractionConnectionTokens) {
3124 return; // no change
3125 }
3126 mInteractionConnectionTokens = newConnectionTokens;
3127
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003128 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003129 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003130 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003131 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003132 std::string message = "Interaction with: " + targetList;
3133 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003134 message += "<none>";
3135 }
3136 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3137}
3138
chaviwfd6d3512019-03-25 13:23:49 -07003139void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003140 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003141 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003142 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3143 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003144 return;
3145 }
3146
Vishnu Nairc519ff72021-01-21 08:23:08 -08003147 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003148 if (focusedToken == token) {
3149 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003150 return;
3151 }
3152
Prabir Pradhancef936d2021-07-21 16:17:52 +00003153 auto command = [this, token]() REQUIRES(mLock) {
3154 scoped_unlock unlock(mLock);
3155 mPolicy->onPointerDownOutsideFocus(token);
3156 };
3157 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158}
3159
3160void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003162 if (ATRACE_ENABLED()) {
3163 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003165 ATRACE_NAME(message.c_str());
3166 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003167 if (DEBUG_DISPATCH_CYCLE) {
3168 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003171 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003172 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003174 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003175 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003176 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177
3178 // Publish the event.
3179 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3181 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003182 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3184 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003186 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003187 status = connection->inputPublisher
3188 .publishKeyEvent(dispatchEntry->seq,
3189 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3190 keyEntry.source, keyEntry.displayId,
3191 std::move(hmac), dispatchEntry->resolvedAction,
3192 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3193 keyEntry.scanCode, keyEntry.metaState,
3194 keyEntry.repeatCount, keyEntry.downTime,
3195 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003199 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003200 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003203 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204
chaviw82357092020-01-28 13:13:06 -08003205 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003206 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3208 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003209 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003210 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3211 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003212 // Don't apply window scale here since we don't want scale to affect raw
3213 // coordinates. The scale will be sent back to the client and applied
3214 // later when requesting relative coordinates.
3215 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3216 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 }
3218 usingCoords = scaledCoords;
3219 }
3220 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 // We don't want the dispatch target to know.
3222 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 scaledCoords[i].clear();
3225 }
3226 usingCoords = scaledCoords;
3227 }
3228 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003229
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003230 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231
3232 // Publish the motion event.
3233 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003234 .publishMotionEvent(dispatchEntry->seq,
3235 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 motionEntry.deviceId, motionEntry.source,
3237 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003238 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003239 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 motionEntry.edgeFlags, motionEntry.metaState,
3242 motionEntry.buttonState,
3243 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003244 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003245 motionEntry.xPrecision, motionEntry.yPrecision,
3246 motionEntry.xCursorPosition,
3247 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003248 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003249 motionEntry.downTime, motionEntry.eventTime,
3250 motionEntry.pointerCount,
3251 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 break;
3253 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003254
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003255 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003257 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003258 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003259 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003260 break;
3261 }
3262
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003263 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3264 const TouchModeEntry& touchModeEntry =
3265 static_cast<const TouchModeEntry&>(eventEntry);
3266 status = connection->inputPublisher
3267 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3268 touchModeEntry.inTouchMode);
3269
3270 break;
3271 }
3272
Prabir Pradhan99987712020-11-10 18:43:05 -08003273 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3274 const auto& captureEntry =
3275 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3276 status = connection->inputPublisher
3277 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003278 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003279 break;
3280 }
3281
arthurhungb89ccb02020-12-30 16:19:01 +08003282 case EventEntry::Type::DRAG: {
3283 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3284 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3285 dragEntry.id, dragEntry.x,
3286 dragEntry.y,
3287 dragEntry.isExiting);
3288 break;
3289 }
3290
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003291 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003292 case EventEntry::Type::DEVICE_RESET:
3293 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003294 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003295 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 }
3299
3300 // Check the result.
3301 if (status) {
3302 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003303 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 "This is unexpected because the wait queue is empty, so the pipe "
3306 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003307 "event to it, status=%s(%d)",
3308 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3309 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3311 } else {
3312 // Pipe is full and we are waiting for the app to finish process some events
3313 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003314 if (DEBUG_DISPATCH_CYCLE) {
3315 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3316 "waiting for the application to catch up",
3317 connection->getInputChannelName().c_str());
3318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 }
3320 } else {
3321 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003322 "status=%s(%d)",
3323 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3324 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3326 }
3327 return;
3328 }
3329
3330 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003331 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3332 connection->outboundQueue.end(),
3333 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003334 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003335 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003336 if (connection->responsive) {
3337 mAnrTracker.insert(dispatchEntry->timeoutTime,
3338 connection->inputChannel->getConnectionToken());
3339 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003340 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 }
3342}
3343
chaviw09c8d2d2020-08-24 15:48:26 -07003344std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3345 size_t size;
3346 switch (event.type) {
3347 case VerifiedInputEvent::Type::KEY: {
3348 size = sizeof(VerifiedKeyEvent);
3349 break;
3350 }
3351 case VerifiedInputEvent::Type::MOTION: {
3352 size = sizeof(VerifiedMotionEvent);
3353 break;
3354 }
3355 }
3356 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3357 return mHmacKeyManager.sign(start, size);
3358}
3359
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003360const std::array<uint8_t, 32> InputDispatcher::getSignature(
3361 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003362 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3363 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003364 // Only sign events up and down events as the purely move events
3365 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003366 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003367 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003368
3369 VerifiedMotionEvent verifiedEvent =
3370 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3371 verifiedEvent.actionMasked = actionMasked;
3372 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3373 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003374}
3375
3376const std::array<uint8_t, 32> InputDispatcher::getSignature(
3377 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3378 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3379 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3380 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003381 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003382}
3383
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003386 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003387 if (DEBUG_DISPATCH_CYCLE) {
3388 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3389 connection->getInputChannelName().c_str(), seq, toString(handled));
3390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003392 if (connection->status == Connection::Status::BROKEN ||
3393 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 return;
3395 }
3396
3397 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003398 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3399 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3400 };
3401 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402}
3403
3404void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 const sp<Connection>& connection,
3406 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003407 if (DEBUG_DISPATCH_CYCLE) {
3408 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3409 connection->getInputChannelName().c_str(), toString(notify));
3410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
3412 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003413 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417
3418 // The connection appears to be unrecoverably broken.
3419 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003420 if (connection->status == Connection::Status::NORMAL) {
3421 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422
3423 if (notify) {
3424 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003425 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3426 connection->getInputChannelName().c_str());
3427
3428 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003429 scoped_unlock unlock(mLock);
3430 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3431 };
3432 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 }
3434 }
3435}
3436
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003437void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3438 while (!queue.empty()) {
3439 DispatchEntry* dispatchEntry = queue.front();
3440 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003441 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 }
3443}
3444
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003445void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003447 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449 delete dispatchEntry;
3450}
3451
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003452int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3453 std::scoped_lock _l(mLock);
3454 sp<Connection> connection = getConnectionLocked(connectionToken);
3455 if (connection == nullptr) {
3456 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3457 connectionToken.get(), events);
3458 return 0; // remove the callback
3459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003461 bool notify;
3462 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3463 if (!(events & ALOOPER_EVENT_INPUT)) {
3464 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3465 "events=0x%x",
3466 connection->getInputChannelName().c_str(), events);
3467 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
3469
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003470 nsecs_t currentTime = now();
3471 bool gotOne = false;
3472 status_t status = OK;
3473 for (;;) {
3474 Result<InputPublisher::ConsumerResponse> result =
3475 connection->inputPublisher.receiveConsumerResponse();
3476 if (!result.ok()) {
3477 status = result.error().code();
3478 break;
3479 }
3480
3481 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3482 const InputPublisher::Finished& finish =
3483 std::get<InputPublisher::Finished>(*result);
3484 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3485 finish.consumeTime);
3486 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003487 if (shouldReportMetricsForConnection(*connection)) {
3488 const InputPublisher::Timeline& timeline =
3489 std::get<InputPublisher::Timeline>(*result);
3490 mLatencyTracker
3491 .trackGraphicsLatency(timeline.inputEventId,
3492 connection->inputChannel->getConnectionToken(),
3493 std::move(timeline.graphicsTimeline));
3494 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003495 }
3496 gotOne = true;
3497 }
3498 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003499 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003500 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 return 1;
3502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 }
3504
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003505 notify = status != DEAD_OBJECT || !connection->monitor;
3506 if (notify) {
3507 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3508 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3509 status);
3510 }
3511 } else {
3512 // Monitor channels are never explicitly unregistered.
3513 // We do it automatically when the remote endpoint is closed so don't warn about them.
3514 const bool stillHaveWindowHandle =
3515 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3516 notify = !connection->monitor && stillHaveWindowHandle;
3517 if (notify) {
3518 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3519 connection->getInputChannelName().c_str(), events);
3520 }
3521 }
3522
3523 // Remove the channel.
3524 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3525 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526}
3527
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003528void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003530 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003531 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533}
3534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003535void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003536 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003537 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3538 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3539}
3540
3541void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3542 const CancelationOptions& options,
3543 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3544 for (const auto& it : monitorsByDisplay) {
3545 const std::vector<Monitor>& monitors = it.second;
3546 for (const Monitor& monitor : monitors) {
3547 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003548 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003549 }
3550}
3551
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003553 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003554 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003555 if (connection == nullptr) {
3556 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003558
3559 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560}
3561
3562void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3563 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003564 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 return;
3566 }
3567
3568 nsecs_t currentTime = now();
3569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003570 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003571 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003573 if (cancelationEvents.empty()) {
3574 return;
3575 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003576 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3577 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3578 "with reality: %s, mode=%d.",
3579 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3580 options.mode);
3581 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003582
Arthur Hungb3307ee2021-10-14 10:57:37 +00003583 std::string reason = std::string("reason=").append(options.reason);
3584 android_log_event_list(LOGTAG_INPUT_CANCEL)
3585 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3586
Svet Ganov5d3bc372020-01-26 23:11:07 -08003587 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003588 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003589 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3590 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003591 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003592 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003593 target.globalScaleFactor = windowInfo->globalScaleFactor;
3594 }
3595 target.inputChannel = connection->inputChannel;
3596 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3597
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003598 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003599 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003600 switch (cancelationEventEntry->type) {
3601 case EventEntry::Type::KEY: {
3602 logOutboundKeyDetails("cancel - ",
3603 static_cast<const KeyEntry&>(*cancelationEventEntry));
3604 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003606 case EventEntry::Type::MOTION: {
3607 logOutboundMotionDetails("cancel - ",
3608 static_cast<const MotionEntry&>(*cancelationEventEntry));
3609 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003611 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003612 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003613 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3614 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003615 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003616 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003617 break;
3618 }
3619 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003620 case EventEntry::Type::DEVICE_RESET:
3621 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003622 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003623 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003624 break;
3625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003628 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3629 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003631
3632 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633}
3634
Svet Ganov5d3bc372020-01-26 23:11:07 -08003635void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3636 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003637 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003638 return;
3639 }
3640
3641 nsecs_t currentTime = now();
3642
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003643 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003644 connection->inputState.synthesizePointerDownEvents(currentTime);
3645
3646 if (downEvents.empty()) {
3647 return;
3648 }
3649
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003650 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003651 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3652 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003653 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654
3655 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003656 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003657 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3658 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003659 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003660 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 target.globalScaleFactor = windowInfo->globalScaleFactor;
3662 }
3663 target.inputChannel = connection->inputChannel;
3664 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3665
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003666 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003667 switch (downEventEntry->type) {
3668 case EventEntry::Type::MOTION: {
3669 logOutboundMotionDetails("down - ",
3670 static_cast<const MotionEntry&>(*downEventEntry));
3671 break;
3672 }
3673
3674 case EventEntry::Type::KEY:
3675 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003676 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003677 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003678 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003679 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003680 case EventEntry::Type::SENSOR:
3681 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003682 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003683 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003684 break;
3685 }
3686 }
3687
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003688 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3689 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003690 }
3691
3692 startDispatchCycleLocked(currentTime, connection);
3693}
3694
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003695std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3696 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 ALOG_ASSERT(pointerIds.value != 0);
3698
3699 uint32_t splitPointerIndexMap[MAX_POINTERS];
3700 PointerProperties splitPointerProperties[MAX_POINTERS];
3701 PointerCoords splitPointerCoords[MAX_POINTERS];
3702
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003703 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 uint32_t splitPointerCount = 0;
3705
3706 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003709 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 uint32_t pointerId = uint32_t(pointerProperties.id);
3711 if (pointerIds.hasBit(pointerId)) {
3712 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3713 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3714 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003715 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 splitPointerCount += 1;
3717 }
3718 }
3719
3720 if (splitPointerCount != pointerIds.count()) {
3721 // This is bad. We are missing some of the pointers that we expected to deliver.
3722 // Most likely this indicates that we received an ACTION_MOVE events that has
3723 // different pointer ids than we expected based on the previous ACTION_DOWN
3724 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3725 // in this way.
3726 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003727 "we expected there to be %d pointers. This probably means we received "
3728 "a broken sequence of pointer ids from the input device.",
3729 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003730 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 }
3732
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003733 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3736 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3738 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003739 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 uint32_t pointerId = uint32_t(pointerProperties.id);
3741 if (pointerIds.hasBit(pointerId)) {
3742 if (pointerIds.count() == 1) {
3743 // The first/last pointer went down/up.
3744 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003745 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003746 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3747 ? AMOTION_EVENT_ACTION_CANCEL
3748 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 } else {
3750 // A secondary pointer went down/up.
3751 uint32_t splitPointerIndex = 0;
3752 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3753 splitPointerIndex += 1;
3754 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003755 action = maskedAction |
3756 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 }
3758 } else {
3759 // An unrelated pointer changed.
3760 action = AMOTION_EVENT_ACTION_MOVE;
3761 }
3762 }
3763
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003764 int32_t newId = mIdGenerator.nextId();
3765 if (ATRACE_ENABLED()) {
3766 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3767 ") to MotionEvent(id=0x%" PRIx32 ").",
3768 originalMotionEntry.id, newId);
3769 ATRACE_NAME(message.c_str());
3770 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003771 std::unique_ptr<MotionEntry> splitMotionEntry =
3772 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3773 originalMotionEntry.deviceId, originalMotionEntry.source,
3774 originalMotionEntry.displayId,
3775 originalMotionEntry.policyFlags, action,
3776 originalMotionEntry.actionButton,
3777 originalMotionEntry.flags, originalMotionEntry.metaState,
3778 originalMotionEntry.buttonState,
3779 originalMotionEntry.classification,
3780 originalMotionEntry.edgeFlags,
3781 originalMotionEntry.xPrecision,
3782 originalMotionEntry.yPrecision,
3783 originalMotionEntry.xCursorPosition,
3784 originalMotionEntry.yCursorPosition,
3785 originalMotionEntry.downTime, splitPointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00003786 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003788 if (originalMotionEntry.injectionState) {
3789 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 splitMotionEntry->injectionState->refCount += 1;
3791 }
3792
3793 return splitMotionEntry;
3794}
3795
3796void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003797 if (DEBUG_INBOUND_EVENT_DETAILS) {
3798 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
Antonio Kantekf16f2832021-09-28 04:39:20 +00003801 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003803 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003805 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3806 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3807 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 } // release lock
3809
3810 if (needWake) {
3811 mLooper->wake();
3812 }
3813}
3814
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003815/**
3816 * If one of the meta shortcuts is detected, process them here:
3817 * Meta + Backspace -> generate BACK
3818 * Meta + Enter -> generate HOME
3819 * This will potentially overwrite keyCode and metaState.
3820 */
3821void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003822 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003823 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3824 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3825 if (keyCode == AKEYCODE_DEL) {
3826 newKeyCode = AKEYCODE_BACK;
3827 } else if (keyCode == AKEYCODE_ENTER) {
3828 newKeyCode = AKEYCODE_HOME;
3829 }
3830 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003831 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003832 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003833 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003834 keyCode = newKeyCode;
3835 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3836 }
3837 } else if (action == AKEY_EVENT_ACTION_UP) {
3838 // In order to maintain a consistent stream of up and down events, check to see if the key
3839 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3840 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003841 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003842 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003843 auto replacementIt = mReplacedKeys.find(replacement);
3844 if (replacementIt != mReplacedKeys.end()) {
3845 keyCode = replacementIt->second;
3846 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003847 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3848 }
3849 }
3850}
3851
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003853 if (DEBUG_INBOUND_EVENT_DETAILS) {
3854 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3855 "policyFlags=0x%x, action=0x%x, "
3856 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3857 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3858 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3859 args->downTime);
3860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 if (!validateKeyEvent(args->action)) {
3862 return;
3863 }
3864
3865 uint32_t policyFlags = args->policyFlags;
3866 int32_t flags = args->flags;
3867 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003868 // InputDispatcher tracks and generates key repeats on behalf of
3869 // whatever notifies it, so repeatCount should always be set to 0
3870 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3872 policyFlags |= POLICY_FLAG_VIRTUAL;
3873 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 if (policyFlags & POLICY_FLAG_FUNCTION) {
3876 metaState |= AMETA_FUNCTION_ON;
3877 }
3878
3879 policyFlags |= POLICY_FLAG_TRUSTED;
3880
Michael Wright78f24442014-08-06 15:55:28 -07003881 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003882 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003883
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003885 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003886 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3887 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888
Michael Wright2b3c3302018-03-02 17:19:13 +00003889 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003891 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3892 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003893 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
Antonio Kantekf16f2832021-09-28 04:39:20 +00003896 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 { // acquire lock
3898 mLock.lock();
3899
3900 if (shouldSendKeyToInputFilterLocked(args)) {
3901 mLock.unlock();
3902
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003903 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3905 return; // event was consumed by the filter
3906 }
3907
3908 mLock.lock();
3909 }
3910
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003911 std::unique_ptr<KeyEntry> newEntry =
3912 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3913 args->displayId, policyFlags, args->action, flags,
3914 keyCode, args->scanCode, metaState, repeatCount,
3915 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003917 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 mLock.unlock();
3919 } // release lock
3920
3921 if (needWake) {
3922 mLooper->wake();
3923 }
3924}
3925
3926bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3927 return mInputFilterEnabled;
3928}
3929
3930void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003931 if (DEBUG_INBOUND_EVENT_DETAILS) {
3932 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3933 "displayId=%" PRId32 ", policyFlags=0x%x, "
3934 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3935 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3936 "yCursorPosition=%f, downTime=%" PRId64,
3937 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3938 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3939 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3940 args->xCursorPosition, args->yCursorPosition, args->downTime);
3941 for (uint32_t i = 0; i < args->pointerCount; i++) {
3942 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3943 "x=%f, y=%f, pressure=%f, size=%f, "
3944 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3945 "orientation=%f",
3946 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3948 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3949 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3950 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3951 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3952 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3953 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3954 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3955 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3959 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 return;
3961 }
3962
3963 uint32_t policyFlags = args->policyFlags;
3964 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003965
3966 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003967 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003968 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3969 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972
Antonio Kantekf16f2832021-09-28 04:39:20 +00003973 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 { // acquire lock
3975 mLock.lock();
3976
3977 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003978 ui::Transform displayTransform;
3979 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3980 displayTransform = it->second.transform;
3981 }
3982
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 mLock.unlock();
3984
3985 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003986 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3987 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003988 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003989 displayTransform, args->xPrecision, args->yPrecision,
3990 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003991 args->downTime, args->eventTime, args->pointerCount,
3992 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
3994 policyFlags |= POLICY_FLAG_FILTERED;
3995 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3996 return; // event was consumed by the filter
3997 }
3998
3999 mLock.lock();
4000 }
4001
4002 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004003 std::unique_ptr<MotionEntry> newEntry =
4004 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4005 args->source, args->displayId, policyFlags,
4006 args->action, args->actionButton, args->flags,
4007 args->metaState, args->buttonState,
4008 args->classification, args->edgeFlags,
4009 args->xPrecision, args->yPrecision,
4010 args->xCursorPosition, args->yCursorPosition,
4011 args->downTime, args->pointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00004012 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004014 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4015 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4016 !mInputFilterEnabled) {
4017 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4018 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4019 }
4020
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004021 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 mLock.unlock();
4023 } // release lock
4024
4025 if (needWake) {
4026 mLooper->wake();
4027 }
4028}
4029
Chris Yef59a2f42020-10-16 12:55:26 -07004030void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 if (DEBUG_INBOUND_EVENT_DETAILS) {
4032 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4033 " sensorType=%s",
4034 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004035 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004036 }
Chris Yef59a2f42020-10-16 12:55:26 -07004037
Antonio Kantekf16f2832021-09-28 04:39:20 +00004038 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004039 { // acquire lock
4040 mLock.lock();
4041
4042 // Just enqueue a new sensor event.
4043 std::unique_ptr<SensorEntry> newEntry =
4044 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4045 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4046 args->sensorType, args->accuracy,
4047 args->accuracyChanged, args->values);
4048
4049 needWake = enqueueInboundEventLocked(std::move(newEntry));
4050 mLock.unlock();
4051 } // release lock
4052
4053 if (needWake) {
4054 mLooper->wake();
4055 }
4056}
4057
Chris Yefb552902021-02-03 17:18:37 -08004058void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004059 if (DEBUG_INBOUND_EVENT_DETAILS) {
4060 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4061 args->deviceId, args->isOn);
4062 }
Chris Yefb552902021-02-03 17:18:37 -08004063 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4064}
4065
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004067 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068}
4069
4070void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004071 if (DEBUG_INBOUND_EVENT_DETAILS) {
4072 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4073 "switchMask=0x%08x",
4074 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076
4077 uint32_t policyFlags = args->policyFlags;
4078 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080}
4081
4082void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004083 if (DEBUG_INBOUND_EVENT_DETAILS) {
4084 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4085 args->deviceId);
4086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087
Antonio Kantekf16f2832021-09-28 04:39:20 +00004088 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004090 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004092 std::unique_ptr<DeviceResetEntry> newEntry =
4093 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4094 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 } // release lock
4096
4097 if (needWake) {
4098 mLooper->wake();
4099 }
4100}
4101
Prabir Pradhan7e186182020-11-10 13:56:45 -08004102void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004103 if (DEBUG_INBOUND_EVENT_DETAILS) {
4104 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004105 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004106 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004107
Antonio Kantekf16f2832021-09-28 04:39:20 +00004108 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004109 { // acquire lock
4110 std::scoped_lock _l(mLock);
4111 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004112 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004113 needWake = enqueueInboundEventLocked(std::move(entry));
4114 } // release lock
4115
4116 if (needWake) {
4117 mLooper->wake();
4118 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004119}
4120
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004121InputEventInjectionResult InputDispatcher::injectInputEvent(
4122 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4123 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004124 if (DEBUG_INBOUND_EVENT_DETAILS) {
4125 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4126 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4127 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4128 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004129 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
4131 policyFlags |= POLICY_FLAG_INJECTED;
4132 if (hasInjectionPermission(injectorPid, injectorUid)) {
4133 policyFlags |= POLICY_FLAG_TRUSTED;
4134 }
4135
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004136 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4138 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4139 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4140 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4141 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004143 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004144 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004145 }
4146
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004147 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004150 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4151 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004153 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004156 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004157 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4158 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4159 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004160 int32_t keyCode = incomingKey.getKeyCode();
4161 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004162 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004164 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004165 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004166 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4167 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4168 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4171 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004172 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173
4174 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4175 android::base::Timer t;
4176 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4177 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4178 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4179 std::to_string(t.duration().count()).c_str());
4180 }
4181 }
4182
4183 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004184 std::unique_ptr<KeyEntry> injectedEntry =
4185 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004186 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004187 incomingKey.getDisplayId(), policyFlags, action,
4188 flags, keyCode, incomingKey.getScanCode(), metaState,
4189 incomingKey.getRepeatCount(),
4190 incomingKey.getDownTime());
4191 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004196 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004197 const int32_t action = motionEvent.getAction();
4198 const bool isPointerEvent =
4199 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4200 // If a pointer event has no displayId specified, inject it to the default display.
4201 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4202 ? ADISPLAY_ID_DEFAULT
4203 : event->getDisplayId();
4204 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004205 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004206 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004207 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004209 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 }
4211
4212 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004213 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004214 android::base::Timer t;
4215 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4216 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4217 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4218 std::to_string(t.duration().count()).c_str());
4219 }
4220 }
4221
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004222 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4223 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4224 }
4225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4228 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004229 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4231 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004232 displayId, policyFlags, action, actionButton,
4233 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 motionEvent.getButtonState(),
4235 motionEvent.getClassification(),
4236 motionEvent.getEdgeFlags(),
4237 motionEvent.getXPrecision(),
4238 motionEvent.getYPrecision(),
4239 motionEvent.getRawXCursorPosition(),
4240 motionEvent.getRawYCursorPosition(),
4241 motionEvent.getDownTime(), uint32_t(pointerCount),
Alex Chau663fc832021-12-03 10:37:54 +00004242 pointerProperties, samplePointerCoords,
4243 motionEvent.getXOffset(),
4244 motionEvent.getYOffset());
4245 transformMotionEntryForInjectionLocked(*injectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004246 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 sampleEventTimes += 1;
4249 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004250 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4252 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004253 displayId, policyFlags, action, actionButton,
4254 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004255 motionEvent.getButtonState(),
4256 motionEvent.getClassification(),
4257 motionEvent.getEdgeFlags(),
4258 motionEvent.getXPrecision(),
4259 motionEvent.getYPrecision(),
4260 motionEvent.getRawXCursorPosition(),
4261 motionEvent.getRawYCursorPosition(),
4262 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263 uint32_t(pointerCount), pointerProperties,
Alex Chau663fc832021-12-03 10:37:54 +00004264 samplePointerCoords, motionEvent.getXOffset(),
4265 motionEvent.getYOffset());
4266 transformMotionEntryForInjectionLocked(*nextInjectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 }
4269 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004273 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004274 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276
4277 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004278 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 injectionState->injectionIsAsync = true;
4280 }
4281
4282 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004283 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284
4285 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004286 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004288 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 }
4290
4291 mLock.unlock();
4292
4293 if (needWake) {
4294 mLooper->wake();
4295 }
4296
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004299 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 if (syncMode == InputEventInjectionSync::NONE) {
4302 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 } else {
4304 for (;;) {
4305 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 break;
4308 }
4309
4310 nsecs_t remainingTimeout = endTime - now();
4311 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004312 if (DEBUG_INJECTION) {
4313 ALOGD("injectInputEvent - Timed out waiting for injection result "
4314 "to become available.");
4315 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004316 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 break;
4318 }
4319
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004320 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4324 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004326 if (DEBUG_INJECTION) {
4327 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4328 injectionState->pendingForegroundDispatches);
4329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 nsecs_t remainingTimeout = endTime - now();
4331 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004332 if (DEBUG_INJECTION) {
4333 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4334 "dispatches to finish.");
4335 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004336 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 break;
4338 }
4339
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004340 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342 }
4343 }
4344
4345 injectionState->release();
4346 } // release lock
4347
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004348 if (DEBUG_INJECTION) {
4349 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4350 injectionResult, injectorPid, injectorUid);
4351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352
4353 return injectionResult;
4354}
4355
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004356std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004357 std::array<uint8_t, 32> calculatedHmac;
4358 std::unique_ptr<VerifiedInputEvent> result;
4359 switch (event.getType()) {
4360 case AINPUT_EVENT_TYPE_KEY: {
4361 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4362 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4363 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004364 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004365 break;
4366 }
4367 case AINPUT_EVENT_TYPE_MOTION: {
4368 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4369 VerifiedMotionEvent verifiedMotionEvent =
4370 verifiedMotionEventFromMotionEvent(motionEvent);
4371 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004372 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004373 break;
4374 }
4375 default: {
4376 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4377 return nullptr;
4378 }
4379 }
4380 if (calculatedHmac == INVALID_HMAC) {
4381 return nullptr;
4382 }
4383 if (calculatedHmac != event.getHmac()) {
4384 return nullptr;
4385 }
4386 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004387}
4388
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 return injectorUid == 0 ||
4391 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392}
4393
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004394void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004396 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004398 if (DEBUG_INJECTION) {
4399 ALOGD("Setting input event injection result to %d. "
4400 "injectorPid=%d, injectorUid=%d",
4401 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004404 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 // Log the outcome since the injector did not wait for the injection result.
4406 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 ALOGV("Asynchronous input event injection succeeded.");
4409 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004410 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 ALOGW("Asynchronous input event injection failed.");
4412 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 ALOGW("Asynchronous input event injection permission denied.");
4415 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 ALOGW("Asynchronous input event injection timed out.");
4418 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 case InputEventInjectionResult::PENDING:
4420 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4421 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 }
4423 }
4424
4425 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004426 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 }
4428}
4429
Alex Chau663fc832021-12-03 10:37:54 +00004430void InputDispatcher::transformMotionEntryForInjectionLocked(MotionEntry& entry) const {
4431 const bool isRelativeMouseEvent = isFromSource(entry.source, AINPUT_SOURCE_MOUSE_RELATIVE);
4432 if (!isRelativeMouseEvent && !isFromSource(entry.source, AINPUT_SOURCE_CLASS_POINTER)) {
4433 return;
4434 }
4435
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004436 // Input injection works in the logical display coordinate space, but the input pipeline works
4437 // display space, so we need to transform the injected events accordingly.
4438 const auto it = mDisplayInfos.find(entry.displayId);
4439 if (it == mDisplayInfos.end()) return;
Alex Chau663fc832021-12-03 10:37:54 +00004440 const auto& transformToDisplay = it->second.transform.inverse();
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004441
4442 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4443 PointerCoords& pc = entry.pointerCoords[i];
Alex Chau663fc832021-12-03 10:37:54 +00004444 const auto xy = isRelativeMouseEvent
4445 ? transformWithoutTranslation(transformToDisplay, pc.getX(), pc.getY())
4446 : transformToDisplay.transform(pc.getXYValue());
4447 pc.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
4448 pc.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004449
Alex Chau663fc832021-12-03 10:37:54 +00004450 // Axes with relative values never represent points on a screen, so they should never have
4451 // translation applied. If a device does not report relative values, these values are always
4452 // 0, and will remain unaffected by the following operation.
4453 const auto rel =
4454 transformWithoutTranslation(transformToDisplay,
4455 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
4456 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4457 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, rel.x);
4458 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, rel.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004459 }
4460}
4461
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004462void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4463 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 if (injectionState) {
4465 injectionState->pendingForegroundDispatches += 1;
4466 }
4467}
4468
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004469void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4470 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 if (injectionState) {
4472 injectionState->pendingForegroundDispatches -= 1;
4473
4474 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004475 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 }
4477 }
4478}
4479
chaviw98318de2021-05-19 16:45:23 -05004480const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004481 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004482 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004483 auto it = mWindowHandlesByDisplay.find(displayId);
4484 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004485}
4486
chaviw98318de2021-05-19 16:45:23 -05004487sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004488 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004489 if (windowHandleToken == nullptr) {
4490 return nullptr;
4491 }
4492
Arthur Hungb92218b2018-08-14 12:00:21 +08004493 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004494 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4495 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004496 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004497 return windowHandle;
4498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 }
4500 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004501 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502}
4503
chaviw98318de2021-05-19 16:45:23 -05004504sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4505 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004506 if (windowHandleToken == nullptr) {
4507 return nullptr;
4508 }
4509
chaviw98318de2021-05-19 16:45:23 -05004510 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004511 if (windowHandle->getToken() == windowHandleToken) {
4512 return windowHandle;
4513 }
4514 }
4515 return nullptr;
4516}
4517
chaviw98318de2021-05-19 16:45:23 -05004518sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4519 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004520 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004521 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4522 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004523 if (handle->getId() == windowHandle->getId() &&
4524 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004525 if (windowHandle->getInfo()->displayId != it.first) {
4526 ALOGE("Found window %s in display %" PRId32
4527 ", but it should belong to display %" PRId32,
4528 windowHandle->getName().c_str(), it.first,
4529 windowHandle->getInfo()->displayId);
4530 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004531 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 }
4534 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004535 return nullptr;
4536}
4537
chaviw98318de2021-05-19 16:45:23 -05004538sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004539 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4540 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541}
4542
chaviw98318de2021-05-19 16:45:23 -05004543bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004544 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4545 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004546 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004547 if (connection != nullptr && noInputChannel) {
4548 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4549 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4550 return false;
4551 }
4552
4553 if (connection == nullptr) {
4554 if (!noInputChannel) {
4555 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4556 }
4557 return false;
4558 }
4559 if (!connection->responsive) {
4560 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4561 return false;
4562 }
4563 return true;
4564}
4565
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004566std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4567 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004568 auto connectionIt = mConnectionsByToken.find(token);
4569 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004570 return nullptr;
4571 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004572 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004573}
4574
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004575void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004576 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4577 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004578 // Remove all handles on a display if there are no windows left.
4579 mWindowHandlesByDisplay.erase(displayId);
4580 return;
4581 }
4582
4583 // Since we compare the pointer of input window handles across window updates, we need
4584 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004585 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4586 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4587 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004588 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004589 }
4590
chaviw98318de2021-05-19 16:45:23 -05004591 std::vector<sp<WindowInfoHandle>> newHandles;
4592 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004593 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004594 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004595 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004596 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4597 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4598 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004599 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004600 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004601 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004602 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004603 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004604 }
4605
4606 if (info->displayId != displayId) {
4607 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4608 handle->getName().c_str(), displayId, info->displayId);
4609 continue;
4610 }
4611
Robert Carredd13602020-04-13 17:24:34 -07004612 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4613 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004614 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004615 oldHandle->updateFrom(handle);
4616 newHandles.push_back(oldHandle);
4617 } else {
4618 newHandles.push_back(handle);
4619 }
4620 }
4621
4622 // Insert or replace
4623 mWindowHandlesByDisplay[displayId] = newHandles;
4624}
4625
Arthur Hung72d8dc32020-03-28 00:48:39 +00004626void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004627 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004628 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004629 { // acquire lock
4630 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004631 for (const auto& [displayId, handles] : handlesPerDisplay) {
4632 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004633 }
4634 }
4635 // Wake up poll loop since it may need to make new input dispatching choices.
4636 mLooper->wake();
4637}
4638
Arthur Hungb92218b2018-08-14 12:00:21 +08004639/**
4640 * Called from InputManagerService, update window handle list by displayId that can receive input.
4641 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4642 * If set an empty list, remove all handles from the specific display.
4643 * For focused handle, check if need to change and send a cancel event to previous one.
4644 * For removed handle, check if need to send a cancel event if already in touch.
4645 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004646void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004647 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004648 if (DEBUG_FOCUS) {
4649 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004650 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004651 windowList += iwh->getName() + " ";
4652 }
4653 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004656 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004657 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004658 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004659 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004660 if (noInputWindow && window->getToken() != nullptr) {
4661 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4662 window->getName().c_str());
4663 window->releaseChannel();
4664 }
4665 }
4666
Arthur Hung72d8dc32020-03-28 00:48:39 +00004667 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004668 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004670 // Save the old windows' orientation by ID before it gets updated.
4671 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004672 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004673 oldWindowOrientations.emplace(handle->getId(),
4674 handle->getInfo()->transform.getOrientation());
4675 }
4676
chaviw98318de2021-05-19 16:45:23 -05004677 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004678
chaviw98318de2021-05-19 16:45:23 -05004679 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004680 if (mLastHoverWindowHandle &&
4681 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4682 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004683 mLastHoverWindowHandle = nullptr;
4684 }
4685
Vishnu Nairc519ff72021-01-21 08:23:08 -08004686 std::optional<FocusResolver::FocusChanges> changes =
4687 mFocusResolver.setInputWindows(displayId, windowHandles);
4688 if (changes) {
4689 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004692 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4693 mTouchStatesByDisplay.find(displayId);
4694 if (stateIt != mTouchStatesByDisplay.end()) {
4695 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004696 for (size_t i = 0; i < state.windows.size();) {
4697 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004698 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004699 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004700 ALOGD("Touched window was removed: %s in display %" PRId32,
4701 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004702 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004703 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004704 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4705 if (touchedInputChannel != nullptr) {
4706 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4707 "touched window was removed");
4708 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004709 // Since we are about to drop the touch, cancel the events for the wallpaper as
4710 // well.
4711 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4712 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4713 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4714 if (wallpaper != nullptr) {
4715 sp<Connection> wallpaperConnection =
4716 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004717 if (wallpaperConnection != nullptr) {
4718 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4719 options);
4720 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004721 }
4722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004724 state.windows.erase(state.windows.begin() + i);
4725 } else {
4726 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 }
4728 }
arthurhungb89ccb02020-12-30 16:19:01 +08004729
arthurhung6d4bed92021-03-17 11:59:33 +08004730 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004731 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004732 if (mDragState &&
4733 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004734 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004735 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004736 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004737 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004738
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004739 // Determine if the orientation of any of the input windows have changed, and cancel all
4740 // pointer events if necessary.
4741 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4742 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4743 if (newWindowHandle != nullptr &&
4744 newWindowHandle->getInfo()->transform.getOrientation() !=
4745 oldWindowOrientations[oldWindowHandle->getId()]) {
4746 std::shared_ptr<InputChannel> inputChannel =
4747 getInputChannelLocked(newWindowHandle->getToken());
4748 if (inputChannel != nullptr) {
4749 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4750 "touched window's orientation changed");
4751 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004752 }
4753 }
4754 }
4755
Arthur Hung72d8dc32020-03-28 00:48:39 +00004756 // Release information for windows that are no longer present.
4757 // This ensures that unused input channels are released promptly.
4758 // Otherwise, they might stick around until the window handle is destroyed
4759 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004760 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004761 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004762 if (DEBUG_FOCUS) {
4763 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004764 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004765 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004766 // To avoid making too many calls into the compat framework, only
4767 // check for window flags when windows are going away.
4768 // TODO(b/157929241) : delete this. This is only needed temporarily
4769 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004770 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004771 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4772 oldWindowHandle->getName().c_str());
4773 if (mCompatService != nullptr) {
4774 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4775 oldWindowHandle->getInfo()->ownerUid);
4776 }
4777 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004778 }
chaviw291d88a2019-02-14 10:33:58 -08004779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780}
4781
4782void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004783 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004784 if (DEBUG_FOCUS) {
4785 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4786 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4787 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004788 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004789 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004790 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 } // release lock
4792
4793 // Wake up poll loop since it may need to make new input dispatching choices.
4794 mLooper->wake();
4795}
4796
Vishnu Nair599f1412021-06-21 10:39:58 -07004797void InputDispatcher::setFocusedApplicationLocked(
4798 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4799 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4800 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4801
4802 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4803 return; // This application is already focused. No need to wake up or change anything.
4804 }
4805
4806 // Set the new application handle.
4807 if (inputApplicationHandle != nullptr) {
4808 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4809 } else {
4810 mFocusedApplicationHandlesByDisplay.erase(displayId);
4811 }
4812
4813 // No matter what the old focused application was, stop waiting on it because it is
4814 // no longer focused.
4815 resetNoFocusedWindowTimeoutLocked();
4816}
4817
Tiger Huang721e26f2018-07-24 22:26:19 +08004818/**
4819 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4820 * the display not specified.
4821 *
4822 * We track any unreleased events for each window. If a window loses the ability to receive the
4823 * released event, we will send a cancel event to it. So when the focused display is changed, we
4824 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4825 * display. The display-specified events won't be affected.
4826 */
4827void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004828 if (DEBUG_FOCUS) {
4829 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4830 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004831 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004832 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004833
4834 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004835 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004836 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004837 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004838 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004839 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004840 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004841 CancelationOptions
4842 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4843 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004844 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004845 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4846 }
4847 }
4848 mFocusedDisplayId = displayId;
4849
Chris Ye3c2d6f52020-08-09 10:39:48 -07004850 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004851 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004852 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004853
Vishnu Nairad321cd2020-08-20 16:40:21 -07004854 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004855 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004856 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004857 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004858 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004859 }
4860 }
4861 }
4862
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004863 if (DEBUG_FOCUS) {
4864 logDispatchStateLocked();
4865 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004866 } // release lock
4867
4868 // Wake up poll loop since it may need to make new input dispatching choices.
4869 mLooper->wake();
4870}
4871
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004873 if (DEBUG_FOCUS) {
4874 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876
4877 bool changed;
4878 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004879 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880
4881 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4882 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 }
4885
4886 if (mDispatchEnabled && !enabled) {
4887 resetAndDropEverythingLocked("dispatcher is being disabled");
4888 }
4889
4890 mDispatchEnabled = enabled;
4891 mDispatchFrozen = frozen;
4892 changed = true;
4893 } else {
4894 changed = false;
4895 }
4896
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004897 if (DEBUG_FOCUS) {
4898 logDispatchStateLocked();
4899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 } // release lock
4901
4902 if (changed) {
4903 // Wake up poll loop since it may need to make new input dispatching choices.
4904 mLooper->wake();
4905 }
4906}
4907
4908void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004909 if (DEBUG_FOCUS) {
4910 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
4913 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004914 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 if (mInputFilterEnabled == enabled) {
4917 return;
4918 }
4919
4920 mInputFilterEnabled = enabled;
4921 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4922 } // release lock
4923
4924 // Wake up poll loop since there might be work to do to drop everything.
4925 mLooper->wake();
4926}
4927
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004928void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004929 bool needWake = false;
4930 {
4931 std::scoped_lock lock(mLock);
4932 if (mInTouchMode == inTouchMode) {
4933 return;
4934 }
4935 if (DEBUG_TOUCH_MODE) {
4936 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4937 toString(inTouchMode));
4938 // TODO(b/198487159): Also print the current last interacted apps.
4939 }
4940
4941 // TODO(b/198499018): Store touch mode per display.
4942 mInTouchMode = inTouchMode;
4943
4944 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4945 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4946 needWake = enqueueInboundEventLocked(std::move(entry));
4947 } // release lock
4948
4949 if (needWake) {
4950 mLooper->wake();
4951 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004952}
4953
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004954void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4955 if (opacity < 0 || opacity > 1) {
4956 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4957 return;
4958 }
4959
4960 std::scoped_lock lock(mLock);
4961 mMaximumObscuringOpacityForTouch = opacity;
4962}
4963
4964void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4965 std::scoped_lock lock(mLock);
4966 mBlockUntrustedTouchesMode = mode;
4967}
4968
Arthur Hungabbb9d82021-09-01 14:52:30 +00004969std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4970 const sp<IBinder>& token) {
4971 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4972 for (TouchedWindow& w : state.windows) {
4973 if (w.windowHandle->getToken() == token) {
4974 return std::make_pair(&state, &w);
4975 }
4976 }
4977 }
4978 return std::make_pair(nullptr, nullptr);
4979}
4980
arthurhungb89ccb02020-12-30 16:19:01 +08004981bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4982 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004983 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004984 if (DEBUG_FOCUS) {
4985 ALOGD("Trivial transfer to same window.");
4986 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004987 return true;
4988 }
4989
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004991 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992
Arthur Hungabbb9d82021-09-01 14:52:30 +00004993 // Find the target touch state and touched window by fromToken.
4994 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4995 if (state == nullptr || touchedWindow == nullptr) {
4996 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 return false;
4998 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004999
5000 const int32_t displayId = state->displayId;
5001 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5002 if (toWindowHandle == nullptr) {
5003 ALOGW("Cannot transfer focus because to window not found.");
5004 return false;
5005 }
5006
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005007 if (DEBUG_FOCUS) {
5008 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005009 touchedWindow->windowHandle->getName().c_str(),
5010 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012
Arthur Hungabbb9d82021-09-01 14:52:30 +00005013 // Erase old window.
5014 int32_t oldTargetFlags = touchedWindow->targetFlags;
5015 BitSet32 pointerIds = touchedWindow->pointerIds;
5016 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017
Arthur Hungabbb9d82021-09-01 14:52:30 +00005018 // Add new window.
5019 int32_t newTargetFlags = oldTargetFlags &
5020 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5021 InputTarget::FLAG_DISPATCH_AS_IS);
5022 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023
Arthur Hungabbb9d82021-09-01 14:52:30 +00005024 // Store the dragging window.
5025 if (isDragDrop) {
5026 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 }
5028
Arthur Hungabbb9d82021-09-01 14:52:30 +00005029 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005030 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5031 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005032 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005033 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005034 CancelationOptions
5035 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5036 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005038 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 }
5040
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005041 if (DEBUG_FOCUS) {
5042 logDispatchStateLocked();
5043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 } // release lock
5045
5046 // Wake up poll loop since it may need to make new input dispatching choices.
5047 mLooper->wake();
5048 return true;
5049}
5050
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005051// Binder call
5052bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5053 sp<IBinder> fromToken;
5054 { // acquire lock
5055 std::scoped_lock _l(mLock);
5056
Arthur Hungabbb9d82021-09-01 14:52:30 +00005057 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5058 [](const auto& pair) { return pair.second.windows.size() == 1; });
5059 if (it == mTouchStatesByDisplay.end()) {
5060 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5061 return false;
5062 }
5063 const int32_t displayId = it->first;
5064 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005065 if (toWindowHandle == nullptr) {
5066 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5067 return false;
5068 }
5069
Arthur Hungabbb9d82021-09-01 14:52:30 +00005070 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005071 const TouchedWindow& touchedWindow = state.windows[0];
5072 fromToken = touchedWindow.windowHandle->getToken();
5073 } // release lock
5074
5075 return transferTouchFocus(fromToken, destChannelToken);
5076}
5077
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005079 if (DEBUG_FOCUS) {
5080 ALOGD("Resetting and dropping all events (%s).", reason);
5081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082
5083 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5084 synthesizeCancelationEventsForAllConnectionsLocked(options);
5085
5086 resetKeyRepeatLocked();
5087 releasePendingEventLocked();
5088 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005089 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005092 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005094 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095}
5096
5097void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005098 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 dumpDispatchStateLocked(dump);
5100
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005101 std::istringstream stream(dump);
5102 std::string line;
5103
5104 while (std::getline(stream, line, '\n')) {
5105 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 }
5107}
5108
Prabir Pradhan99987712020-11-10 18:43:05 -08005109std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5110 std::string dump;
5111
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005112 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5113 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005114
5115 std::string windowName = "None";
5116 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005117 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005118 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5119 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5120 : "token has capture without window";
5121 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005122 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005123
5124 return dump;
5125}
5126
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005127void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005128 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5129 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5130 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005131 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132
Tiger Huang721e26f2018-07-24 22:26:19 +08005133 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5134 dump += StringPrintf(INDENT "FocusedApplications:\n");
5135 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5136 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005137 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005138 const std::chrono::duration timeout =
5139 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005140 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005141 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005142 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005145 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005147
Vishnu Nairc519ff72021-01-21 08:23:08 -08005148 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005149 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005151 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005153 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5154 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005155 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156 state.displayId, toString(state.down), toString(state.split),
5157 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005158 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005159 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005160 for (size_t i = 0; i < state.windows.size(); i++) {
5161 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005162 dump += StringPrintf(INDENT4
5163 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5164 i, touchedWindow.windowHandle->getName().c_str(),
5165 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005166 }
5167 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005168 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005172 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174
arthurhung6d4bed92021-03-17 11:59:33 +08005175 if (mDragState) {
5176 dump += StringPrintf(INDENT "DragState:\n");
5177 mDragState->dump(dump, INDENT2);
5178 }
5179
Arthur Hungb92218b2018-08-14 12:00:21 +08005180 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005181 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5182 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5183 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5184 const auto& displayInfo = it->second;
5185 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5186 displayInfo.logicalHeight);
5187 displayInfo.transform.dump(dump, "transform", INDENT4);
5188 } else {
5189 dump += INDENT2 "No DisplayInfo found!\n";
5190 }
5191
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005192 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005193 dump += INDENT2 "Windows:\n";
5194 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005195 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5196 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005198 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005199 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005200 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005201 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005202 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005203 "applicationInfo.name=%s, "
5204 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005205 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005206 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005207 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005208 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005209 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005210 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005211 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005212 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005213 windowInfo->frameLeft, windowInfo->frameTop,
5214 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005215 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005216 windowInfo->applicationInfo.name.c_str(),
5217 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005218 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005219 dump += StringPrintf(", inputFeatures=%s",
5220 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005221 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005222 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005223 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005224 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005225 millis(windowInfo->dispatchingTimeout),
5226 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005227 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005228 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005229 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005230 }
5231 } else {
5232 dump += INDENT2 "Windows: <none>\n";
5233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 }
5235 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005236 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 }
5238
Michael Wright3dd60e22019-03-27 22:06:44 +00005239 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005240 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005241 const std::vector<Monitor>& monitors = it.second;
5242 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5243 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005244 }
5245 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005246 const std::vector<Monitor>& monitors = it.second;
5247 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5248 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005251 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 }
5253
5254 nsecs_t currentTime = now();
5255
5256 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005257 if (!mRecentQueue.empty()) {
5258 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005259 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005260 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005261 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005262 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
5264 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005265 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 }
5267
5268 // Dump event currently being dispatched.
5269 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005270 dump += INDENT "PendingEvent:\n";
5271 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005272 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005273 dump += StringPrintf(", age=%" PRId64 "ms\n",
5274 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005276 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 }
5278
5279 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005280 if (!mInboundQueue.empty()) {
5281 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005282 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005283 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005284 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005285 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 }
5287 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005288 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 }
5290
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005291 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005292 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005293 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5294 const KeyReplacement& replacement = pair.first;
5295 int32_t newKeyCode = pair.second;
5296 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005297 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005298 }
5299 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005300 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005301 }
5302
Prabir Pradhancef936d2021-07-21 16:17:52 +00005303 if (!mCommandQueue.empty()) {
5304 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5305 } else {
5306 dump += INDENT "CommandQueue: <empty>\n";
5307 }
5308
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005309 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005310 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005311 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005312 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005313 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005314 connection->inputChannel->getFd().get(),
5315 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005316 connection->getWindowName().c_str(),
5317 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005318 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005320 if (!connection->outboundQueue.empty()) {
5321 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5322 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005323 dump += dumpQueue(connection->outboundQueue, currentTime);
5324
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005326 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005329 if (!connection->waitQueue.empty()) {
5330 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5331 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005332 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336 }
5337 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005338 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 }
5340
5341 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005342 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5343 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005345 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346 }
5347
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005348 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005349 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5350 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5351 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005352 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005353 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354}
5355
Michael Wright3dd60e22019-03-27 22:06:44 +00005356void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5357 const size_t numMonitors = monitors.size();
5358 for (size_t i = 0; i < numMonitors; i++) {
5359 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005360 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005361 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5362 dump += "\n";
5363 }
5364}
5365
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005366class LooperEventCallback : public LooperCallback {
5367public:
5368 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5369 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5370
5371private:
5372 std::function<int(int events)> mCallback;
5373};
5374
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005375Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005376 if (DEBUG_CHANNEL_CREATION) {
5377 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005380 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005381 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005382 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005383
5384 if (result) {
5385 return base::Error(result) << "Failed to open input channel pair with name " << name;
5386 }
5387
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005389 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005390 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005391 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005392 sp<Connection> connection =
5393 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005395 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5396 ALOGE("Created a new connection, but the token %p is already known", token.get());
5397 }
5398 mConnectionsByToken.emplace(token, connection);
5399
5400 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5401 this, std::placeholders::_1, token);
5402
5403 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 } // release lock
5405
5406 // Wake the looper because some connections have changed.
5407 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005408 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409}
5410
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005411Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5412 bool isGestureMonitor,
5413 const std::string& name,
5414 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005415 std::shared_ptr<InputChannel> serverChannel;
5416 std::unique_ptr<InputChannel> clientChannel;
5417 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5418 if (result) {
5419 return base::Error(result) << "Failed to open input channel pair with name " << name;
5420 }
5421
Michael Wright3dd60e22019-03-27 22:06:44 +00005422 { // acquire lock
5423 std::scoped_lock _l(mLock);
5424
5425 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005426 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5427 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005428 }
5429
Garfield Tan15601662020-09-22 15:32:38 -07005430 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005431 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005432 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005433
5434 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5435 ALOGE("Created a new connection, but the token %p is already known", token.get());
5436 }
5437 mConnectionsByToken.emplace(token, connection);
5438 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5439 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005440
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005441 auto& monitorsByDisplay =
5442 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005443 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005444
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005445 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005446 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5447 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005448 }
Garfield Tan15601662020-09-22 15:32:38 -07005449
Michael Wright3dd60e22019-03-27 22:06:44 +00005450 // Wake the looper because some connections have changed.
5451 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005452 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005453}
5454
Garfield Tan15601662020-09-22 15:32:38 -07005455status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005457 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
Garfield Tan15601662020-09-22 15:32:38 -07005459 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 if (status) {
5461 return status;
5462 }
5463 } // release lock
5464
5465 // Wake the poll loop because removing the connection may have changed the current
5466 // synchronization state.
5467 mLooper->wake();
5468 return OK;
5469}
5470
Garfield Tan15601662020-09-22 15:32:38 -07005471status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5472 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005473 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005474 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005475 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 return BAD_VALUE;
5477 }
5478
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005479 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005480
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005482 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 }
5484
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005485 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486
5487 nsecs_t currentTime = now();
5488 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5489
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005490 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 return OK;
5492}
5493
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005494void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5495 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5496 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005497}
5498
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005499void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005500 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005501 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005502 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005503 std::vector<Monitor>& monitors = it->second;
5504 const size_t numMonitors = monitors.size();
5505 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005506 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005507 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5508 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005509 monitors.erase(monitors.begin() + i);
5510 break;
5511 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005512 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005513 if (monitors.empty()) {
5514 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005515 } else {
5516 ++it;
5517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 }
5519}
5520
Michael Wright3dd60e22019-03-27 22:06:44 +00005521status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5522 { // acquire lock
5523 std::scoped_lock _l(mLock);
5524 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5525
5526 if (!foundDisplayId) {
5527 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5528 return BAD_VALUE;
5529 }
5530 int32_t displayId = foundDisplayId.value();
5531
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005532 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5533 mTouchStatesByDisplay.find(displayId);
5534 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005535 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5536 return BAD_VALUE;
5537 }
5538
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005539 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005540 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005541 std::optional<int32_t> foundDeviceId;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07005542 for (const auto& monitor : state.gestureMonitors) {
5543 if (monitor.inputChannel->getConnectionToken() == token) {
5544 requestingChannel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005545 foundDeviceId = state.deviceId;
5546 }
5547 }
5548 if (!foundDeviceId || !state.down) {
5549 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005550 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005551 return BAD_VALUE;
5552 }
5553 int32_t deviceId = foundDeviceId.value();
5554
5555 // Send cancel events to all the input channels we're stealing from.
5556 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005557 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005558 options.deviceId = deviceId;
5559 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005560 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005561 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005562 std::shared_ptr<InputChannel> channel =
5563 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005564 if (channel != nullptr) {
5565 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005566 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005567 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005568 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005569 canceledWindows += "]";
5570 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5571 canceledWindows.c_str());
5572
Michael Wright3dd60e22019-03-27 22:06:44 +00005573 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hungfbfa5722021-11-16 02:45:54 +00005574 state.split = false;
Michael Wright3dd60e22019-03-27 22:06:44 +00005575 state.filterNonMonitors();
5576 }
5577 return OK;
5578}
5579
Prabir Pradhan99987712020-11-10 18:43:05 -08005580void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5581 { // acquire lock
5582 std::scoped_lock _l(mLock);
5583 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005584 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005585 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5586 windowHandle != nullptr ? windowHandle->getName().c_str()
5587 : "token without window");
5588 }
5589
Vishnu Nairc519ff72021-01-21 08:23:08 -08005590 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005591 if (focusedToken != windowToken) {
5592 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5593 enabled ? "enable" : "disable");
5594 return;
5595 }
5596
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005597 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005598 ALOGW("Ignoring request to %s Pointer Capture: "
5599 "window has %s requested pointer capture.",
5600 enabled ? "enable" : "disable", enabled ? "already" : "not");
5601 return;
5602 }
5603
Prabir Pradhan99987712020-11-10 18:43:05 -08005604 setPointerCaptureLocked(enabled);
5605 } // release lock
5606
5607 // Wake the thread to process command entries.
5608 mLooper->wake();
5609}
5610
Michael Wright3dd60e22019-03-27 22:06:44 +00005611std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5612 const sp<IBinder>& token) {
5613 for (const auto& it : mGestureMonitorsByDisplay) {
5614 const std::vector<Monitor>& monitors = it.second;
5615 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005616 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005617 return it.first;
5618 }
5619 }
5620 }
5621 return std::nullopt;
5622}
5623
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005624std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5625 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5626 if (gesturePid.has_value()) {
5627 return gesturePid;
5628 }
5629 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5630}
5631
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005632sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005633 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005634 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005635 }
5636
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005637 for (const auto& [token, connection] : mConnectionsByToken) {
5638 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005639 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641 }
Robert Carr4e670e52018-08-15 13:26:12 -07005642
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005643 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644}
5645
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005646std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5647 sp<Connection> connection = getConnectionLocked(connectionToken);
5648 if (connection == nullptr) {
5649 return "<nullptr>";
5650 }
5651 return connection->getInputChannelName();
5652}
5653
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005654void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005655 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005656 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005657}
5658
Prabir Pradhancef936d2021-07-21 16:17:52 +00005659void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5660 const sp<Connection>& connection, uint32_t seq,
5661 bool handled, nsecs_t consumeTime) {
5662 // Handle post-event policy actions.
5663 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5664 if (dispatchEntryIt == connection->waitQueue.end()) {
5665 return;
5666 }
5667 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5668 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5669 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5670 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5671 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5672 }
5673 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5674 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5675 connection->inputChannel->getConnectionToken(),
5676 dispatchEntry->deliveryTime, consumeTime, finishTime);
5677 }
5678
5679 bool restartEvent;
5680 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5681 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5682 restartEvent =
5683 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5684 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5685 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5686 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5687 handled);
5688 } else {
5689 restartEvent = false;
5690 }
5691
5692 // Dequeue the event and start the next cycle.
5693 // Because the lock might have been released, it is possible that the
5694 // contents of the wait queue to have been drained, so we need to double-check
5695 // a few things.
5696 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5697 if (dispatchEntryIt != connection->waitQueue.end()) {
5698 dispatchEntry = *dispatchEntryIt;
5699 connection->waitQueue.erase(dispatchEntryIt);
5700 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5701 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5702 if (!connection->responsive) {
5703 connection->responsive = isConnectionResponsive(*connection);
5704 if (connection->responsive) {
5705 // The connection was unresponsive, and now it's responsive.
5706 processConnectionResponsiveLocked(*connection);
5707 }
5708 }
5709 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005710 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005711 connection->outboundQueue.push_front(dispatchEntry);
5712 traceOutboundQueueLength(*connection);
5713 } else {
5714 releaseDispatchEntry(dispatchEntry);
5715 }
5716 }
5717
5718 // Start the next dispatch cycle for this connection.
5719 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720}
5721
Prabir Pradhancef936d2021-07-21 16:17:52 +00005722void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5723 const sp<IBinder>& newToken) {
5724 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5725 scoped_unlock unlock(mLock);
5726 mPolicy->notifyFocusChanged(oldToken, newToken);
5727 };
5728 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729}
5730
Prabir Pradhancef936d2021-07-21 16:17:52 +00005731void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5732 auto command = [this, token, x, y]() REQUIRES(mLock) {
5733 scoped_unlock unlock(mLock);
5734 mPolicy->notifyDropWindow(token, x, y);
5735 };
5736 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005737}
5738
Prabir Pradhancef936d2021-07-21 16:17:52 +00005739void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5740 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5741 scoped_unlock unlock(mLock);
5742 mPolicy->notifyUntrustedTouch(obscuringPackage);
5743 };
5744 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005745}
5746
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005747void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5748 if (connection == nullptr) {
5749 LOG_ALWAYS_FATAL("Caller must check for nullness");
5750 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005751 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5752 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005753 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005754 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005755 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005756 return;
5757 }
5758 /**
5759 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5760 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5761 * has changed. This could cause newer entries to time out before the already dispatched
5762 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5763 * processes the events linearly. So providing information about the oldest entry seems to be
5764 * most useful.
5765 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005766 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005767 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5768 std::string reason =
5769 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005770 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005771 ns2ms(currentWait),
5772 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005773 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005774 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005775
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005776 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5777
5778 // Stop waking up for events on this connection, it is already unresponsive
5779 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005780}
5781
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005782void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5783 std::string reason =
5784 StringPrintf("%s does not have a focused window", application->getName().c_str());
5785 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005786
Prabir Pradhancef936d2021-07-21 16:17:52 +00005787 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5788 scoped_unlock unlock(mLock);
5789 mPolicy->notifyNoFocusedWindowAnr(application);
5790 };
5791 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005792}
5793
chaviw98318de2021-05-19 16:45:23 -05005794void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005795 const std::string& reason) {
5796 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5797 updateLastAnrStateLocked(windowLabel, reason);
5798}
5799
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005800void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5801 const std::string& reason) {
5802 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803 updateLastAnrStateLocked(windowLabel, reason);
5804}
5805
5806void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5807 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005809 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 struct tm tm;
5811 localtime_r(&t, &tm);
5812 char timestr[64];
5813 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005814 mLastAnrState.clear();
5815 mLastAnrState += INDENT "ANR:\n";
5816 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005817 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5818 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005819 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820}
5821
Prabir Pradhancef936d2021-07-21 16:17:52 +00005822void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5823 KeyEntry& entry) {
5824 const KeyEvent event = createKeyEvent(entry);
5825 nsecs_t delay = 0;
5826 { // release lock
5827 scoped_unlock unlock(mLock);
5828 android::base::Timer t;
5829 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5830 entry.policyFlags);
5831 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5832 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5833 std::to_string(t.duration().count()).c_str());
5834 }
5835 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
5837 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005838 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005840 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005842 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5843 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845}
5846
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005847void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005848 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5849 scoped_unlock unlock(mLock);
5850 mPolicy->notifyMonitorUnresponsive(pid, reason);
5851 };
5852 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005853}
5854
Prabir Pradhancef936d2021-07-21 16:17:52 +00005855void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005856 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005857 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5858 scoped_unlock unlock(mLock);
5859 mPolicy->notifyWindowUnresponsive(token, reason);
5860 };
5861 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005862}
5863
5864void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005865 auto command = [this, pid]() REQUIRES(mLock) {
5866 scoped_unlock unlock(mLock);
5867 mPolicy->notifyMonitorResponsive(pid);
5868 };
5869 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005870}
5871
Prabir Pradhancef936d2021-07-21 16:17:52 +00005872void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5873 auto command = [this, connectionToken]() REQUIRES(mLock) {
5874 scoped_unlock unlock(mLock);
5875 mPolicy->notifyWindowResponsive(connectionToken);
5876 };
5877 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005878}
5879
5880/**
5881 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5882 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5883 * command entry to the command queue.
5884 */
5885void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5886 std::string reason) {
5887 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5888 if (connection.monitor) {
5889 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5890 reason.c_str());
5891 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5892 if (!pid.has_value()) {
5893 ALOGE("Could not find unresponsive monitor for connection %s",
5894 connection.inputChannel->getName().c_str());
5895 return;
5896 }
5897 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5898 return;
5899 }
5900 // If not a monitor, must be a window
5901 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5902 reason.c_str());
5903 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5904}
5905
5906/**
5907 * Tell the policy that a connection has become responsive so that it can stop ANR.
5908 */
5909void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5910 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5911 if (connection.monitor) {
5912 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5913 if (!pid.has_value()) {
5914 ALOGE("Could not find responsive monitor for connection %s",
5915 connection.inputChannel->getName().c_str());
5916 return;
5917 }
5918 sendMonitorResponsiveCommandLocked(pid.value());
5919 return;
5920 }
5921 // If not a monitor, must be a window
5922 sendWindowResponsiveCommandLocked(connectionToken);
5923}
5924
Prabir Pradhancef936d2021-07-21 16:17:52 +00005925bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005926 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005927 KeyEntry& keyEntry, bool handled) {
5928 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005929 if (!handled) {
5930 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005931 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005932 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005933 return false;
5934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005936 // Get the fallback key state.
5937 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005938 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005939 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005940 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005941 connection->inputState.removeFallbackKey(originalKeyCode);
5942 }
5943
5944 if (handled || !dispatchEntry->hasForegroundTarget()) {
5945 // If the application handles the original key for which we previously
5946 // generated a fallback or if the window is not a foreground window,
5947 // then cancel the associated fallback key, if any.
5948 if (fallbackKeyCode != -1) {
5949 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005950 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5951 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5952 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5953 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5954 keyEntry.policyFlags);
5955 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005956 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005957 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958
5959 mLock.unlock();
5960
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005961 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005962 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963
5964 mLock.lock();
5965
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005966 // Cancel the fallback key.
5967 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005969 "application handled the original non-fallback key "
5970 "or is no longer a foreground target, "
5971 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 options.keyCode = fallbackKeyCode;
5973 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005975 connection->inputState.removeFallbackKey(originalKeyCode);
5976 }
5977 } else {
5978 // If the application did not handle a non-fallback key, first check
5979 // that we are in a good state to perform unhandled key event processing
5980 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005981 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005982 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005983 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5984 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5985 "since this is not an initial down. "
5986 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5987 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5988 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005989 return false;
5990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005991
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005992 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005993 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5994 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5995 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5996 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5997 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005998 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005999
6000 mLock.unlock();
6001
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006002 bool fallback =
6003 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006004 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006005
6006 mLock.lock();
6007
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006008 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006009 connection->inputState.removeFallbackKey(originalKeyCode);
6010 return false;
6011 }
6012
6013 // Latch the fallback keycode for this key on an initial down.
6014 // The fallback keycode cannot change at any other point in the lifecycle.
6015 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006017 fallbackKeyCode = event.getKeyCode();
6018 } else {
6019 fallbackKeyCode = AKEYCODE_UNKNOWN;
6020 }
6021 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6022 }
6023
6024 ALOG_ASSERT(fallbackKeyCode != -1);
6025
6026 // Cancel the fallback key if the policy decides not to send it anymore.
6027 // We will continue to dispatch the key to the policy but we will no
6028 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006029 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6030 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006031 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6032 if (fallback) {
6033 ALOGD("Unhandled key event: Policy requested to send key %d"
6034 "as a fallback for %d, but on the DOWN it had requested "
6035 "to send %d instead. Fallback canceled.",
6036 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6037 } else {
6038 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6039 "but on the DOWN it had requested to send %d. "
6040 "Fallback canceled.",
6041 originalKeyCode, fallbackKeyCode);
6042 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044
6045 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6046 "canceling fallback, policy no longer desires it");
6047 options.keyCode = fallbackKeyCode;
6048 synthesizeCancelationEventsForConnectionLocked(connection, options);
6049
6050 fallback = false;
6051 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006053 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 }
6055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006056
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006057 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6058 {
6059 std::string msg;
6060 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6061 connection->inputState.getFallbackKeys();
6062 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6063 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6064 }
6065 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6066 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006067 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006068 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069
6070 if (fallback) {
6071 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006072 keyEntry.eventTime = event.getEventTime();
6073 keyEntry.deviceId = event.getDeviceId();
6074 keyEntry.source = event.getSource();
6075 keyEntry.displayId = event.getDisplayId();
6076 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6077 keyEntry.keyCode = fallbackKeyCode;
6078 keyEntry.scanCode = event.getScanCode();
6079 keyEntry.metaState = event.getMetaState();
6080 keyEntry.repeatCount = event.getRepeatCount();
6081 keyEntry.downTime = event.getDownTime();
6082 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006084 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6085 ALOGD("Unhandled key event: Dispatching fallback key. "
6086 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6087 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6088 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006089 return true; // restart the event
6090 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006091 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6092 ALOGD("Unhandled key event: No fallback key.");
6093 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006094
6095 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006096 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 }
6098 }
6099 return false;
6100}
6101
Prabir Pradhancef936d2021-07-21 16:17:52 +00006102bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006103 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006104 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 return false;
6106}
6107
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108void InputDispatcher::traceInboundQueueLengthLocked() {
6109 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006110 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
6112}
6113
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006114void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115 if (ATRACE_ENABLED()) {
6116 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006117 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6118 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 }
6120}
6121
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006122void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 if (ATRACE_ENABLED()) {
6124 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006125 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6126 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006127 }
6128}
6129
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006130void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006131 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006132
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006133 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006134 dumpDispatchStateLocked(dump);
6135
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006136 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006137 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006138 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006139 }
6140}
6141
6142void InputDispatcher::monitor() {
6143 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006144 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006146 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006147}
6148
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006149/**
6150 * Wake up the dispatcher and wait until it processes all events and commands.
6151 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6152 * this method can be safely called from any thread, as long as you've ensured that
6153 * the work you are interested in completing has already been queued.
6154 */
6155bool InputDispatcher::waitForIdle() {
6156 /**
6157 * Timeout should represent the longest possible time that a device might spend processing
6158 * events and commands.
6159 */
6160 constexpr std::chrono::duration TIMEOUT = 100ms;
6161 std::unique_lock lock(mLock);
6162 mLooper->wake();
6163 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6164 return result == std::cv_status::no_timeout;
6165}
6166
Vishnu Naire798b472020-07-23 13:52:21 -07006167/**
6168 * Sets focus to the window identified by the token. This must be called
6169 * after updating any input window handles.
6170 *
6171 * Params:
6172 * request.token - input channel token used to identify the window that should gain focus.
6173 * request.focusedToken - the token that the caller expects currently to be focused. If the
6174 * specified token does not match the currently focused window, this request will be dropped.
6175 * If the specified focused token matches the currently focused window, the call will succeed.
6176 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6177 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6178 * when requesting the focus change. This determines which request gets
6179 * precedence if there is a focus change request from another source such as pointer down.
6180 */
Vishnu Nair958da932020-08-21 17:12:37 -07006181void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6182 { // acquire lock
6183 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006184 std::optional<FocusResolver::FocusChanges> changes =
6185 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6186 if (changes) {
6187 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006188 }
6189 } // release lock
6190 // Wake up poll loop since it may need to make new input dispatching choices.
6191 mLooper->wake();
6192}
6193
Vishnu Nairc519ff72021-01-21 08:23:08 -08006194void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6195 if (changes.oldFocus) {
6196 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006197 if (focusedInputChannel) {
6198 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6199 "focus left window");
6200 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006201 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006202 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006203 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006204 if (changes.newFocus) {
6205 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006206 }
6207
Prabir Pradhan99987712020-11-10 18:43:05 -08006208 // If a window has pointer capture, then it must have focus. We need to ensure that this
6209 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6210 // If the window loses focus before it loses pointer capture, then the window can be in a state
6211 // where it has pointer capture but not focus, violating the contract. Therefore we must
6212 // dispatch the pointer capture event before the focus event. Since focus events are added to
6213 // the front of the queue (above), we add the pointer capture event to the front of the queue
6214 // after the focus events are added. This ensures the pointer capture event ends up at the
6215 // front.
6216 disablePointerCaptureForcedLocked();
6217
Vishnu Nairc519ff72021-01-21 08:23:08 -08006218 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006219 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006220 }
6221}
Vishnu Nair958da932020-08-21 17:12:37 -07006222
Prabir Pradhan99987712020-11-10 18:43:05 -08006223void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006224 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006225 return;
6226 }
6227
6228 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6229
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006230 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006231 setPointerCaptureLocked(false);
6232 }
6233
6234 if (!mWindowTokenWithPointerCapture) {
6235 // No need to send capture changes because no window has capture.
6236 return;
6237 }
6238
6239 if (mPendingEvent != nullptr) {
6240 // Move the pending event to the front of the queue. This will give the chance
6241 // for the pending event to be dropped if it is a captured event.
6242 mInboundQueue.push_front(mPendingEvent);
6243 mPendingEvent = nullptr;
6244 }
6245
6246 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006247 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006248 mInboundQueue.push_front(std::move(entry));
6249}
6250
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006251void InputDispatcher::setPointerCaptureLocked(bool enable) {
6252 mCurrentPointerCaptureRequest.enable = enable;
6253 mCurrentPointerCaptureRequest.seq++;
6254 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006255 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006256 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006257 };
6258 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006259}
6260
Vishnu Nair599f1412021-06-21 10:39:58 -07006261void InputDispatcher::displayRemoved(int32_t displayId) {
6262 { // acquire lock
6263 std::scoped_lock _l(mLock);
6264 // Set an empty list to remove all handles from the specific display.
6265 setInputWindowsLocked(/* window handles */ {}, displayId);
6266 setFocusedApplicationLocked(displayId, nullptr);
6267 // Call focus resolver to clean up stale requests. This must be called after input windows
6268 // have been removed for the removed display.
6269 mFocusResolver.displayRemoved(displayId);
6270 } // release lock
6271
6272 // Wake up poll loop since it may need to make new input dispatching choices.
6273 mLooper->wake();
6274}
6275
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006276void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6277 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006278 // The listener sends the windows as a flattened array. Separate the windows by display for
6279 // more convenient parsing.
6280 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006281 for (const auto& info : windowInfos) {
6282 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6283 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6284 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006285
6286 { // acquire lock
6287 std::scoped_lock _l(mLock);
6288 mDisplayInfos.clear();
6289 for (const auto& displayInfo : displayInfos) {
6290 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6291 }
6292
6293 for (const auto& [displayId, handles] : handlesPerDisplay) {
6294 setInputWindowsLocked(handles, displayId);
6295 }
6296 }
6297 // Wake up poll loop since it may need to make new input dispatching choices.
6298 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006299}
6300
Vishnu Nair062a8672021-09-03 16:07:44 -07006301bool InputDispatcher::shouldDropInput(
6302 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6303 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6304 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6305 isWindowObscuredLocked(windowHandle))) {
6306 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6307 "%" PRId32 ".",
6308 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6309 windowHandle->getInfo()->inputFeatures.string().c_str(),
6310 windowHandle->getInfo()->displayId);
6311 return true;
6312 }
6313 return false;
6314}
6315
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006316void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6317 const std::vector<gui::WindowInfo>& windowInfos,
6318 const std::vector<DisplayInfo>& displayInfos) {
6319 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6320}
6321
Garfield Tane84e6f92019-08-29 17:28:41 -07006322} // namespace android::inputdispatcher