blob: 69d9048bb96cdee7c0a1ace106ab2e45682b75a4 [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 Pradhan61a5d242021-07-26 16:41:09 +0000532} // namespace
533
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534// --- InputDispatcher ---
535
Garfield Tan00f511d2019-06-12 16:55:40 -0700536InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
537 : mPolicy(policy),
538 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700539 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800540 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700541 mAppSwitchSawKeyDown(false),
542 mAppSwitchDueTime(LONG_LONG_MAX),
543 mNextUnblockedEvent(nullptr),
544 mDispatchEnabled(false),
545 mDispatchFrozen(false),
546 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800547 // mInTouchMode will be initialized by the WindowManager to the default device config.
548 // To avoid leaking stack in case that call never comes, and for tests,
549 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000550 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100551 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000552 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800553 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000554 mLatencyAggregator(),
555 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000556 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800558 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700560 mWindowInfoListener = new DispatcherWindowListener(*this);
561 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
562
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564
565 policy->getDispatcherConfiguration(&mConfig);
566}
567
568InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000569 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
Prabir Pradhancef936d2021-07-21 16:17:52 +0000571 resetKeyRepeatLocked();
572 releasePendingEventLocked();
573 drainInboundQueueLocked();
574 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000576 while (!mConnectionsByToken.empty()) {
577 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000578 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
579 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 }
581}
582
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700583status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700584 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700585 return ALREADY_EXISTS;
586 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700587 mThread = std::make_unique<InputThread>(
588 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
589 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700590}
591
592status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700593 if (mThread && mThread->isCallingThread()) {
594 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595 return INVALID_OPERATION;
596 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 mThread.reset();
598 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700599}
600
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601void InputDispatcher::dispatchOnce() {
602 nsecs_t nextWakeupTime = LONG_LONG_MAX;
603 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800604 std::scoped_lock _l(mLock);
605 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606
607 // Run a dispatch loop if there are no pending commands.
608 // The dispatch loop might enqueue commands to run afterwards.
609 if (!haveCommandsLocked()) {
610 dispatchOnceInnerLocked(&nextWakeupTime);
611 }
612
613 // Run all pending commands if there are any.
614 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000615 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 nextWakeupTime = LONG_LONG_MIN;
617 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800618
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700619 // If we are still waiting for ack on some events,
620 // we might have to wake up earlier to check if an app is anr'ing.
621 const nsecs_t nextAnrCheck = processAnrsLocked();
622 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
623
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800624 // We are about to enter an infinitely long sleep, because we have no commands or
625 // pending or queued events
626 if (nextWakeupTime == LONG_LONG_MAX) {
627 mDispatcherEnteredIdle.notify_all();
628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 } // release lock
630
631 // Wait for callback or timeout or wake. (make sure we round up, not down)
632 nsecs_t currentTime = now();
633 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
634 mLooper->pollOnce(timeoutMillis);
635}
636
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700637/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500638 * Raise ANR if there is no focused window.
639 * Before the ANR is raised, do a final state check:
640 * 1. The currently focused application must be the same one we are waiting for.
641 * 2. Ensure we still don't have a focused window.
642 */
643void InputDispatcher::processNoFocusedWindowAnrLocked() {
644 // Check if the application that we are waiting for is still focused.
645 std::shared_ptr<InputApplicationHandle> focusedApplication =
646 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
647 if (focusedApplication == nullptr ||
648 focusedApplication->getApplicationToken() !=
649 mAwaitedFocusedApplication->getApplicationToken()) {
650 // Unexpected because we should have reset the ANR timer when focused application changed
651 ALOGE("Waited for a focused window, but focused application has already changed to %s",
652 focusedApplication->getName().c_str());
653 return; // The focused application has changed.
654 }
655
chaviw98318de2021-05-19 16:45:23 -0500656 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500657 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
658 if (focusedWindowHandle != nullptr) {
659 return; // We now have a focused window. No need for ANR.
660 }
661 onAnrLocked(mAwaitedFocusedApplication);
662}
663
664/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700665 * Check if any of the connections' wait queues have events that are too old.
666 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
667 * Return the time at which we should wake up next.
668 */
669nsecs_t InputDispatcher::processAnrsLocked() {
670 const nsecs_t currentTime = now();
671 nsecs_t nextAnrCheck = LONG_LONG_MAX;
672 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
673 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
674 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500675 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700676 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500677 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 return LONG_LONG_MIN;
679 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500680 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700681 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
682 }
683 }
684
685 // Check if any connection ANRs are due
686 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
687 if (currentTime < nextAnrCheck) { // most likely scenario
688 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
689 }
690
691 // If we reached here, we have an unresponsive connection.
692 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
693 if (connection == nullptr) {
694 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
695 return nextAnrCheck;
696 }
697 connection->responsive = false;
698 // Stop waking up for this unresponsive connection
699 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000700 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700701 return LONG_LONG_MIN;
702}
703
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500704std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500705 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500707 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500709 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700710}
711
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
713 nsecs_t currentTime = now();
714
Jeff Browndc5992e2014-04-11 01:27:26 -0700715 // Reset the key repeat timer whenever normal dispatch is suspended while the
716 // device is in a non-interactive state. This is to ensure that we abort a key
717 // repeat if the device is just coming out of sleep.
718 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 resetKeyRepeatLocked();
720 }
721
722 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
723 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100724 if (DEBUG_FOCUS) {
725 ALOGD("Dispatch frozen. Waiting some more.");
726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 return;
728 }
729
730 // Optimize latency of app switches.
731 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
732 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
733 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
734 if (mAppSwitchDueTime < *nextWakeupTime) {
735 *nextWakeupTime = mAppSwitchDueTime;
736 }
737
738 // Ready to start a new event.
739 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700741 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 if (isAppSwitchDue) {
743 // The inbound queue is empty so the app switch key we were waiting
744 // for will never arrive. Stop waiting for it.
745 resetPendingAppSwitchLocked(false);
746 isAppSwitchDue = false;
747 }
748
749 // Synthesize a key repeat if appropriate.
750 if (mKeyRepeatState.lastKeyEntry) {
751 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
752 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
753 } else {
754 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
755 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
756 }
757 }
758 }
759
760 // Nothing to do if there is no pending event.
761 if (!mPendingEvent) {
762 return;
763 }
764 } else {
765 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700766 mPendingEvent = mInboundQueue.front();
767 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 traceInboundQueueLengthLocked();
769 }
770
771 // Poke user activity for this event.
772 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700773 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 }
776
777 // Now we have an event to dispatch.
778 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700779 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700785 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787
788 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700789 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 }
791
792 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700793 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700794 const ConfigurationChangedEntry& typedEntry =
795 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700797 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 break;
799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700801 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700802 const DeviceResetEntry& typedEntry =
803 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700805 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 break;
807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100809 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700810 std::shared_ptr<FocusEntry> typedEntry =
811 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100812 dispatchFocusLocked(currentTime, typedEntry);
813 done = true;
814 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
815 break;
816 }
817
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700818 case EventEntry::Type::TOUCH_MODE_CHANGED: {
819 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
820 dispatchTouchModeChangeLocked(currentTime, typedEntry);
821 done = true;
822 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
823 break;
824 }
825
Prabir Pradhan99987712020-11-10 18:43:05 -0800826 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
827 const auto typedEntry =
828 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
829 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
830 done = true;
831 break;
832 }
833
arthurhungb89ccb02020-12-30 16:19:01 +0800834 case EventEntry::Type::DRAG: {
835 std::shared_ptr<DragEntry> typedEntry =
836 std::static_pointer_cast<DragEntry>(mPendingEvent);
837 dispatchDragLocked(currentTime, typedEntry);
838 done = true;
839 break;
840 }
841
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700842 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700843 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700845 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 resetPendingAppSwitchLocked(true);
847 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700848 } else if (dropReason == DropReason::NOT_DROPPED) {
849 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 }
851 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700852 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700853 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700855 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
856 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 break;
860 }
861
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700862 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 std::shared_ptr<MotionEntry> motionEntry =
864 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
866 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700868 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700869 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
872 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 }
Chris Yef59a2f42020-10-16 12:55:26 -0700877
878 case EventEntry::Type::SENSOR: {
879 std::shared_ptr<SensorEntry> sensorEntry =
880 std::static_pointer_cast<SensorEntry>(mPendingEvent);
881 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
882 dropReason = DropReason::APP_SWITCH;
883 }
884 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
885 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
886 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
887 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
888 dropReason = DropReason::STALE;
889 }
890 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
891 done = true;
892 break;
893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
895
896 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700898 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
Michael Wright3a981722015-06-10 15:26:13 +0100900 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
902 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905}
906
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700907/**
908 * Return true if the events preceding this incoming motion event should be dropped
909 * Return false otherwise (the default behaviour)
910 */
911bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700912 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700913 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914
915 // Optimize case where the current application is unresponsive and the user
916 // decides to touch a window in a different application.
917 // If the application takes too long to catch up then we drop all events preceding
918 // the touch into the other window.
919 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700920 int32_t displayId = motionEntry.displayId;
921 int32_t x = static_cast<int32_t>(
922 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
923 int32_t y = static_cast<int32_t>(
924 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500925 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926 findTouchedWindowAtLocked(displayId, x, y, nullptr);
927 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700928 touchedWindowHandle->getApplicationToken() !=
929 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931 ALOGI("Pruning input queue because user touched a different application while waiting "
932 "for %s",
933 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700934 return true;
935 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936
937 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700938 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700940 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000941 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 // This monitor could take more input. Drop all events preceding this
943 // event, so that gesture monitor could get a chance to receive the stream
944 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
945 "responsive gesture monitor that may handle the event",
946 mAwaitedFocusedApplication->getName().c_str());
947 return true;
948 }
949 }
950 }
951
952 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
953 // yet been processed by some connections, the dispatcher will wait for these motion
954 // events to be processed before dispatching the key event. This is because these motion events
955 // may cause a new window to be launched, which the user might expect to receive focus.
956 // To prevent waiting forever for such events, just send the key to the currently focused window
957 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
958 ALOGD("Received a new pointer down event, stop waiting for events to process and "
959 "just send the pending key event to the focused window.");
960 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 }
962 return false;
963}
964
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700966 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 mInboundQueue.push_back(std::move(newEntry));
968 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 traceInboundQueueLengthLocked();
970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700971 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700972 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 // Optimize app switch latency.
974 // If the application takes too long to catch up then we drop all events preceding
975 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700978 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700980 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000982 if (DEBUG_APP_SWITCH) {
983 ALOGD("App switch is pending!");
984 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700985 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 mAppSwitchSawKeyDown = false;
987 needWake = true;
988 }
989 }
990 }
991 break;
992 }
993
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700994 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700995 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
996 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700997 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001002 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1003 break;
1004 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001005 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001006 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001007 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001008 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001009 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1010 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001011 // nothing to do
1012 break;
1013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 return needWake;
1017}
1018
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001019void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001020 // Do not store sensor event in recent queue to avoid flooding the queue.
1021 if (entry->type != EventEntry::Type::SENSOR) {
1022 mRecentQueue.push_back(entry);
1023 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001024 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001025 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027}
1028
chaviw98318de2021-05-19 16:45:23 -05001029sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1030 int32_t y, TouchState* touchState,
1031 bool addOutsideTargets,
1032 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001033 if (addOutsideTargets && touchState == nullptr) {
1034 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001037 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1038 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001039 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001040 continue;
1041 }
chaviw98318de2021-05-19 16:45:23 -05001042 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001044 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045
1046 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001047 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1048 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1049 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1051 // Found window.
1052 return windowHandle;
1053 }
1054 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001055
chaviw98318de2021-05-19 16:45:23 -05001056 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001057 touchState->addOrUpdateWindow(windowHandle,
1058 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1059 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001064 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065}
1066
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001067void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 const char* reason;
1069 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001070 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001071 if (DEBUG_INBOUND_EVENT_DETAILS) {
1072 ALOGD("Dropped event because policy consumed it.");
1073 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 reason = "inbound event was dropped because the policy consumed it";
1075 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 case DropReason::DISABLED:
1077 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 ALOGI("Dropped event because input dispatch is disabled.");
1079 }
1080 reason = "inbound event was dropped because input dispatch is disabled";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 ALOGI("Dropped event because of pending overdue app switch.");
1084 reason = "inbound event was dropped because of pending overdue app switch";
1085 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 ALOGI("Dropped event because the current application is not responding and the user "
1088 "has started interacting with a different application.");
1089 reason = "inbound event was dropped because the current application is not responding "
1090 "and the user has started interacting with a different application";
1091 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001092 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 ALOGI("Dropped event because it is stale.");
1094 reason = "inbound event was dropped because it is stale";
1095 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001096 case DropReason::NO_POINTER_CAPTURE:
1097 ALOGI("Dropped event because there is no window with Pointer Capture.");
1098 reason = "inbound event was dropped because there is no window with Pointer Capture";
1099 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001100 case DropReason::NOT_DROPPED: {
1101 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
1105
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001106 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001107 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1109 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001112 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001113 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1114 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1116 synthesizeCancelationEventsForAllConnectionsLocked(options);
1117 } else {
1118 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1119 synthesizeCancelationEventsForAllConnectionsLocked(options);
1120 }
1121 break;
1122 }
Chris Yef59a2f42020-10-16 12:55:26 -07001123 case EventEntry::Type::SENSOR: {
1124 break;
1125 }
arthurhungb89ccb02020-12-30 16:19:01 +08001126 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1127 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001128 break;
1129 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001130 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001131 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::CONFIGURATION_CHANGED:
1133 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001134 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001135 break;
1136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138}
1139
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001140static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1142 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143}
1144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001145bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1146 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1147 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1148 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149}
1150
1151bool InputDispatcher::isAppSwitchPendingLocked() {
1152 return mAppSwitchDueTime != LONG_LONG_MAX;
1153}
1154
1155void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1156 mAppSwitchDueTime = LONG_LONG_MAX;
1157
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001158 if (DEBUG_APP_SWITCH) {
1159 if (handled) {
1160 ALOGD("App switch has arrived.");
1161 } else {
1162 ALOGD("App switch was abandoned.");
1163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165}
1166
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001168 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169}
1170
Prabir Pradhancef936d2021-07-21 16:17:52 +00001171bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001172 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 return false;
1174 }
1175
1176 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001177 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001178 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001179 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1180 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001181 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 return true;
1183}
1184
Prabir Pradhancef936d2021-07-21 16:17:52 +00001185void InputDispatcher::postCommandLocked(Command&& command) {
1186 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187}
1188
1189void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001190 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001192 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 releaseInboundEventLocked(entry);
1194 }
1195 traceInboundQueueLengthLocked();
1196}
1197
1198void InputDispatcher::releasePendingEventLocked() {
1199 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001201 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 }
1203}
1204
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001205void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001207 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001208 if (DEBUG_DISPATCH_CYCLE) {
1209 ALOGD("Injected inbound event was dropped.");
1210 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001211 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001214 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 }
1216 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217}
1218
1219void InputDispatcher::resetKeyRepeatLocked() {
1220 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001221 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223}
1224
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1226 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227
Michael Wright2e732952014-09-24 13:26:59 -07001228 uint32_t policyFlags = entry->policyFlags &
1229 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231 std::shared_ptr<KeyEntry> newEntry =
1232 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1233 entry->source, entry->displayId, policyFlags, entry->action,
1234 entry->flags, entry->keyCode, entry->scanCode,
1235 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 newEntry->syntheticRepeat = true;
1238 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001240 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241}
1242
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001245 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1246 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
1249 // Reset key repeating in case a keyboard device was added or removed or something.
1250 resetKeyRepeatLocked();
1251
1252 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001253 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1254 scoped_unlock unlock(mLock);
1255 mPolicy->notifyConfigurationChanged(eventTime);
1256 };
1257 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 return true;
1259}
1260
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1262 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001263 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1264 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1265 entry.deviceId);
1266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267
liushenxiang42232912021-05-21 20:24:09 +08001268 // Reset key repeating in case a keyboard device was disabled or enabled.
1269 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1270 resetKeyRepeatLocked();
1271 }
1272
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001273 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 synthesizeCancelationEventsForAllConnectionsLocked(options);
1276 return true;
1277}
1278
Vishnu Nairad321cd2020-08-20 16:40:21 -07001279void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001280 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001281 if (mPendingEvent != nullptr) {
1282 // Move the pending event to the front of the queue. This will give the chance
1283 // for the pending event to get dispatched to the newly focused window
1284 mInboundQueue.push_front(mPendingEvent);
1285 mPendingEvent = nullptr;
1286 }
1287
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001288 std::unique_ptr<FocusEntry> focusEntry =
1289 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1290 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001291
1292 // This event should go to the front of the queue, but behind all other focus events
1293 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001295 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001296 [](const std::shared_ptr<EventEntry>& event) {
1297 return event->type == EventEntry::Type::FOCUS;
1298 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001299
1300 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001302}
1303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001305 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001306 if (channel == nullptr) {
1307 return; // Window has gone away
1308 }
1309 InputTarget target;
1310 target.inputChannel = channel;
1311 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1312 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001313 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1314 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001315 std::string reason = std::string("reason=").append(entry->reason);
1316 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001317 dispatchEventLocked(currentTime, entry, {target});
1318}
1319
Prabir Pradhan99987712020-11-10 18:43:05 -08001320void InputDispatcher::dispatchPointerCaptureChangedLocked(
1321 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1322 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001323 dropReason = DropReason::NOT_DROPPED;
1324
Prabir Pradhan99987712020-11-10 18:43:05 -08001325 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001326 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001327
1328 if (entry->pointerCaptureRequest.enable) {
1329 // Enable Pointer Capture.
1330 if (haveWindowWithPointerCapture &&
1331 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1332 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1333 "to the window.");
1334 }
1335 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001336 // This can happen if a window requests capture and immediately releases capture.
1337 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001338 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001339 return;
1340 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001341 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1342 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1343 return;
1344 }
1345
Vishnu Nairc519ff72021-01-21 08:23:08 -08001346 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001347 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1348 mWindowTokenWithPointerCapture = token;
1349 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001350 // Disable Pointer Capture.
1351 // We do not check if the sequence number matches for requests to disable Pointer Capture
1352 // for two reasons:
1353 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1354 // to disable capture with the same sequence number: one generated by
1355 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1356 // Capture being disabled in InputReader.
1357 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1358 // actual Pointer Capture state that affects events being generated by input devices is
1359 // in InputReader.
1360 if (!haveWindowWithPointerCapture) {
1361 // Pointer capture was already forcefully disabled because of focus change.
1362 dropReason = DropReason::NOT_DROPPED;
1363 return;
1364 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001365 token = mWindowTokenWithPointerCapture;
1366 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001367 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001368 setPointerCaptureLocked(false);
1369 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001370 }
1371
1372 auto channel = getInputChannelLocked(token);
1373 if (channel == nullptr) {
1374 // Window has gone away, clean up Pointer Capture state.
1375 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001376 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001377 setPointerCaptureLocked(false);
1378 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001379 return;
1380 }
1381 InputTarget target;
1382 target.inputChannel = channel;
1383 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1384 entry->dispatchInProgress = true;
1385 dispatchEventLocked(currentTime, entry, {target});
1386
1387 dropReason = DropReason::NOT_DROPPED;
1388}
1389
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001390void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1391 const std::shared_ptr<TouchModeEntry>& entry) {
1392 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1393 getWindowHandlesLocked(mFocusedDisplayId);
1394 if (windowHandles.empty()) {
1395 return;
1396 }
1397 const std::vector<InputTarget> inputTargets =
1398 getInputTargetsFromWindowHandlesLocked(windowHandles);
1399 if (inputTargets.empty()) {
1400 return;
1401 }
1402 entry->dispatchInProgress = true;
1403 dispatchEventLocked(currentTime, entry, inputTargets);
1404}
1405
1406std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1407 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1408 std::vector<InputTarget> inputTargets;
1409 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1410 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1411 const sp<IBinder>& token = handle->getToken();
1412 if (token == nullptr) {
1413 continue;
1414 }
1415 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1416 if (channel == nullptr) {
1417 continue; // Window has gone away
1418 }
1419 InputTarget target;
1420 target.inputChannel = channel;
1421 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1422 inputTargets.push_back(target);
1423 }
1424 return inputTargets;
1425}
1426
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001427bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001430 if (!entry->dispatchInProgress) {
1431 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1432 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1433 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1434 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001435 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 // We have seen two identical key downs in a row which indicates that the device
1437 // driver is automatically generating key repeats itself. We take note of the
1438 // repeat here, but we disable our own next key repeat timer since it is clear that
1439 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001440 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1441 // Make sure we don't get key down from a different device. If a different
1442 // device Id has same key pressed down, the new device Id will replace the
1443 // current one to hold the key repeat with repeat count reset.
1444 // In the future when got a KEY_UP on the device id, drop it and do not
1445 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1447 resetKeyRepeatLocked();
1448 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1449 } else {
1450 // Not a repeat. Save key down state in case we do see a repeat later.
1451 resetKeyRepeatLocked();
1452 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1453 }
1454 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001455 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1456 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001457 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001458 if (DEBUG_INBOUND_EVENT_DETAILS) {
1459 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1460 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001461 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 resetKeyRepeatLocked();
1463 }
1464
1465 if (entry->repeatCount == 1) {
1466 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1467 } else {
1468 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1469 }
1470
1471 entry->dispatchInProgress = true;
1472
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 }
1475
1476 // Handle case where the policy asked us to try again later last time.
1477 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1478 if (currentTime < entry->interceptKeyWakeupTime) {
1479 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1480 *nextWakeupTime = entry->interceptKeyWakeupTime;
1481 }
1482 return false; // wait until next wakeup
1483 }
1484 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1485 entry->interceptKeyWakeupTime = 0;
1486 }
1487
1488 // Give the policy a chance to intercept the key.
1489 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1490 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001491 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001492 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001493
1494 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1495 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1496 };
1497 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 return false; // wait for the command to run
1499 } else {
1500 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1501 }
1502 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001503 if (*dropReason == DropReason::NOT_DROPPED) {
1504 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 }
1506 }
1507
1508 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001509 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001511 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1512 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001513 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 return true;
1515 }
1516
1517 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001518 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001519 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001520 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001521 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 return false;
1523 }
1524
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001525 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001526 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 return true;
1528 }
1529
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001530 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001531 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532
1533 // Dispatch the key.
1534 dispatchEventLocked(currentTime, entry, inputTargets);
1535 return true;
1536}
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001539 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1540 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1541 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1542 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1543 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1544 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1545 entry.metaState, entry.repeatCount, entry.downTime);
1546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547}
1548
Prabir Pradhancef936d2021-07-21 16:17:52 +00001549void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1550 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001551 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001552 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1553 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1554 "source=0x%x, sensorType=%s",
1555 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001556 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001557 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001558 auto command = [this, entry]() REQUIRES(mLock) {
1559 scoped_unlock unlock(mLock);
1560
1561 if (entry->accuracyChanged) {
1562 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1563 }
1564 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1565 entry->hwTimestamp, entry->values);
1566 };
1567 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001568}
1569
1570bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001571 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1572 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001573 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001574 }
Chris Yef59a2f42020-10-16 12:55:26 -07001575 { // acquire lock
1576 std::scoped_lock _l(mLock);
1577
1578 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1579 std::shared_ptr<EventEntry> entry = *it;
1580 if (entry->type == EventEntry::Type::SENSOR) {
1581 it = mInboundQueue.erase(it);
1582 releaseInboundEventLocked(entry);
1583 }
1584 }
1585 }
1586 return true;
1587}
1588
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001589bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001590 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001591 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001593 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 entry->dispatchInProgress = true;
1595
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001596 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 }
1598
1599 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001600 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001601 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001602 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1603 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 return true;
1605 }
1606
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001607 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608
1609 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001610 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611
1612 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001613 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 if (isPointerEvent) {
1615 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001616 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001617 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 } else {
1620 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001621 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001622 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001624 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 return false;
1626 }
1627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001628 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001629 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001630 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1631 return true;
1632 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001633 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001634 CancelationOptions::Mode mode(isPointerEvent
1635 ? CancelationOptions::CANCEL_POINTER_EVENTS
1636 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1637 CancelationOptions options(mode, "input event injection failed");
1638 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 return true;
1640 }
1641
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001642 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001643 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644
1645 // Dispatch the motion.
1646 if (conflictingPointerActions) {
1647 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 synthesizeCancelationEventsForAllConnectionsLocked(options);
1650 }
1651 dispatchEventLocked(currentTime, entry, inputTargets);
1652 return true;
1653}
1654
chaviw98318de2021-05-19 16:45:23 -05001655void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001656 bool isExiting, const MotionEntry& motionEntry) {
1657 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1658 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1659 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1660 PointerCoords pointerCoords;
1661 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1662 pointerCoords.transform(windowHandle->getInfo()->transform);
1663
1664 std::unique_ptr<DragEntry> dragEntry =
1665 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1666 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1667 pointerCoords.getY());
1668
1669 enqueueInboundEventLocked(std::move(dragEntry));
1670}
1671
1672void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1673 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1674 if (channel == nullptr) {
1675 return; // Window has gone away
1676 }
1677 InputTarget target;
1678 target.inputChannel = channel;
1679 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1680 entry->dispatchInProgress = true;
1681 dispatchEventLocked(currentTime, entry, {target});
1682}
1683
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001684void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001685 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1686 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1687 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001688 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001689 "metaState=0x%x, buttonState=0x%x,"
1690 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1691 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001692 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1693 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1694 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001696 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1697 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1698 "x=%f, y=%f, pressure=%f, size=%f, "
1699 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1700 "orientation=%f",
1701 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1702 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1703 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1704 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1705 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1706 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1707 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1708 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1709 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1710 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713}
1714
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001715void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1716 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001717 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001719 if (DEBUG_DISPATCH_CYCLE) {
1720 ALOGD("dispatchEventToCurrentInputTargets");
1721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001723 updateInteractionTokensLocked(*eventEntry, inputTargets);
1724
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1726
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001727 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001729 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001730 sp<Connection> connection =
1731 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001732 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001733 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001735 if (DEBUG_FOCUS) {
1736 ALOGD("Dropping event delivery to target with channel '%s' because it "
1737 "is no longer registered with the input dispatcher.",
1738 inputTarget.inputChannel->getName().c_str());
1739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 }
1741 }
1742}
1743
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001744void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1745 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1746 // If the policy decides to close the app, we will get a channel removal event via
1747 // unregisterInputChannel, and will clean up the connection that way. We are already not
1748 // sending new pointers to the connection when it blocked, but focused events will continue to
1749 // pile up.
1750 ALOGW("Canceling events for %s because it is unresponsive",
1751 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001752 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001753 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1754 "application not responding");
1755 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757}
1758
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001759void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001760 if (DEBUG_FOCUS) {
1761 ALOGD("Resetting ANR timeouts.");
1762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
1764 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001765 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001766 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767}
1768
Tiger Huang721e26f2018-07-24 22:26:19 +08001769/**
1770 * Get the display id that the given event should go to. If this event specifies a valid display id,
1771 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1772 * Focused display is the display that the user most recently interacted with.
1773 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001774int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001775 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001776 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001777 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001778 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1779 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 break;
1781 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001782 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001783 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1784 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001785 break;
1786 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001787 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001788 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001789 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001790 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001791 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001792 case EventEntry::Type::SENSOR:
1793 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001794 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 return ADISPLAY_ID_NONE;
1796 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001797 }
1798 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1799}
1800
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001801bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1802 const char* focusedWindowName) {
1803 if (mAnrTracker.empty()) {
1804 // already processed all events that we waited for
1805 mKeyIsWaitingForEventsTimeout = std::nullopt;
1806 return false;
1807 }
1808
1809 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1810 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001811 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001812 mKeyIsWaitingForEventsTimeout = currentTime +
1813 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1814 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001815 return true;
1816 }
1817
1818 // We still have pending events, and already started the timer
1819 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1820 return true; // Still waiting
1821 }
1822
1823 // Waited too long, and some connection still hasn't processed all motions
1824 // Just send the key to the focused window
1825 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1826 focusedWindowName);
1827 mKeyIsWaitingForEventsTimeout = std::nullopt;
1828 return false;
1829}
1830
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1832 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1833 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001834 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835
Tiger Huang721e26f2018-07-24 22:26:19 +08001836 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001837 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001838 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001839 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1840
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 // If there is no currently focused window and no focused application
1842 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001843 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1844 ALOGI("Dropping %s event because there is no focused window or focused application in "
1845 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001846 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
1849
Vishnu Nair062a8672021-09-03 16:07:44 -07001850 // Drop key events if requested by input feature
1851 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1852 return InputEventInjectionResult::FAILED;
1853 }
1854
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001855 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1856 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1857 // start interacting with another application via touch (app switch). This code can be removed
1858 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1859 // an app is expected to have a focused window.
1860 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1861 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1862 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001863 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1864 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1865 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001866 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001867 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001868 ALOGW("Waiting because no window has focus but %s may eventually add a "
1869 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001870 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001871 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001873 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1874 // Already raised ANR. Drop the event
1875 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001876 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001878 } else {
1879 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881 }
1882 }
1883
1884 // we have a valid, non-null focused window
1885 resetNoFocusedWindowTimeoutLocked();
1886
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001888 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001889 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 if (focusedWindowHandle->getInfo()->paused) {
1893 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001895 }
1896
1897 // If the event is a key event, then we must wait for all previous events to
1898 // complete before delivering it because previous events may have the
1899 // side-effect of transferring focus to a different window and we want to
1900 // ensure that the following keys are sent to the new window.
1901 //
1902 // Suppose the user touches a button in a window then immediately presses "A".
1903 // If the button causes a pop-up window to appear then we want to ensure that
1904 // the "A" key is delivered to the new pop-up window. This is because users
1905 // often anticipate pending UI changes when typing on a keyboard.
1906 // To obtain this behavior, we must serialize key events with respect to all
1907 // prior input events.
1908 if (entry.type == EventEntry::Type::KEY) {
1909 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1910 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001911 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 }
1914
1915 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001916 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001917 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1918 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919
1920 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922}
1923
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924/**
1925 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1926 * that are currently unresponsive.
1927 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001928std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1929 const std::vector<Monitor>& monitors) const {
1930 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001932 [this](const Monitor& monitor) REQUIRES(mLock) {
1933 sp<Connection> connection =
1934 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001935 if (connection == nullptr) {
1936 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001937 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001938 return false;
1939 }
1940 if (!connection->responsive) {
1941 ALOGW("Unresponsive monitor %s will not get the new gesture",
1942 connection->inputChannel->getName().c_str());
1943 return false;
1944 }
1945 return true;
1946 });
1947 return responsiveMonitors;
1948}
1949
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1951 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1952 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 enum InjectionPermission {
1955 INJECTION_PERMISSION_UNKNOWN,
1956 INJECTION_PERMISSION_GRANTED,
1957 INJECTION_PERMISSION_DENIED
1958 };
1959
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 // For security reasons, we defer updating the touch state until we are sure that
1961 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001962 int32_t displayId = entry.displayId;
1963 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1965
1966 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001967 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001969 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1970 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001972 // Copy current touch state into tempTouchState.
1973 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1974 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001975 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001976 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001977 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1978 mTouchStatesByDisplay.find(displayId);
1979 if (oldStateIt != mTouchStatesByDisplay.end()) {
1980 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001981 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001982 }
1983
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001984 bool isSplit = tempTouchState.split;
1985 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1986 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1987 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001988 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1989 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1990 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1991 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1992 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001993 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 bool wrongDevice = false;
1995 if (newGesture) {
1996 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001998 ALOGI("Dropping event because a pointer for a different device is already down "
1999 "in display %" PRId32,
2000 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002001 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002002 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 switchedDevice = false;
2004 wrongDevice = true;
2005 goto Failed;
2006 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002007 tempTouchState.reset();
2008 tempTouchState.down = down;
2009 tempTouchState.deviceId = entry.deviceId;
2010 tempTouchState.source = entry.source;
2011 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002013 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002014 ALOGI("Dropping move event because a pointer for a different device is already active "
2015 "in display %" PRId32,
2016 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002017 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002018 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002019 switchedDevice = false;
2020 wrongDevice = true;
2021 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
2023
2024 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2025 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2026
Garfield Tan00f511d2019-06-12 16:55:40 -07002027 int32_t x;
2028 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002030 // Always dispatch mouse events to cursor position.
2031 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032 x = int32_t(entry.xCursorPosition);
2033 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002034 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002035 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2036 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002037 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002038 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002039 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2040 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002041
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043 if (newTouchedWindowHandle != nullptr &&
2044 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002045 // New window supports splitting, but we should never split mouse events.
2046 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 } else if (isSplit) {
2048 // New window does not support splitting but we have already split events.
2049 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002050 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 }
2052
2053 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002054 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002055 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2056 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002058 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 }
2060
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002061 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2062 ALOGI("Not sending touch event to %s because it is paused",
2063 newTouchedWindowHandle->getName().c_str());
2064 newTouchedWindowHandle = nullptr;
2065 }
2066
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002067 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002069 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2070 if (!isResponsive) {
2071 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2073 newTouchedWindowHandle = nullptr;
2074 }
2075 }
2076
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002077 // Drop events that can't be trusted due to occlusion
2078 if (newTouchedWindowHandle != nullptr &&
2079 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2080 TouchOcclusionInfo occlusionInfo =
2081 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002082 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002083 if (DEBUG_TOUCH_OCCLUSION) {
2084 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2085 for (const auto& log : occlusionInfo.debugInfo) {
2086 ALOGD("%s", log.c_str());
2087 }
2088 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002089 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002090 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2091 ALOGW("Dropping untrusted touch event due to %s/%d",
2092 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2093 newTouchedWindowHandle = nullptr;
2094 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002095 }
2096 }
2097
Vishnu Nair062a8672021-09-03 16:07:44 -07002098 // Drop touch events if requested by input feature
2099 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2100 newTouchedWindowHandle = nullptr;
2101 }
2102
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002103 const std::vector<Monitor> newGestureMonitors = isDown
2104 ? selectResponsiveMonitorsLocked(
2105 getValueByKey(mGestureMonitorsByDisplay, displayId))
Arthur Hungfbfa5722021-11-16 02:45:54 +00002106 : tempTouchState.gestureMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107
Michael Wright3dd60e22019-03-27 22:06:44 +00002108 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2109 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002110 "(%d, %d) in display %" PRId32 ".",
2111 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002113 goto Failed;
2114 }
2115
2116 if (newTouchedWindowHandle != nullptr) {
2117 // Set target flags.
2118 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2119 if (isSplit) {
2120 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002122 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2123 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2124 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2125 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2126 }
2127
2128 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002129 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2130 newHoverWindowHandle = nullptr;
2131 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002132 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002133 }
2134
2135 // Update the temporary touch state.
2136 BitSet32 pointerIds;
2137 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002138 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 pointerIds.markBit(pointerId);
2140 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002141 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Arthur Hungfbfa5722021-11-16 02:45:54 +00002142 } else if (tempTouchState.windows.empty()) {
2143 // If no window is touched, set split to true. This will allow the next pointer down to
2144 // be delivered to a new window which supports split touch.
2145 tempTouchState.split = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 }
Arthur Hung2ea44b92021-11-23 07:42:21 +00002147 if (isDown) {
2148 tempTouchState.addGestureMonitors(newGestureMonitors);
2149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 } else {
2151 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2152
2153 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002154 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002155 if (DEBUG_FOCUS) {
2156 ALOGD("Dropping event because the pointer is not down or we previously "
2157 "dropped the pointer down event in display %" PRId32,
2158 displayId);
2159 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002160 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 goto Failed;
2162 }
2163
arthurhung6d4bed92021-03-17 11:59:33 +08002164 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002165
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002167 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002169 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2170 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
chaviw98318de2021-05-19 16:45:23 -05002172 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002174 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002175
2176 // Drop touch events if requested by input feature
2177 if (newTouchedWindowHandle != nullptr &&
2178 shouldDropInput(entry, newTouchedWindowHandle)) {
2179 newTouchedWindowHandle = nullptr;
2180 }
2181
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002182 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2183 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002184 if (DEBUG_FOCUS) {
2185 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2186 oldTouchedWindowHandle->getName().c_str(),
2187 newTouchedWindowHandle->getName().c_str(), displayId);
2188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002190 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2191 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2192 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193
2194 // Make a slippery entrance into the new window.
2195 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2196 isSplit = true;
2197 }
2198
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002199 int32_t targetFlags =
2200 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 if (isSplit) {
2202 targetFlags |= InputTarget::FLAG_SPLIT;
2203 }
2204 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2205 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002206 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2207 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 }
2209
2210 BitSet32 pointerIds;
2211 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002212 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002214 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 }
2216 }
2217 }
2218
2219 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002220 // Let the previous window know that the hover sequence is over, unless we already did it
2221 // when dispatching it as is to newTouchedWindowHandle.
2222 if (mLastHoverWindowHandle != nullptr &&
2223 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2224 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002225 if (DEBUG_HOVER) {
2226 ALOGD("Sending hover exit event to window %s.",
2227 mLastHoverWindowHandle->getName().c_str());
2228 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2230 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
2232
Garfield Tandf26e862020-07-01 20:18:19 -07002233 // Let the new window know that the hover sequence is starting, unless we already did it
2234 // when dispatching it as is to newTouchedWindowHandle.
2235 if (newHoverWindowHandle != nullptr &&
2236 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2237 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002238 if (DEBUG_HOVER) {
2239 ALOGD("Sending hover enter event to window %s.",
2240 newHoverWindowHandle->getName().c_str());
2241 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2243 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2244 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246 }
2247
2248 // Check permission to inject into all touched foreground windows and ensure there
2249 // is at least one touched foreground window.
2250 {
2251 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2254 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002255 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002256 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 injectionPermission = INJECTION_PERMISSION_DENIED;
2258 goto Failed;
2259 }
2260 }
2261 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002262 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002263 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002264 ALOGI("Dropping event because there is no touched foreground window in display "
2265 "%" PRId32 " or gesture monitor to receive it.",
2266 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002267 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 goto Failed;
2269 }
2270
2271 // Permission granted to injection into all touched foreground windows.
2272 injectionPermission = INJECTION_PERMISSION_GRANTED;
2273 }
2274
2275 // Check whether windows listening for outside touches are owned by the same UID. If it is
2276 // set the policy flag that we will not reveal coordinate information to this window.
2277 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002278 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002279 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002280 if (foregroundWindowHandle) {
2281 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002282 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002283 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002284 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2285 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2286 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002287 InputTarget::FLAG_ZERO_COORDS,
2288 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291 }
2292 }
2293 }
2294
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 // If this is the first pointer going down and the touched window has a wallpaper
2296 // then also add the touched wallpaper windows so they are locked in for the duration
2297 // of the touch gesture.
2298 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2299 // engine only supports touch events. We would need to add a mechanism similar
2300 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2301 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002302 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002304 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002305 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002306 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002307 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2308 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002310 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 .addOrUpdateWindow(windowHandle,
2313 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2314 InputTarget::
2315 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2316 InputTarget::FLAG_DISPATCH_AS_IS,
2317 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 }
2319 }
2320 }
2321 }
2322
2323 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002324 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002326 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002331 for (const auto& monitor : tempTouchState.gestureMonitors) {
2332 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002333 }
2334
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 // Drop the outside or hover touch windows since we will not care about them
2336 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002337 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
2339Failed:
2340 // Check injection permission once and for all.
2341 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002342 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 injectionPermission = INJECTION_PERMISSION_GRANTED;
2344 } else {
2345 injectionPermission = INJECTION_PERMISSION_DENIED;
2346 }
2347 }
2348
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002349 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2350 return injectionResult;
2351 }
2352
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002354 if (!wrongDevice) {
2355 if (switchedDevice) {
2356 if (DEBUG_FOCUS) {
2357 ALOGD("Conflicting pointer actions: Switched to a different device.");
2358 }
2359 *outConflictingPointerActions = true;
2360 }
2361
2362 if (isHoverAction) {
2363 // Started hovering, therefore no longer down.
2364 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002365 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002366 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2367 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 *outConflictingPointerActions = true;
2370 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002371 tempTouchState.reset();
2372 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2373 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2374 tempTouchState.deviceId = entry.deviceId;
2375 tempTouchState.source = entry.source;
2376 tempTouchState.displayId = displayId;
2377 }
2378 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2379 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2380 // All pointers up or canceled.
2381 tempTouchState.reset();
2382 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2383 // First pointer went down.
2384 if (oldState && oldState->down) {
2385 if (DEBUG_FOCUS) {
2386 ALOGD("Conflicting pointer actions: Down received while already down.");
2387 }
2388 *outConflictingPointerActions = true;
2389 }
2390 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2391 // One pointer went up.
2392 if (isSplit) {
2393 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2394 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002396 for (size_t i = 0; i < tempTouchState.windows.size();) {
2397 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2398 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2399 touchedWindow.pointerIds.clearBit(pointerId);
2400 if (touchedWindow.pointerIds.isEmpty()) {
2401 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2402 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002405 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002407 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002408 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002409
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002410 // Save changes unless the action was scroll in which case the temporary touch
2411 // state was only valid for this one action.
2412 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2413 if (tempTouchState.displayId >= 0) {
2414 mTouchStatesByDisplay[displayId] = tempTouchState;
2415 } else {
2416 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002420 // Update hover state.
2421 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 return injectionResult;
2425}
2426
arthurhung6d4bed92021-03-17 11:59:33 +08002427void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002428 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002429 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002430 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002431 if (dropWindow) {
2432 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002433 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002434 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002435 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002436 }
2437 mDragState.reset();
2438}
2439
2440void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2441 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002442 return;
2443 }
2444
arthurhung6d4bed92021-03-17 11:59:33 +08002445 if (!mDragState->isStartDrag) {
2446 mDragState->isStartDrag = true;
2447 mDragState->isStylusButtonDownAtStart =
2448 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2449 }
2450
arthurhungb89ccb02020-12-30 16:19:01 +08002451 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2452 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2453 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2454 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002455 // Handle the special case : stylus button no longer pressed.
2456 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2457 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2458 finishDragAndDrop(entry.displayId, x, y);
2459 return;
2460 }
2461
chaviw98318de2021-05-19 16:45:23 -05002462 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002463 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002464 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002465 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002466 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2467 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2468 if (mDragState->dragHoverWindowHandle != nullptr) {
2469 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2470 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002471 }
arthurhung6d4bed92021-03-17 11:59:33 +08002472 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002473 }
2474 // enqueue drag location if needed.
2475 if (hoverWindowHandle != nullptr) {
2476 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2477 }
arthurhung6d4bed92021-03-17 11:59:33 +08002478 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2479 finishDragAndDrop(entry.displayId, x, y);
2480 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002481 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002482 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002483 }
2484}
2485
chaviw98318de2021-05-19 16:45:23 -05002486void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 int32_t targetFlags, BitSet32 pointerIds,
2488 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002489 std::vector<InputTarget>::iterator it =
2490 std::find_if(inputTargets.begin(), inputTargets.end(),
2491 [&windowHandle](const InputTarget& inputTarget) {
2492 return inputTarget.inputChannel->getConnectionToken() ==
2493 windowHandle->getToken();
2494 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002495
chaviw98318de2021-05-19 16:45:23 -05002496 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002497
2498 if (it == inputTargets.end()) {
2499 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002500 std::shared_ptr<InputChannel> inputChannel =
2501 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002502 if (inputChannel == nullptr) {
2503 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2504 return;
2505 }
2506 inputTarget.inputChannel = inputChannel;
2507 inputTarget.flags = targetFlags;
2508 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002509 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2510 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002511 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002512 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002513 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002514 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002515 inputTargets.push_back(inputTarget);
2516 it = inputTargets.end() - 1;
2517 }
2518
2519 ALOG_ASSERT(it->flags == targetFlags);
2520 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2521
chaviw1ff3d1e2020-07-01 15:53:47 -07002522 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523}
2524
Michael Wright3dd60e22019-03-27 22:06:44 +00002525void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002526 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002527 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2528 mGlobalMonitorsByDisplay.find(displayId);
2529
2530 if (it != mGlobalMonitorsByDisplay.end()) {
2531 const std::vector<Monitor>& monitors = it->second;
2532 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002533 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 }
2536}
2537
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002538void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002540 InputTarget target;
2541 target.inputChannel = monitor.inputChannel;
2542 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002543 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002544 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002545 const auto& displayTransform = it->second.transform;
2546 target.displayTransform = displayTransform;
2547 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002548 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002549 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002550 inputTargets.push_back(target);
2551}
2552
chaviw98318de2021-05-19 16:45:23 -05002553bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002554 const InjectionState* injectionState) {
2555 if (injectionState &&
2556 (windowHandle == nullptr ||
2557 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2558 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002559 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 "owned by uid %d",
2562 injectionState->injectorPid, injectionState->injectorUid,
2563 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 } else {
2565 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 }
2568 return false;
2569 }
2570 return true;
2571}
2572
Robert Carrc9bf1d32020-04-13 17:21:08 -07002573/**
2574 * Indicate whether one window handle should be considered as obscuring
2575 * another window handle. We only check a few preconditions. Actually
2576 * checking the bounds is left to the caller.
2577 */
chaviw98318de2021-05-19 16:45:23 -05002578static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2579 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002580 // Compare by token so cloned layers aren't counted
2581 if (haveSameToken(windowHandle, otherHandle)) {
2582 return false;
2583 }
2584 auto info = windowHandle->getInfo();
2585 auto otherInfo = otherHandle->getInfo();
2586 if (!otherInfo->visible) {
2587 return false;
chaviw98318de2021-05-19 16:45:23 -05002588 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002589 // Those act as if they were invisible, so we don't need to flag them.
2590 // We do want to potentially flag touchable windows even if they have 0
2591 // opacity, since they can consume touches and alter the effects of the
2592 // user interaction (eg. apps that rely on
2593 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2594 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2595 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002596 } else if (info->ownerUid == otherInfo->ownerUid) {
2597 // If ownerUid is the same we don't generate occlusion events as there
2598 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002599 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002600 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002601 return false;
2602 } else if (otherInfo->displayId != info->displayId) {
2603 return false;
2604 }
2605 return true;
2606}
2607
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002608/**
2609 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2610 * untrusted, one should check:
2611 *
2612 * 1. If result.hasBlockingOcclusion is true.
2613 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2614 * BLOCK_UNTRUSTED.
2615 *
2616 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2617 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2618 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2619 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2620 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2621 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2622 *
2623 * If neither of those is true, then it means the touch can be allowed.
2624 */
2625InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002626 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2627 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002628 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002629 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002630 TouchOcclusionInfo info;
2631 info.hasBlockingOcclusion = false;
2632 info.obscuringOpacity = 0;
2633 info.obscuringUid = -1;
2634 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002635 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002636 if (windowHandle == otherHandle) {
2637 break; // All future windows are below us. Exit early.
2638 }
chaviw98318de2021-05-19 16:45:23 -05002639 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002640 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2641 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002642 if (DEBUG_TOUCH_OCCLUSION) {
2643 info.debugInfo.push_back(
2644 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2645 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002646 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2647 // we perform the checks below to see if the touch can be propagated or not based on the
2648 // window's touch occlusion mode
2649 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2650 info.hasBlockingOcclusion = true;
2651 info.obscuringUid = otherInfo->ownerUid;
2652 info.obscuringPackage = otherInfo->packageName;
2653 break;
2654 }
2655 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2656 uint32_t uid = otherInfo->ownerUid;
2657 float opacity =
2658 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2659 // Given windows A and B:
2660 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2661 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2662 opacityByUid[uid] = opacity;
2663 if (opacity > info.obscuringOpacity) {
2664 info.obscuringOpacity = opacity;
2665 info.obscuringUid = uid;
2666 info.obscuringPackage = otherInfo->packageName;
2667 }
2668 }
2669 }
2670 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002671 if (DEBUG_TOUCH_OCCLUSION) {
2672 info.debugInfo.push_back(
2673 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2674 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002675 return info;
2676}
2677
chaviw98318de2021-05-19 16:45:23 -05002678std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002679 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002680 return StringPrintf(INDENT2
2681 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2682 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2683 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2684 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002685 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002686 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002687 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2688 info->frameTop, info->frameRight, info->frameBottom,
2689 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002690 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2691 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2692 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002693}
2694
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002695bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2696 if (occlusionInfo.hasBlockingOcclusion) {
2697 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2698 occlusionInfo.obscuringUid);
2699 return false;
2700 }
2701 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2702 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2703 "%.2f, maximum allowed = %.2f)",
2704 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2705 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2706 return false;
2707 }
2708 return true;
2709}
2710
chaviw98318de2021-05-19 16:45:23 -05002711bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002712 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002714 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2715 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002716 if (windowHandle == otherHandle) {
2717 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 }
chaviw98318de2021-05-19 16:45:23 -05002719 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002720 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002721 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 return true;
2723 }
2724 }
2725 return false;
2726}
2727
chaviw98318de2021-05-19 16:45:23 -05002728bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002729 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002730 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2731 const WindowInfo* windowInfo = windowHandle->getInfo();
2732 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002733 if (windowHandle == otherHandle) {
2734 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002735 }
chaviw98318de2021-05-19 16:45:23 -05002736 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002737 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002738 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002739 return true;
2740 }
2741 }
2742 return false;
2743}
2744
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002745std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002746 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002747 if (applicationHandle != nullptr) {
2748 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002749 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 } else {
2751 return applicationHandle->getName();
2752 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002753 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002754 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002756 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 }
2758}
2759
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002760void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002761 if (!isUserActivityEvent(eventEntry)) {
2762 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002763 return;
2764 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002765 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002766 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002767 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002768 const WindowInfo* info = focusedWindowHandle->getInfo();
2769 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002770 if (DEBUG_DISPATCH_CYCLE) {
2771 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 return;
2774 }
2775 }
2776
2777 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002778 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002779 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002780 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2781 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002782 return;
2783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002785 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002786 eventType = USER_ACTIVITY_EVENT_TOUCH;
2787 }
2788 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002790 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002791 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2792 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793 return;
2794 }
2795 eventType = USER_ACTIVITY_EVENT_BUTTON;
2796 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002798 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002799 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002800 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002801 break;
2802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 }
2804
Prabir Pradhancef936d2021-07-21 16:17:52 +00002805 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2806 REQUIRES(mLock) {
2807 scoped_unlock unlock(mLock);
2808 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2809 };
2810 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811}
2812
2813void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002814 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002815 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002816 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002817 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002819 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002820 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002821 ATRACE_NAME(message.c_str());
2822 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002823 if (DEBUG_DISPATCH_CYCLE) {
2824 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2825 "globalScaleFactor=%f, pointerIds=0x%x %s",
2826 connection->getInputChannelName().c_str(), inputTarget.flags,
2827 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2828 inputTarget.getPointerInfoString().c_str());
2829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830
2831 // Skip this event if the connection status is not normal.
2832 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002833 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002834 if (DEBUG_DISPATCH_CYCLE) {
2835 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002836 connection->getInputChannelName().c_str(),
2837 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 return;
2840 }
2841
2842 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002843 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2844 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2845 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002846 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002848 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002849 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002850 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002851 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 if (!splitMotionEntry) {
2853 return; // split event was dropped
2854 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002855 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2856 std::string reason = std::string("reason=pointer cancel on split window");
2857 android_log_event_list(LOGTAG_INPUT_CANCEL)
2858 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2859 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002860 if (DEBUG_FOCUS) {
2861 ALOGD("channel '%s' ~ Split motion event.",
2862 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002863 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002864 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002865 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2866 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 return;
2868 }
2869 }
2870
2871 // Not splitting. Enqueue dispatch entries for the event as is.
2872 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2873}
2874
2875void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002876 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002877 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002878 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002879 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002880 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002881 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002882 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002883 ATRACE_NAME(message.c_str());
2884 }
2885
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002886 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
2888 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002889 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002891 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002893 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002895 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002897 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002899 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
2902 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002903 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 startDispatchCycleLocked(currentTime, connection);
2905 }
2906}
2907
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002908void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002909 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002910 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002912 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2914 connection->getInputChannelName().c_str(),
2915 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002916 ATRACE_NAME(message.c_str());
2917 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002918 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 if (!(inputTargetFlags & dispatchMode)) {
2920 return;
2921 }
2922 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2923
2924 // This is a new event.
2925 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002926 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002927 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002929 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2930 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002931 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002933 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002934 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002935 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002936 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002937 dispatchEntry->resolvedAction = keyEntry.action;
2938 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002940 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2941 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002942 if (DEBUG_DISPATCH_CYCLE) {
2943 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2944 "event",
2945 connection->getInputChannelName().c_str());
2946 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 return; // skip the inconsistent event
2948 }
2949 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002952 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002954 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2955 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2956 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2957 static_cast<int32_t>(IdGenerator::Source::OTHER);
2958 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2960 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2961 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2962 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2963 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2964 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2965 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2966 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2967 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2968 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2969 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002970 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002971 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 }
2973 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002974 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2975 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002976 if (DEBUG_DISPATCH_CYCLE) {
2977 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2978 "enter event",
2979 connection->getInputChannelName().c_str());
2980 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002981 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2982 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002986 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2988 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2989 }
2990 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2991 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2995 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002996 if (DEBUG_DISPATCH_CYCLE) {
2997 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2998 "event",
2999 connection->getInputChannelName().c_str());
3000 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 return; // skip the inconsistent event
3002 }
3003
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003004 dispatchEntry->resolvedEventId =
3005 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3006 ? mIdGenerator.nextId()
3007 : motionEntry.id;
3008 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3009 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3010 ") to MotionEvent(id=0x%" PRIx32 ").",
3011 motionEntry.id, dispatchEntry->resolvedEventId);
3012 ATRACE_NAME(message.c_str());
3013 }
3014
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003015 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3016 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3017 // Skip reporting pointer down outside focus to the policy.
3018 break;
3019 }
3020
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003021 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003022 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003023
3024 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003026 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003027 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003028 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3029 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003030 break;
3031 }
Chris Yef59a2f42020-10-16 12:55:26 -07003032 case EventEntry::Type::SENSOR: {
3033 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3034 break;
3035 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003036 case EventEntry::Type::CONFIGURATION_CHANGED:
3037 case EventEntry::Type::DEVICE_RESET: {
3038 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003039 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003040 break;
3041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 }
3043
3044 // Remember that we are waiting for this dispatch to complete.
3045 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003046 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
3048
3049 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003050 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003051 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003052}
3053
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003054/**
3055 * This function is purely for debugging. It helps us understand where the user interaction
3056 * was taking place. For example, if user is touching launcher, we will see a log that user
3057 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3058 * We will see both launcher and wallpaper in that list.
3059 * Once the interaction with a particular set of connections starts, no new logs will be printed
3060 * until the set of interacted connections changes.
3061 *
3062 * The following items are skipped, to reduce the logspam:
3063 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3064 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3065 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3066 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3067 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003068 */
3069void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3070 const std::vector<InputTarget>& targets) {
3071 // Skip ACTION_UP events, and all events other than keys and motions
3072 if (entry.type == EventEntry::Type::KEY) {
3073 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3074 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3075 return;
3076 }
3077 } else if (entry.type == EventEntry::Type::MOTION) {
3078 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3079 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3080 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3081 return;
3082 }
3083 } else {
3084 return; // Not a key or a motion
3085 }
3086
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003087 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003088 std::vector<sp<Connection>> newConnections;
3089 for (const InputTarget& target : targets) {
3090 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3091 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3092 continue; // Skip windows that receive ACTION_OUTSIDE
3093 }
3094
3095 sp<IBinder> token = target.inputChannel->getConnectionToken();
3096 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003097 if (connection == nullptr) {
3098 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003099 }
3100 newConnectionTokens.insert(std::move(token));
3101 newConnections.emplace_back(connection);
3102 }
3103 if (newConnectionTokens == mInteractionConnectionTokens) {
3104 return; // no change
3105 }
3106 mInteractionConnectionTokens = newConnectionTokens;
3107
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003108 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003109 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003110 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003111 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003112 std::string message = "Interaction with: " + targetList;
3113 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003114 message += "<none>";
3115 }
3116 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3117}
3118
chaviwfd6d3512019-03-25 13:23:49 -07003119void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003120 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003121 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003122 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3123 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003124 return;
3125 }
3126
Vishnu Nairc519ff72021-01-21 08:23:08 -08003127 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003128 if (focusedToken == token) {
3129 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003130 return;
3131 }
3132
Prabir Pradhancef936d2021-07-21 16:17:52 +00003133 auto command = [this, token]() REQUIRES(mLock) {
3134 scoped_unlock unlock(mLock);
3135 mPolicy->onPointerDownOutsideFocus(token);
3136 };
3137 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138}
3139
3140void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003142 if (ATRACE_ENABLED()) {
3143 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003145 ATRACE_NAME(message.c_str());
3146 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003147 if (DEBUG_DISPATCH_CYCLE) {
3148 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003151 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003152 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003154 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003155 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003156 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
3158 // Publish the event.
3159 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3161 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003162 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3164 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003167 status = connection->inputPublisher
3168 .publishKeyEvent(dispatchEntry->seq,
3169 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3170 keyEntry.source, keyEntry.displayId,
3171 std::move(hmac), dispatchEntry->resolvedAction,
3172 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3173 keyEntry.scanCode, keyEntry.metaState,
3174 keyEntry.repeatCount, keyEntry.downTime,
3175 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
3178
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184
chaviw82357092020-01-28 13:13:06 -08003185 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003186 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3188 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003189 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003190 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3191 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003192 // Don't apply window scale here since we don't want scale to affect raw
3193 // coordinates. The scale will be sent back to the client and applied
3194 // later when requesting relative coordinates.
3195 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3196 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 }
3198 usingCoords = scaledCoords;
3199 }
3200 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 // We don't want the dispatch target to know.
3202 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003203 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 scaledCoords[i].clear();
3205 }
3206 usingCoords = scaledCoords;
3207 }
3208 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003209
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003210 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211
3212 // Publish the motion event.
3213 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003214 .publishMotionEvent(dispatchEntry->seq,
3215 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003216 motionEntry.deviceId, motionEntry.source,
3217 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003218 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003219 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003221 motionEntry.edgeFlags, motionEntry.metaState,
3222 motionEntry.buttonState,
3223 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003224 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003225 motionEntry.xPrecision, motionEntry.yPrecision,
3226 motionEntry.xCursorPosition,
3227 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003228 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003229 motionEntry.downTime, motionEntry.eventTime,
3230 motionEntry.pointerCount,
3231 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 break;
3233 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003234
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003235 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003236 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003237 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003238 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003239 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003240 break;
3241 }
3242
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003243 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3244 const TouchModeEntry& touchModeEntry =
3245 static_cast<const TouchModeEntry&>(eventEntry);
3246 status = connection->inputPublisher
3247 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3248 touchModeEntry.inTouchMode);
3249
3250 break;
3251 }
3252
Prabir Pradhan99987712020-11-10 18:43:05 -08003253 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3254 const auto& captureEntry =
3255 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3256 status = connection->inputPublisher
3257 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003258 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003259 break;
3260 }
3261
arthurhungb89ccb02020-12-30 16:19:01 +08003262 case EventEntry::Type::DRAG: {
3263 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3264 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3265 dragEntry.id, dragEntry.x,
3266 dragEntry.y,
3267 dragEntry.isExiting);
3268 break;
3269 }
3270
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003271 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003272 case EventEntry::Type::DEVICE_RESET:
3273 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003274 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003275 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 }
3279
3280 // Check the result.
3281 if (status) {
3282 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003283 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003285 "This is unexpected because the wait queue is empty, so the pipe "
3286 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003287 "event to it, status=%s(%d)",
3288 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3289 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3291 } else {
3292 // Pipe is full and we are waiting for the app to finish process some events
3293 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003294 if (DEBUG_DISPATCH_CYCLE) {
3295 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3296 "waiting for the application to catch up",
3297 connection->getInputChannelName().c_str());
3298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
3300 } else {
3301 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003302 "status=%s(%d)",
3303 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3304 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3306 }
3307 return;
3308 }
3309
3310 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003311 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3312 connection->outboundQueue.end(),
3313 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003314 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003316 if (connection->responsive) {
3317 mAnrTracker.insert(dispatchEntry->timeoutTime,
3318 connection->inputChannel->getConnectionToken());
3319 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003320 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
3322}
3323
chaviw09c8d2d2020-08-24 15:48:26 -07003324std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3325 size_t size;
3326 switch (event.type) {
3327 case VerifiedInputEvent::Type::KEY: {
3328 size = sizeof(VerifiedKeyEvent);
3329 break;
3330 }
3331 case VerifiedInputEvent::Type::MOTION: {
3332 size = sizeof(VerifiedMotionEvent);
3333 break;
3334 }
3335 }
3336 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3337 return mHmacKeyManager.sign(start, size);
3338}
3339
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003340const std::array<uint8_t, 32> InputDispatcher::getSignature(
3341 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003342 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3343 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003344 // Only sign events up and down events as the purely move events
3345 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003346 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003347 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003348
3349 VerifiedMotionEvent verifiedEvent =
3350 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3351 verifiedEvent.actionMasked = actionMasked;
3352 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3353 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003354}
3355
3356const std::array<uint8_t, 32> InputDispatcher::getSignature(
3357 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3358 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3359 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3360 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003361 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003362}
3363
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003366 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003367 if (DEBUG_DISPATCH_CYCLE) {
3368 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3369 connection->getInputChannelName().c_str(), seq, toString(handled));
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003372 if (connection->status == Connection::Status::BROKEN ||
3373 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 return;
3375 }
3376
3377 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003378 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3379 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3380 };
3381 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382}
3383
3384void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 const sp<Connection>& connection,
3386 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003387 if (DEBUG_DISPATCH_CYCLE) {
3388 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3389 connection->getInputChannelName().c_str(), toString(notify));
3390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
3392 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003393 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003394 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003395 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003396 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397
3398 // The connection appears to be unrecoverably broken.
3399 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003400 if (connection->status == Connection::Status::NORMAL) {
3401 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402
3403 if (notify) {
3404 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003405 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3406 connection->getInputChannelName().c_str());
3407
3408 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003409 scoped_unlock unlock(mLock);
3410 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3411 };
3412 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414 }
3415}
3416
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003417void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3418 while (!queue.empty()) {
3419 DispatchEntry* dispatchEntry = queue.front();
3420 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003421 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
3423}
3424
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003425void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003427 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
3429 delete dispatchEntry;
3430}
3431
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003432int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3433 std::scoped_lock _l(mLock);
3434 sp<Connection> connection = getConnectionLocked(connectionToken);
3435 if (connection == nullptr) {
3436 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3437 connectionToken.get(), events);
3438 return 0; // remove the callback
3439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003441 bool notify;
3442 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3443 if (!(events & ALOOPER_EVENT_INPUT)) {
3444 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3445 "events=0x%x",
3446 connection->getInputChannelName().c_str(), events);
3447 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003450 nsecs_t currentTime = now();
3451 bool gotOne = false;
3452 status_t status = OK;
3453 for (;;) {
3454 Result<InputPublisher::ConsumerResponse> result =
3455 connection->inputPublisher.receiveConsumerResponse();
3456 if (!result.ok()) {
3457 status = result.error().code();
3458 break;
3459 }
3460
3461 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3462 const InputPublisher::Finished& finish =
3463 std::get<InputPublisher::Finished>(*result);
3464 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3465 finish.consumeTime);
3466 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003467 if (shouldReportMetricsForConnection(*connection)) {
3468 const InputPublisher::Timeline& timeline =
3469 std::get<InputPublisher::Timeline>(*result);
3470 mLatencyTracker
3471 .trackGraphicsLatency(timeline.inputEventId,
3472 connection->inputChannel->getConnectionToken(),
3473 std::move(timeline.graphicsTimeline));
3474 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003475 }
3476 gotOne = true;
3477 }
3478 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003479 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003480 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481 return 1;
3482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003485 notify = status != DEAD_OBJECT || !connection->monitor;
3486 if (notify) {
3487 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3488 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3489 status);
3490 }
3491 } else {
3492 // Monitor channels are never explicitly unregistered.
3493 // We do it automatically when the remote endpoint is closed so don't warn about them.
3494 const bool stillHaveWindowHandle =
3495 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3496 notify = !connection->monitor && stillHaveWindowHandle;
3497 if (notify) {
3498 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3499 connection->getInputChannelName().c_str(), events);
3500 }
3501 }
3502
3503 // Remove the channel.
3504 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3505 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506}
3507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003510 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003511 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
3513}
3514
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003516 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003517 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3518 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3519}
3520
3521void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3522 const CancelationOptions& options,
3523 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3524 for (const auto& it : monitorsByDisplay) {
3525 const std::vector<Monitor>& monitors = it.second;
3526 for (const Monitor& monitor : monitors) {
3527 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003528 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003529 }
3530}
3531
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003533 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003534 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003535 if (connection == nullptr) {
3536 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003538
3539 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540}
3541
3542void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3543 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003544 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 return;
3546 }
3547
3548 nsecs_t currentTime = now();
3549
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003550 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003551 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003553 if (cancelationEvents.empty()) {
3554 return;
3555 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003556 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3557 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3558 "with reality: %s, mode=%d.",
3559 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3560 options.mode);
3561 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003562
Arthur Hungb3307ee2021-10-14 10:57:37 +00003563 std::string reason = std::string("reason=").append(options.reason);
3564 android_log_event_list(LOGTAG_INPUT_CANCEL)
3565 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3566
Svet Ganov5d3bc372020-01-26 23:11:07 -08003567 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003568 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3570 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003571 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003572 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003573 target.globalScaleFactor = windowInfo->globalScaleFactor;
3574 }
3575 target.inputChannel = connection->inputChannel;
3576 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3577
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003578 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003579 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003580 switch (cancelationEventEntry->type) {
3581 case EventEntry::Type::KEY: {
3582 logOutboundKeyDetails("cancel - ",
3583 static_cast<const KeyEntry&>(*cancelationEventEntry));
3584 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003586 case EventEntry::Type::MOTION: {
3587 logOutboundMotionDetails("cancel - ",
3588 static_cast<const MotionEntry&>(*cancelationEventEntry));
3589 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003591 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003592 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003593 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3594 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003595 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003596 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003597 break;
3598 }
3599 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003600 case EventEntry::Type::DEVICE_RESET:
3601 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003602 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003603 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003604 break;
3605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
3607
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003608 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3609 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003611
3612 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613}
3614
Svet Ganov5d3bc372020-01-26 23:11:07 -08003615void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3616 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003617 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003618 return;
3619 }
3620
3621 nsecs_t currentTime = now();
3622
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003623 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003624 connection->inputState.synthesizePointerDownEvents(currentTime);
3625
3626 if (downEvents.empty()) {
3627 return;
3628 }
3629
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003630 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3632 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003633 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003634
3635 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003636 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003637 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3638 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003639 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003640 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003641 target.globalScaleFactor = windowInfo->globalScaleFactor;
3642 }
3643 target.inputChannel = connection->inputChannel;
3644 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3645
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003646 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003647 switch (downEventEntry->type) {
3648 case EventEntry::Type::MOTION: {
3649 logOutboundMotionDetails("down - ",
3650 static_cast<const MotionEntry&>(*downEventEntry));
3651 break;
3652 }
3653
3654 case EventEntry::Type::KEY:
3655 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003656 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003657 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003658 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003659 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003660 case EventEntry::Type::SENSOR:
3661 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003662 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003663 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664 break;
3665 }
3666 }
3667
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003668 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3669 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 }
3671
3672 startDispatchCycleLocked(currentTime, connection);
3673}
3674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3676 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 ALOG_ASSERT(pointerIds.value != 0);
3678
3679 uint32_t splitPointerIndexMap[MAX_POINTERS];
3680 PointerProperties splitPointerProperties[MAX_POINTERS];
3681 PointerCoords splitPointerCoords[MAX_POINTERS];
3682
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003683 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 uint32_t splitPointerCount = 0;
3685
3686 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003687 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003689 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 uint32_t pointerId = uint32_t(pointerProperties.id);
3691 if (pointerIds.hasBit(pointerId)) {
3692 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3693 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3694 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003695 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 splitPointerCount += 1;
3697 }
3698 }
3699
3700 if (splitPointerCount != pointerIds.count()) {
3701 // This is bad. We are missing some of the pointers that we expected to deliver.
3702 // Most likely this indicates that we received an ACTION_MOVE events that has
3703 // different pointer ids than we expected based on the previous ACTION_DOWN
3704 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3705 // in this way.
3706 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 "we expected there to be %d pointers. This probably means we received "
3708 "a broken sequence of pointer ids from the input device.",
3709 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003710 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003713 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003715 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3716 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3718 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003719 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 uint32_t pointerId = uint32_t(pointerProperties.id);
3721 if (pointerIds.hasBit(pointerId)) {
3722 if (pointerIds.count() == 1) {
3723 // The first/last pointer went down/up.
3724 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003725 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003726 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3727 ? AMOTION_EVENT_ACTION_CANCEL
3728 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 } else {
3730 // A secondary pointer went down/up.
3731 uint32_t splitPointerIndex = 0;
3732 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3733 splitPointerIndex += 1;
3734 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 action = maskedAction |
3736 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 }
3738 } else {
3739 // An unrelated pointer changed.
3740 action = AMOTION_EVENT_ACTION_MOVE;
3741 }
3742 }
3743
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003744 int32_t newId = mIdGenerator.nextId();
3745 if (ATRACE_ENABLED()) {
3746 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3747 ") to MotionEvent(id=0x%" PRIx32 ").",
3748 originalMotionEntry.id, newId);
3749 ATRACE_NAME(message.c_str());
3750 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003751 std::unique_ptr<MotionEntry> splitMotionEntry =
3752 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3753 originalMotionEntry.deviceId, originalMotionEntry.source,
3754 originalMotionEntry.displayId,
3755 originalMotionEntry.policyFlags, action,
3756 originalMotionEntry.actionButton,
3757 originalMotionEntry.flags, originalMotionEntry.metaState,
3758 originalMotionEntry.buttonState,
3759 originalMotionEntry.classification,
3760 originalMotionEntry.edgeFlags,
3761 originalMotionEntry.xPrecision,
3762 originalMotionEntry.yPrecision,
3763 originalMotionEntry.xCursorPosition,
3764 originalMotionEntry.yCursorPosition,
3765 originalMotionEntry.downTime, splitPointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00003766 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003768 if (originalMotionEntry.injectionState) {
3769 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 splitMotionEntry->injectionState->refCount += 1;
3771 }
3772
3773 return splitMotionEntry;
3774}
3775
3776void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 if (DEBUG_INBOUND_EVENT_DETAILS) {
3778 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
Antonio Kantekf16f2832021-09-28 04:39:20 +00003781 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003783 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3786 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3787 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 } // release lock
3789
3790 if (needWake) {
3791 mLooper->wake();
3792 }
3793}
3794
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003795/**
3796 * If one of the meta shortcuts is detected, process them here:
3797 * Meta + Backspace -> generate BACK
3798 * Meta + Enter -> generate HOME
3799 * This will potentially overwrite keyCode and metaState.
3800 */
3801void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003803 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3804 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3805 if (keyCode == AKEYCODE_DEL) {
3806 newKeyCode = AKEYCODE_BACK;
3807 } else if (keyCode == AKEYCODE_ENTER) {
3808 newKeyCode = AKEYCODE_HOME;
3809 }
3810 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003811 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003812 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003813 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003814 keyCode = newKeyCode;
3815 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3816 }
3817 } else if (action == AKEY_EVENT_ACTION_UP) {
3818 // In order to maintain a consistent stream of up and down events, check to see if the key
3819 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3820 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003821 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003822 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003823 auto replacementIt = mReplacedKeys.find(replacement);
3824 if (replacementIt != mReplacedKeys.end()) {
3825 keyCode = replacementIt->second;
3826 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003827 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3828 }
3829 }
3830}
3831
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003833 if (DEBUG_INBOUND_EVENT_DETAILS) {
3834 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3835 "policyFlags=0x%x, action=0x%x, "
3836 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3837 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3838 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3839 args->downTime);
3840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 if (!validateKeyEvent(args->action)) {
3842 return;
3843 }
3844
3845 uint32_t policyFlags = args->policyFlags;
3846 int32_t flags = args->flags;
3847 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003848 // InputDispatcher tracks and generates key repeats on behalf of
3849 // whatever notifies it, so repeatCount should always be set to 0
3850 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3852 policyFlags |= POLICY_FLAG_VIRTUAL;
3853 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 if (policyFlags & POLICY_FLAG_FUNCTION) {
3856 metaState |= AMETA_FUNCTION_ON;
3857 }
3858
3859 policyFlags |= POLICY_FLAG_TRUSTED;
3860
Michael Wright78f24442014-08-06 15:55:28 -07003861 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003862 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003863
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003865 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003866 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3867 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868
Michael Wright2b3c3302018-03-02 17:19:13 +00003869 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003871 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3872 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003873 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
Antonio Kantekf16f2832021-09-28 04:39:20 +00003876 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 { // acquire lock
3878 mLock.lock();
3879
3880 if (shouldSendKeyToInputFilterLocked(args)) {
3881 mLock.unlock();
3882
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003883 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3885 return; // event was consumed by the filter
3886 }
3887
3888 mLock.lock();
3889 }
3890
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003891 std::unique_ptr<KeyEntry> newEntry =
3892 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3893 args->displayId, policyFlags, args->action, flags,
3894 keyCode, args->scanCode, metaState, repeatCount,
3895 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003897 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 mLock.unlock();
3899 } // release lock
3900
3901 if (needWake) {
3902 mLooper->wake();
3903 }
3904}
3905
3906bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3907 return mInputFilterEnabled;
3908}
3909
3910void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003911 if (DEBUG_INBOUND_EVENT_DETAILS) {
3912 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3913 "displayId=%" PRId32 ", policyFlags=0x%x, "
3914 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3915 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3916 "yCursorPosition=%f, downTime=%" PRId64,
3917 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3918 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3919 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3920 args->xCursorPosition, args->yCursorPosition, args->downTime);
3921 for (uint32_t i = 0; i < args->pointerCount; i++) {
3922 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3923 "x=%f, y=%f, pressure=%f, size=%f, "
3924 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3925 "orientation=%f",
3926 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3927 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3928 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3929 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3930 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3931 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3932 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3933 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3934 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3935 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003938 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3939 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 return;
3941 }
3942
3943 uint32_t policyFlags = args->policyFlags;
3944 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003945
3946 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003947 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003948 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3949 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
Antonio Kantekf16f2832021-09-28 04:39:20 +00003953 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 { // acquire lock
3955 mLock.lock();
3956
3957 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003958 ui::Transform displayTransform;
3959 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3960 displayTransform = it->second.transform;
3961 }
3962
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 mLock.unlock();
3964
3965 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003966 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3967 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003968 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003969 displayTransform, args->xPrecision, args->yPrecision,
3970 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003971 args->downTime, args->eventTime, args->pointerCount,
3972 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973
3974 policyFlags |= POLICY_FLAG_FILTERED;
3975 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3976 return; // event was consumed by the filter
3977 }
3978
3979 mLock.lock();
3980 }
3981
3982 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003983 std::unique_ptr<MotionEntry> newEntry =
3984 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3985 args->source, args->displayId, policyFlags,
3986 args->action, args->actionButton, args->flags,
3987 args->metaState, args->buttonState,
3988 args->classification, args->edgeFlags,
3989 args->xPrecision, args->yPrecision,
3990 args->xCursorPosition, args->yCursorPosition,
3991 args->downTime, args->pointerCount,
Alex Chauf7c99f32021-12-03 10:37:54 +00003992 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00003994 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3995 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3996 !mInputFilterEnabled) {
3997 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3998 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3999 }
4000
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004001 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 mLock.unlock();
4003 } // release lock
4004
4005 if (needWake) {
4006 mLooper->wake();
4007 }
4008}
4009
Chris Yef59a2f42020-10-16 12:55:26 -07004010void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004011 if (DEBUG_INBOUND_EVENT_DETAILS) {
4012 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4013 " sensorType=%s",
4014 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004015 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004016 }
Chris Yef59a2f42020-10-16 12:55:26 -07004017
Antonio Kantekf16f2832021-09-28 04:39:20 +00004018 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004019 { // acquire lock
4020 mLock.lock();
4021
4022 // Just enqueue a new sensor event.
4023 std::unique_ptr<SensorEntry> newEntry =
4024 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4025 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4026 args->sensorType, args->accuracy,
4027 args->accuracyChanged, args->values);
4028
4029 needWake = enqueueInboundEventLocked(std::move(newEntry));
4030 mLock.unlock();
4031 } // release lock
4032
4033 if (needWake) {
4034 mLooper->wake();
4035 }
4036}
4037
Chris Yefb552902021-02-03 17:18:37 -08004038void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 if (DEBUG_INBOUND_EVENT_DETAILS) {
4040 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4041 args->deviceId, args->isOn);
4042 }
Chris Yefb552902021-02-03 17:18:37 -08004043 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4044}
4045
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004047 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048}
4049
4050void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004051 if (DEBUG_INBOUND_EVENT_DETAILS) {
4052 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4053 "switchMask=0x%08x",
4054 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056
4057 uint32_t policyFlags = args->policyFlags;
4058 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060}
4061
4062void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004063 if (DEBUG_INBOUND_EVENT_DETAILS) {
4064 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4065 args->deviceId);
4066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067
Antonio Kantekf16f2832021-09-28 04:39:20 +00004068 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004070 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004072 std::unique_ptr<DeviceResetEntry> newEntry =
4073 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4074 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 } // release lock
4076
4077 if (needWake) {
4078 mLooper->wake();
4079 }
4080}
4081
Prabir Pradhan7e186182020-11-10 13:56:45 -08004082void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004083 if (DEBUG_INBOUND_EVENT_DETAILS) {
4084 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004085 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004087
Antonio Kantekf16f2832021-09-28 04:39:20 +00004088 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004089 { // acquire lock
4090 std::scoped_lock _l(mLock);
4091 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004092 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004093 needWake = enqueueInboundEventLocked(std::move(entry));
4094 } // release lock
4095
4096 if (needWake) {
4097 mLooper->wake();
4098 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004099}
4100
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004101InputEventInjectionResult InputDispatcher::injectInputEvent(
4102 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4103 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004104 if (DEBUG_INBOUND_EVENT_DETAILS) {
4105 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4106 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4107 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4108 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004109 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
4111 policyFlags |= POLICY_FLAG_INJECTED;
4112 if (hasInjectionPermission(injectorPid, injectorUid)) {
4113 policyFlags |= POLICY_FLAG_TRUSTED;
4114 }
4115
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004116 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004117 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4118 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4119 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4120 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4121 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004122 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004123 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004124 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004125 }
4126
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004127 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004130 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4131 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004133 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004136 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4138 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4139 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004140 int32_t keyCode = incomingKey.getKeyCode();
4141 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004142 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004144 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004145 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004146 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4147 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4148 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004150 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4151 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004152 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153
4154 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4155 android::base::Timer t;
4156 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4157 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4158 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4159 std::to_string(t.duration().count()).c_str());
4160 }
4161 }
4162
4163 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004164 std::unique_ptr<KeyEntry> injectedEntry =
4165 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004166 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004167 incomingKey.getDisplayId(), policyFlags, action,
4168 flags, keyCode, incomingKey.getScanCode(), metaState,
4169 incomingKey.getRepeatCount(),
4170 incomingKey.getDownTime());
4171 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 }
4174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004177 const int32_t action = motionEvent.getAction();
4178 const bool isPointerEvent =
4179 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4180 // If a pointer event has no displayId specified, inject it to the default display.
4181 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4182 ? ADISPLAY_ID_DEFAULT
4183 : event->getDisplayId();
4184 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004185 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004186 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004187 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004190 }
4191
4192 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004193 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194 android::base::Timer t;
4195 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4196 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4197 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4198 std::to_string(t.duration().count()).c_str());
4199 }
4200 }
4201
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004202 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4203 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4204 }
4205
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004207 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4208 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004209 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004210 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4211 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004212 displayId, policyFlags, action, actionButton,
4213 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004214 motionEvent.getButtonState(),
4215 motionEvent.getClassification(),
4216 motionEvent.getEdgeFlags(),
4217 motionEvent.getXPrecision(),
4218 motionEvent.getYPrecision(),
4219 motionEvent.getRawXCursorPosition(),
4220 motionEvent.getRawYCursorPosition(),
4221 motionEvent.getDownTime(), uint32_t(pointerCount),
Alex Chau663fc832021-12-03 10:37:54 +00004222 pointerProperties, samplePointerCoords,
4223 motionEvent.getXOffset(),
4224 motionEvent.getYOffset());
4225 transformMotionEntryForInjectionLocked(*injectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004226 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 sampleEventTimes += 1;
4229 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004230 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004231 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4232 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004233 displayId, policyFlags, action, actionButton,
4234 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 motionEvent.getButtonState(),
4236 motionEvent.getClassification(),
4237 motionEvent.getEdgeFlags(),
4238 motionEvent.getXPrecision(),
4239 motionEvent.getYPrecision(),
4240 motionEvent.getRawXCursorPosition(),
4241 motionEvent.getRawYCursorPosition(),
4242 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004243 uint32_t(pointerCount), pointerProperties,
Alex Chau663fc832021-12-03 10:37:54 +00004244 samplePointerCoords, motionEvent.getXOffset(),
4245 motionEvent.getYOffset());
4246 transformMotionEntryForInjectionLocked(*nextInjectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 }
4249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004253 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004254 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 }
4256
4257 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 injectionState->injectionIsAsync = true;
4260 }
4261
4262 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004263 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264
4265 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004266 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004268 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270
4271 mLock.unlock();
4272
4273 if (needWake) {
4274 mLooper->wake();
4275 }
4276
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004277 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004279 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004281 if (syncMode == InputEventInjectionSync::NONE) {
4282 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 } else {
4284 for (;;) {
4285 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 break;
4288 }
4289
4290 nsecs_t remainingTimeout = endTime - now();
4291 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004292 if (DEBUG_INJECTION) {
4293 ALOGD("injectInputEvent - Timed out waiting for injection result "
4294 "to become available.");
4295 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 break;
4298 }
4299
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004300 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 }
4302
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004303 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4304 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004306 if (DEBUG_INJECTION) {
4307 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4308 injectionState->pendingForegroundDispatches);
4309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 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 pending foreground "
4314 "dispatches to finish.");
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 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322 }
4323 }
4324
4325 injectionState->release();
4326 } // release lock
4327
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004328 if (DEBUG_INJECTION) {
4329 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4330 injectionResult, injectorPid, injectorUid);
4331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
4333 return injectionResult;
4334}
4335
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004336std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004337 std::array<uint8_t, 32> calculatedHmac;
4338 std::unique_ptr<VerifiedInputEvent> result;
4339 switch (event.getType()) {
4340 case AINPUT_EVENT_TYPE_KEY: {
4341 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4342 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4343 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004344 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004345 break;
4346 }
4347 case AINPUT_EVENT_TYPE_MOTION: {
4348 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4349 VerifiedMotionEvent verifiedMotionEvent =
4350 verifiedMotionEventFromMotionEvent(motionEvent);
4351 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004352 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004353 break;
4354 }
4355 default: {
4356 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4357 return nullptr;
4358 }
4359 }
4360 if (calculatedHmac == INVALID_HMAC) {
4361 return nullptr;
4362 }
4363 if (calculatedHmac != event.getHmac()) {
4364 return nullptr;
4365 }
4366 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004367}
4368
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 return injectorUid == 0 ||
4371 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372}
4373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004374void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004375 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004376 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004378 if (DEBUG_INJECTION) {
4379 ALOGD("Setting input event injection result to %d. "
4380 "injectorPid=%d, injectorUid=%d",
4381 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004384 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 // Log the outcome since the injector did not wait for the injection result.
4386 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 ALOGV("Asynchronous input event injection succeeded.");
4389 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004390 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004391 ALOGW("Asynchronous input event injection failed.");
4392 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 ALOGW("Asynchronous input event injection permission denied.");
4395 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004397 ALOGW("Asynchronous input event injection timed out.");
4398 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004399 case InputEventInjectionResult::PENDING:
4400 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4401 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 }
4403 }
4404
4405 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004406 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 }
4408}
4409
Alex Chau663fc832021-12-03 10:37:54 +00004410void InputDispatcher::transformMotionEntryForInjectionLocked(MotionEntry& entry) const {
4411 const bool isRelativeMouseEvent = isFromSource(entry.source, AINPUT_SOURCE_MOUSE_RELATIVE);
4412 if (!isRelativeMouseEvent && !isFromSource(entry.source, AINPUT_SOURCE_CLASS_POINTER)) {
4413 return;
4414 }
4415
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004416 // Input injection works in the logical display coordinate space, but the input pipeline works
4417 // display space, so we need to transform the injected events accordingly.
4418 const auto it = mDisplayInfos.find(entry.displayId);
4419 if (it == mDisplayInfos.end()) return;
Alex Chau663fc832021-12-03 10:37:54 +00004420 const auto& transformToDisplay = it->second.transform.inverse();
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004421
4422 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4423 PointerCoords& pc = entry.pointerCoords[i];
Alex Chau663fc832021-12-03 10:37:54 +00004424 const auto xy = isRelativeMouseEvent
4425 ? transformWithoutTranslation(transformToDisplay, pc.getX(), pc.getY())
4426 : transformToDisplay.transform(pc.getXYValue());
4427 pc.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
4428 pc.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004429
Alex Chau663fc832021-12-03 10:37:54 +00004430 // Axes with relative values never represent points on a screen, so they should never have
4431 // translation applied. If a device does not report relative values, these values are always
4432 // 0, and will remain unaffected by the following operation.
4433 const auto rel =
4434 transformWithoutTranslation(transformToDisplay,
4435 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
4436 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4437 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, rel.x);
4438 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, rel.y);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004439 }
4440}
4441
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004442void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4443 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 if (injectionState) {
4445 injectionState->pendingForegroundDispatches += 1;
4446 }
4447}
4448
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004449void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4450 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 if (injectionState) {
4452 injectionState->pendingForegroundDispatches -= 1;
4453
4454 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004455 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 }
4457 }
4458}
4459
chaviw98318de2021-05-19 16:45:23 -05004460const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004461 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004462 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004463 auto it = mWindowHandlesByDisplay.find(displayId);
4464 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004465}
4466
chaviw98318de2021-05-19 16:45:23 -05004467sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004468 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004469 if (windowHandleToken == nullptr) {
4470 return nullptr;
4471 }
4472
Arthur Hungb92218b2018-08-14 12:00:21 +08004473 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004474 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4475 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004476 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004477 return windowHandle;
4478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 }
4480 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004481 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482}
4483
chaviw98318de2021-05-19 16:45:23 -05004484sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4485 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004486 if (windowHandleToken == nullptr) {
4487 return nullptr;
4488 }
4489
chaviw98318de2021-05-19 16:45:23 -05004490 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004491 if (windowHandle->getToken() == windowHandleToken) {
4492 return windowHandle;
4493 }
4494 }
4495 return nullptr;
4496}
4497
chaviw98318de2021-05-19 16:45:23 -05004498sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4499 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004500 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004501 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4502 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004503 if (handle->getId() == windowHandle->getId() &&
4504 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004505 if (windowHandle->getInfo()->displayId != it.first) {
4506 ALOGE("Found window %s in display %" PRId32
4507 ", but it should belong to display %" PRId32,
4508 windowHandle->getName().c_str(), it.first,
4509 windowHandle->getInfo()->displayId);
4510 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004511 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 }
4514 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004515 return nullptr;
4516}
4517
chaviw98318de2021-05-19 16:45:23 -05004518sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004519 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4520 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521}
4522
chaviw98318de2021-05-19 16:45:23 -05004523bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004524 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4525 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004526 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004527 if (connection != nullptr && noInputChannel) {
4528 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4529 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4530 return false;
4531 }
4532
4533 if (connection == nullptr) {
4534 if (!noInputChannel) {
4535 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4536 }
4537 return false;
4538 }
4539 if (!connection->responsive) {
4540 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4541 return false;
4542 }
4543 return true;
4544}
4545
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004546std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4547 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004548 auto connectionIt = mConnectionsByToken.find(token);
4549 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004550 return nullptr;
4551 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004552 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004553}
4554
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004555void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004556 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4557 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004558 // Remove all handles on a display if there are no windows left.
4559 mWindowHandlesByDisplay.erase(displayId);
4560 return;
4561 }
4562
4563 // Since we compare the pointer of input window handles across window updates, we need
4564 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004565 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4566 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4567 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004568 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004569 }
4570
chaviw98318de2021-05-19 16:45:23 -05004571 std::vector<sp<WindowInfoHandle>> newHandles;
4572 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004573 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004574 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004575 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004576 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4577 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4578 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004579 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004580 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004581 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004582 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004583 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004584 }
4585
4586 if (info->displayId != displayId) {
4587 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4588 handle->getName().c_str(), displayId, info->displayId);
4589 continue;
4590 }
4591
Robert Carredd13602020-04-13 17:24:34 -07004592 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4593 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004594 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004595 oldHandle->updateFrom(handle);
4596 newHandles.push_back(oldHandle);
4597 } else {
4598 newHandles.push_back(handle);
4599 }
4600 }
4601
4602 // Insert or replace
4603 mWindowHandlesByDisplay[displayId] = newHandles;
4604}
4605
Arthur Hung72d8dc32020-03-28 00:48:39 +00004606void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004607 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004608 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004609 { // acquire lock
4610 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004611 for (const auto& [displayId, handles] : handlesPerDisplay) {
4612 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004613 }
4614 }
4615 // Wake up poll loop since it may need to make new input dispatching choices.
4616 mLooper->wake();
4617}
4618
Arthur Hungb92218b2018-08-14 12:00:21 +08004619/**
4620 * Called from InputManagerService, update window handle list by displayId that can receive input.
4621 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4622 * If set an empty list, remove all handles from the specific display.
4623 * For focused handle, check if need to change and send a cancel event to previous one.
4624 * For removed handle, check if need to send a cancel event if already in touch.
4625 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004626void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004627 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004628 if (DEBUG_FOCUS) {
4629 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004630 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004631 windowList += iwh->getName() + " ";
4632 }
4633 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004636 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004637 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004638 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004639 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004640 if (noInputWindow && window->getToken() != nullptr) {
4641 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4642 window->getName().c_str());
4643 window->releaseChannel();
4644 }
4645 }
4646
Arthur Hung72d8dc32020-03-28 00:48:39 +00004647 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004648 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004650 // Save the old windows' orientation by ID before it gets updated.
4651 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004652 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004653 oldWindowOrientations.emplace(handle->getId(),
4654 handle->getInfo()->transform.getOrientation());
4655 }
4656
chaviw98318de2021-05-19 16:45:23 -05004657 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004658
chaviw98318de2021-05-19 16:45:23 -05004659 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004660 if (mLastHoverWindowHandle &&
4661 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4662 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004663 mLastHoverWindowHandle = nullptr;
4664 }
4665
Vishnu Nairc519ff72021-01-21 08:23:08 -08004666 std::optional<FocusResolver::FocusChanges> changes =
4667 mFocusResolver.setInputWindows(displayId, windowHandles);
4668 if (changes) {
4669 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004672 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4673 mTouchStatesByDisplay.find(displayId);
4674 if (stateIt != mTouchStatesByDisplay.end()) {
4675 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004676 for (size_t i = 0; i < state.windows.size();) {
4677 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004678 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004679 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004680 ALOGD("Touched window was removed: %s in display %" PRId32,
4681 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004682 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004683 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004684 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4685 if (touchedInputChannel != nullptr) {
4686 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4687 "touched window was removed");
4688 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004689 // Since we are about to drop the touch, cancel the events for the wallpaper as
4690 // well.
4691 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4692 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4693 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4694 if (wallpaper != nullptr) {
4695 sp<Connection> wallpaperConnection =
4696 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004697 if (wallpaperConnection != nullptr) {
4698 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4699 options);
4700 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004701 }
4702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004704 state.windows.erase(state.windows.begin() + i);
4705 } else {
4706 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 }
4708 }
arthurhungb89ccb02020-12-30 16:19:01 +08004709
arthurhung6d4bed92021-03-17 11:59:33 +08004710 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004711 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004712 if (mDragState &&
4713 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004714 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004715 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004716 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004717 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004718
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004719 // Determine if the orientation of any of the input windows have changed, and cancel all
4720 // pointer events if necessary.
4721 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4722 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4723 if (newWindowHandle != nullptr &&
4724 newWindowHandle->getInfo()->transform.getOrientation() !=
4725 oldWindowOrientations[oldWindowHandle->getId()]) {
4726 std::shared_ptr<InputChannel> inputChannel =
4727 getInputChannelLocked(newWindowHandle->getToken());
4728 if (inputChannel != nullptr) {
4729 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4730 "touched window's orientation changed");
4731 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004732 }
4733 }
4734 }
4735
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 // Release information for windows that are no longer present.
4737 // This ensures that unused input channels are released promptly.
4738 // Otherwise, they might stick around until the window handle is destroyed
4739 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004740 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004741 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004742 if (DEBUG_FOCUS) {
4743 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004744 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004745 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004746 // To avoid making too many calls into the compat framework, only
4747 // check for window flags when windows are going away.
4748 // TODO(b/157929241) : delete this. This is only needed temporarily
4749 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004750 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004751 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4752 oldWindowHandle->getName().c_str());
4753 if (mCompatService != nullptr) {
4754 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4755 oldWindowHandle->getInfo()->ownerUid);
4756 }
4757 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004758 }
chaviw291d88a2019-02-14 10:33:58 -08004759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760}
4761
4762void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004763 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004764 if (DEBUG_FOCUS) {
4765 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4766 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4767 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004768 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004769 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004770 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 } // release lock
4772
4773 // Wake up poll loop since it may need to make new input dispatching choices.
4774 mLooper->wake();
4775}
4776
Vishnu Nair599f1412021-06-21 10:39:58 -07004777void InputDispatcher::setFocusedApplicationLocked(
4778 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4779 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4780 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4781
4782 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4783 return; // This application is already focused. No need to wake up or change anything.
4784 }
4785
4786 // Set the new application handle.
4787 if (inputApplicationHandle != nullptr) {
4788 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4789 } else {
4790 mFocusedApplicationHandlesByDisplay.erase(displayId);
4791 }
4792
4793 // No matter what the old focused application was, stop waiting on it because it is
4794 // no longer focused.
4795 resetNoFocusedWindowTimeoutLocked();
4796}
4797
Tiger Huang721e26f2018-07-24 22:26:19 +08004798/**
4799 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4800 * the display not specified.
4801 *
4802 * We track any unreleased events for each window. If a window loses the ability to receive the
4803 * released event, we will send a cancel event to it. So when the focused display is changed, we
4804 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4805 * display. The display-specified events won't be affected.
4806 */
4807void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004808 if (DEBUG_FOCUS) {
4809 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4810 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004811 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004812 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004813
4814 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004815 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004816 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004817 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004818 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004819 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004820 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004821 CancelationOptions
4822 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4823 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004824 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004825 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4826 }
4827 }
4828 mFocusedDisplayId = displayId;
4829
Chris Ye3c2d6f52020-08-09 10:39:48 -07004830 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004831 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004832 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004833
Vishnu Nairad321cd2020-08-20 16:40:21 -07004834 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004835 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004836 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004837 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004838 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004839 }
4840 }
4841 }
4842
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004843 if (DEBUG_FOCUS) {
4844 logDispatchStateLocked();
4845 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004846 } // release lock
4847
4848 // Wake up poll loop since it may need to make new input dispatching choices.
4849 mLooper->wake();
4850}
4851
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004853 if (DEBUG_FOCUS) {
4854 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856
4857 bool changed;
4858 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004859 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860
4861 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4862 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 }
4865
4866 if (mDispatchEnabled && !enabled) {
4867 resetAndDropEverythingLocked("dispatcher is being disabled");
4868 }
4869
4870 mDispatchEnabled = enabled;
4871 mDispatchFrozen = frozen;
4872 changed = true;
4873 } else {
4874 changed = false;
4875 }
4876
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004877 if (DEBUG_FOCUS) {
4878 logDispatchStateLocked();
4879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 } // release lock
4881
4882 if (changed) {
4883 // Wake up poll loop since it may need to make new input dispatching choices.
4884 mLooper->wake();
4885 }
4886}
4887
4888void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004889 if (DEBUG_FOCUS) {
4890 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892
4893 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004894 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895
4896 if (mInputFilterEnabled == enabled) {
4897 return;
4898 }
4899
4900 mInputFilterEnabled = enabled;
4901 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4902 } // release lock
4903
4904 // Wake up poll loop since there might be work to do to drop everything.
4905 mLooper->wake();
4906}
4907
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004908void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004909 bool needWake = false;
4910 {
4911 std::scoped_lock lock(mLock);
4912 if (mInTouchMode == inTouchMode) {
4913 return;
4914 }
4915 if (DEBUG_TOUCH_MODE) {
4916 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4917 toString(inTouchMode));
4918 // TODO(b/198487159): Also print the current last interacted apps.
4919 }
4920
4921 // TODO(b/198499018): Store touch mode per display.
4922 mInTouchMode = inTouchMode;
4923
4924 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4925 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4926 needWake = enqueueInboundEventLocked(std::move(entry));
4927 } // release lock
4928
4929 if (needWake) {
4930 mLooper->wake();
4931 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004932}
4933
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004934void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4935 if (opacity < 0 || opacity > 1) {
4936 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4937 return;
4938 }
4939
4940 std::scoped_lock lock(mLock);
4941 mMaximumObscuringOpacityForTouch = opacity;
4942}
4943
4944void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4945 std::scoped_lock lock(mLock);
4946 mBlockUntrustedTouchesMode = mode;
4947}
4948
Arthur Hungabbb9d82021-09-01 14:52:30 +00004949std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4950 const sp<IBinder>& token) {
4951 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4952 for (TouchedWindow& w : state.windows) {
4953 if (w.windowHandle->getToken() == token) {
4954 return std::make_pair(&state, &w);
4955 }
4956 }
4957 }
4958 return std::make_pair(nullptr, nullptr);
4959}
4960
arthurhungb89ccb02020-12-30 16:19:01 +08004961bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4962 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004963 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004964 if (DEBUG_FOCUS) {
4965 ALOGD("Trivial transfer to same window.");
4966 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004967 return true;
4968 }
4969
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004971 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
Arthur Hungabbb9d82021-09-01 14:52:30 +00004973 // Find the target touch state and touched window by fromToken.
4974 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4975 if (state == nullptr || touchedWindow == nullptr) {
4976 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 return false;
4978 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00004979
4980 const int32_t displayId = state->displayId;
4981 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4982 if (toWindowHandle == nullptr) {
4983 ALOGW("Cannot transfer focus because to window not found.");
4984 return false;
4985 }
4986
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004987 if (DEBUG_FOCUS) {
4988 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00004989 touchedWindow->windowHandle->getName().c_str(),
4990 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991 }
4992
Arthur Hungabbb9d82021-09-01 14:52:30 +00004993 // Erase old window.
4994 int32_t oldTargetFlags = touchedWindow->targetFlags;
4995 BitSet32 pointerIds = touchedWindow->pointerIds;
4996 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997
Arthur Hungabbb9d82021-09-01 14:52:30 +00004998 // Add new window.
4999 int32_t newTargetFlags = oldTargetFlags &
5000 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5001 InputTarget::FLAG_DISPATCH_AS_IS);
5002 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003
Arthur Hungabbb9d82021-09-01 14:52:30 +00005004 // Store the dragging window.
5005 if (isDragDrop) {
5006 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 }
5008
Arthur Hungabbb9d82021-09-01 14:52:30 +00005009 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005010 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5011 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005012 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005013 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005014 CancelationOptions
5015 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5016 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005018 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 }
5020
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005021 if (DEBUG_FOCUS) {
5022 logDispatchStateLocked();
5023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 } // release lock
5025
5026 // Wake up poll loop since it may need to make new input dispatching choices.
5027 mLooper->wake();
5028 return true;
5029}
5030
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005031// Binder call
5032bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5033 sp<IBinder> fromToken;
5034 { // acquire lock
5035 std::scoped_lock _l(mLock);
5036
Arthur Hungabbb9d82021-09-01 14:52:30 +00005037 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5038 [](const auto& pair) { return pair.second.windows.size() == 1; });
5039 if (it == mTouchStatesByDisplay.end()) {
5040 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5041 return false;
5042 }
5043 const int32_t displayId = it->first;
5044 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005045 if (toWindowHandle == nullptr) {
5046 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5047 return false;
5048 }
5049
Arthur Hungabbb9d82021-09-01 14:52:30 +00005050 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005051 const TouchedWindow& touchedWindow = state.windows[0];
5052 fromToken = touchedWindow.windowHandle->getToken();
5053 } // release lock
5054
5055 return transferTouchFocus(fromToken, destChannelToken);
5056}
5057
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005059 if (DEBUG_FOCUS) {
5060 ALOGD("Resetting and dropping all events (%s).", reason);
5061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062
5063 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5064 synthesizeCancelationEventsForAllConnectionsLocked(options);
5065
5066 resetKeyRepeatLocked();
5067 releasePendingEventLocked();
5068 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005069 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005070
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005071 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005072 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005074 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075}
5076
5077void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005078 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 dumpDispatchStateLocked(dump);
5080
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005081 std::istringstream stream(dump);
5082 std::string line;
5083
5084 while (std::getline(stream, line, '\n')) {
5085 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087}
5088
Prabir Pradhan99987712020-11-10 18:43:05 -08005089std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5090 std::string dump;
5091
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005092 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5093 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005094
5095 std::string windowName = "None";
5096 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005097 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005098 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5099 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5100 : "token has capture without window";
5101 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005102 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005103
5104 return dump;
5105}
5106
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005107void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005108 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5109 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5110 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005111 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112
Tiger Huang721e26f2018-07-24 22:26:19 +08005113 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5114 dump += StringPrintf(INDENT "FocusedApplications:\n");
5115 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5116 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005117 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005118 const std::chrono::duration timeout =
5119 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005120 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005121 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005122 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005125 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005127
Vishnu Nairc519ff72021-01-21 08:23:08 -08005128 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005129 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005131 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005132 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005133 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5134 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005135 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005136 state.displayId, toString(state.down), toString(state.split),
5137 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005138 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005139 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005140 for (size_t i = 0; i < state.windows.size(); i++) {
5141 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005142 dump += StringPrintf(INDENT4
5143 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5144 i, touchedWindow.windowHandle->getName().c_str(),
5145 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005146 }
5147 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005148 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 }
5151 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154
arthurhung6d4bed92021-03-17 11:59:33 +08005155 if (mDragState) {
5156 dump += StringPrintf(INDENT "DragState:\n");
5157 mDragState->dump(dump, INDENT2);
5158 }
5159
Arthur Hungb92218b2018-08-14 12:00:21 +08005160 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005161 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5162 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5163 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5164 const auto& displayInfo = it->second;
5165 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5166 displayInfo.logicalHeight);
5167 displayInfo.transform.dump(dump, "transform", INDENT4);
5168 } else {
5169 dump += INDENT2 "No DisplayInfo found!\n";
5170 }
5171
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005172 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005173 dump += INDENT2 "Windows:\n";
5174 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005175 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5176 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005178 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005179 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005180 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005181 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005182 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005183 "applicationInfo.name=%s, "
5184 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005185 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005186 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005187 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005188 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005189 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005190 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005191 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005192 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005193 windowInfo->frameLeft, windowInfo->frameTop,
5194 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005195 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005196 windowInfo->applicationInfo.name.c_str(),
5197 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005198 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005199 dump += StringPrintf(", inputFeatures=%s",
5200 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005201 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005202 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005203 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005204 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005205 millis(windowInfo->dispatchingTimeout),
5206 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005207 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005208 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005209 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005210 }
5211 } else {
5212 dump += INDENT2 "Windows: <none>\n";
5213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 }
5215 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005216 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 }
5218
Michael Wright3dd60e22019-03-27 22:06:44 +00005219 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005220 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005221 const std::vector<Monitor>& monitors = it.second;
5222 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5223 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005224 }
5225 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005226 const std::vector<Monitor>& monitors = it.second;
5227 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5228 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005231 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 }
5233
5234 nsecs_t currentTime = now();
5235
5236 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005237 if (!mRecentQueue.empty()) {
5238 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005239 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005240 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005241 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005242 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 }
5244 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005245 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
5247
5248 // Dump event currently being dispatched.
5249 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005250 dump += INDENT "PendingEvent:\n";
5251 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005252 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005253 dump += StringPrintf(", age=%" PRId64 "ms\n",
5254 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005256 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 }
5258
5259 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005260 if (!mInboundQueue.empty()) {
5261 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005262 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005263 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005264 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005265 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 }
5267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005268 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 }
5270
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005271 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005272 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005273 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5274 const KeyReplacement& replacement = pair.first;
5275 int32_t newKeyCode = pair.second;
5276 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005277 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005278 }
5279 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005280 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005281 }
5282
Prabir Pradhancef936d2021-07-21 16:17:52 +00005283 if (!mCommandQueue.empty()) {
5284 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5285 } else {
5286 dump += INDENT "CommandQueue: <empty>\n";
5287 }
5288
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005289 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005290 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005291 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005292 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005293 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005294 connection->inputChannel->getFd().get(),
5295 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005296 connection->getWindowName().c_str(),
5297 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005298 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005300 if (!connection->outboundQueue.empty()) {
5301 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5302 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005303 dump += dumpQueue(connection->outboundQueue, currentTime);
5304
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 }
5308
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005309 if (!connection->waitQueue.empty()) {
5310 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5311 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005312 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005314 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 }
5316 }
5317 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005318 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 }
5320
5321 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005322 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5323 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005325 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 }
5327
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005328 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005329 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5330 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5331 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005332 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005333 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334}
5335
Michael Wright3dd60e22019-03-27 22:06:44 +00005336void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5337 const size_t numMonitors = monitors.size();
5338 for (size_t i = 0; i < numMonitors; i++) {
5339 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005340 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005341 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5342 dump += "\n";
5343 }
5344}
5345
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005346class LooperEventCallback : public LooperCallback {
5347public:
5348 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5349 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5350
5351private:
5352 std::function<int(int events)> mCallback;
5353};
5354
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005355Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005356 if (DEBUG_CHANNEL_CREATION) {
5357 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005360 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005361 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005362 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005363
5364 if (result) {
5365 return base::Error(result) << "Failed to open input channel pair with name " << name;
5366 }
5367
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005369 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005370 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005371 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005372 sp<Connection> connection =
5373 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005375 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5376 ALOGE("Created a new connection, but the token %p is already known", token.get());
5377 }
5378 mConnectionsByToken.emplace(token, connection);
5379
5380 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5381 this, std::placeholders::_1, token);
5382
5383 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 } // release lock
5385
5386 // Wake the looper because some connections have changed.
5387 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005388 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389}
5390
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005391Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5392 bool isGestureMonitor,
5393 const std::string& name,
5394 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005395 std::shared_ptr<InputChannel> serverChannel;
5396 std::unique_ptr<InputChannel> clientChannel;
5397 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5398 if (result) {
5399 return base::Error(result) << "Failed to open input channel pair with name " << name;
5400 }
5401
Michael Wright3dd60e22019-03-27 22:06:44 +00005402 { // acquire lock
5403 std::scoped_lock _l(mLock);
5404
5405 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005406 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5407 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005408 }
5409
Garfield Tan15601662020-09-22 15:32:38 -07005410 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005411 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005412 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005413
5414 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5415 ALOGE("Created a new connection, but the token %p is already known", token.get());
5416 }
5417 mConnectionsByToken.emplace(token, connection);
5418 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5419 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005420
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005421 auto& monitorsByDisplay =
5422 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005423 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005424
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005425 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005426 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5427 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005428 }
Garfield Tan15601662020-09-22 15:32:38 -07005429
Michael Wright3dd60e22019-03-27 22:06:44 +00005430 // Wake the looper because some connections have changed.
5431 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005432 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005433}
5434
Garfield Tan15601662020-09-22 15:32:38 -07005435status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005437 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438
Garfield Tan15601662020-09-22 15:32:38 -07005439 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 if (status) {
5441 return status;
5442 }
5443 } // release lock
5444
5445 // Wake the poll loop because removing the connection may have changed the current
5446 // synchronization state.
5447 mLooper->wake();
5448 return OK;
5449}
5450
Garfield Tan15601662020-09-22 15:32:38 -07005451status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5452 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005453 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005454 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005455 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 return BAD_VALUE;
5457 }
5458
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005459 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005460
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005462 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 }
5464
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005465 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466
5467 nsecs_t currentTime = now();
5468 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5469
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005470 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 return OK;
5472}
5473
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005474void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5475 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5476 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005477}
5478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005479void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005480 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005481 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005482 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005483 std::vector<Monitor>& monitors = it->second;
5484 const size_t numMonitors = monitors.size();
5485 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005486 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005487 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5488 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005489 monitors.erase(monitors.begin() + i);
5490 break;
5491 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005492 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005493 if (monitors.empty()) {
5494 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005495 } else {
5496 ++it;
5497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 }
5499}
5500
Michael Wright3dd60e22019-03-27 22:06:44 +00005501status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5502 { // acquire lock
5503 std::scoped_lock _l(mLock);
5504 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5505
5506 if (!foundDisplayId) {
5507 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5508 return BAD_VALUE;
5509 }
5510 int32_t displayId = foundDisplayId.value();
5511
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005512 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5513 mTouchStatesByDisplay.find(displayId);
5514 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005515 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5516 return BAD_VALUE;
5517 }
5518
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005519 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005520 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005521 std::optional<int32_t> foundDeviceId;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07005522 for (const auto& monitor : state.gestureMonitors) {
5523 if (monitor.inputChannel->getConnectionToken() == token) {
5524 requestingChannel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005525 foundDeviceId = state.deviceId;
5526 }
5527 }
5528 if (!foundDeviceId || !state.down) {
5529 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005530 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005531 return BAD_VALUE;
5532 }
5533 int32_t deviceId = foundDeviceId.value();
5534
5535 // Send cancel events to all the input channels we're stealing from.
5536 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005537 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005538 options.deviceId = deviceId;
5539 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005540 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005541 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005542 std::shared_ptr<InputChannel> channel =
5543 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005544 if (channel != nullptr) {
5545 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005546 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005547 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005548 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005549 canceledWindows += "]";
5550 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5551 canceledWindows.c_str());
5552
Michael Wright3dd60e22019-03-27 22:06:44 +00005553 // Then clear the current touch state so we stop dispatching to them as well.
Arthur Hungfbfa5722021-11-16 02:45:54 +00005554 state.split = false;
Michael Wright3dd60e22019-03-27 22:06:44 +00005555 state.filterNonMonitors();
5556 }
5557 return OK;
5558}
5559
Prabir Pradhan99987712020-11-10 18:43:05 -08005560void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5561 { // acquire lock
5562 std::scoped_lock _l(mLock);
5563 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005564 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005565 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5566 windowHandle != nullptr ? windowHandle->getName().c_str()
5567 : "token without window");
5568 }
5569
Vishnu Nairc519ff72021-01-21 08:23:08 -08005570 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005571 if (focusedToken != windowToken) {
5572 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5573 enabled ? "enable" : "disable");
5574 return;
5575 }
5576
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005577 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005578 ALOGW("Ignoring request to %s Pointer Capture: "
5579 "window has %s requested pointer capture.",
5580 enabled ? "enable" : "disable", enabled ? "already" : "not");
5581 return;
5582 }
5583
Prabir Pradhan99987712020-11-10 18:43:05 -08005584 setPointerCaptureLocked(enabled);
5585 } // release lock
5586
5587 // Wake the thread to process command entries.
5588 mLooper->wake();
5589}
5590
Michael Wright3dd60e22019-03-27 22:06:44 +00005591std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5592 const sp<IBinder>& token) {
5593 for (const auto& it : mGestureMonitorsByDisplay) {
5594 const std::vector<Monitor>& monitors = it.second;
5595 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005596 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005597 return it.first;
5598 }
5599 }
5600 }
5601 return std::nullopt;
5602}
5603
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005604std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5605 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5606 if (gesturePid.has_value()) {
5607 return gesturePid;
5608 }
5609 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5610}
5611
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005612sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005613 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005614 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005615 }
5616
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005617 for (const auto& [token, connection] : mConnectionsByToken) {
5618 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005619 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 }
5621 }
Robert Carr4e670e52018-08-15 13:26:12 -07005622
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005623 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624}
5625
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005626std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5627 sp<Connection> connection = getConnectionLocked(connectionToken);
5628 if (connection == nullptr) {
5629 return "<nullptr>";
5630 }
5631 return connection->getInputChannelName();
5632}
5633
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005634void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005635 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005636 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005637}
5638
Prabir Pradhancef936d2021-07-21 16:17:52 +00005639void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5640 const sp<Connection>& connection, uint32_t seq,
5641 bool handled, nsecs_t consumeTime) {
5642 // Handle post-event policy actions.
5643 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5644 if (dispatchEntryIt == connection->waitQueue.end()) {
5645 return;
5646 }
5647 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5648 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5649 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5650 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5651 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5652 }
5653 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5654 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5655 connection->inputChannel->getConnectionToken(),
5656 dispatchEntry->deliveryTime, consumeTime, finishTime);
5657 }
5658
5659 bool restartEvent;
5660 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5661 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5662 restartEvent =
5663 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5664 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5665 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5666 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5667 handled);
5668 } else {
5669 restartEvent = false;
5670 }
5671
5672 // Dequeue the event and start the next cycle.
5673 // Because the lock might have been released, it is possible that the
5674 // contents of the wait queue to have been drained, so we need to double-check
5675 // a few things.
5676 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5677 if (dispatchEntryIt != connection->waitQueue.end()) {
5678 dispatchEntry = *dispatchEntryIt;
5679 connection->waitQueue.erase(dispatchEntryIt);
5680 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5681 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5682 if (!connection->responsive) {
5683 connection->responsive = isConnectionResponsive(*connection);
5684 if (connection->responsive) {
5685 // The connection was unresponsive, and now it's responsive.
5686 processConnectionResponsiveLocked(*connection);
5687 }
5688 }
5689 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005690 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005691 connection->outboundQueue.push_front(dispatchEntry);
5692 traceOutboundQueueLength(*connection);
5693 } else {
5694 releaseDispatchEntry(dispatchEntry);
5695 }
5696 }
5697
5698 // Start the next dispatch cycle for this connection.
5699 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700}
5701
Prabir Pradhancef936d2021-07-21 16:17:52 +00005702void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5703 const sp<IBinder>& newToken) {
5704 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5705 scoped_unlock unlock(mLock);
5706 mPolicy->notifyFocusChanged(oldToken, newToken);
5707 };
5708 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709}
5710
Prabir Pradhancef936d2021-07-21 16:17:52 +00005711void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5712 auto command = [this, token, x, y]() REQUIRES(mLock) {
5713 scoped_unlock unlock(mLock);
5714 mPolicy->notifyDropWindow(token, x, y);
5715 };
5716 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005717}
5718
Prabir Pradhancef936d2021-07-21 16:17:52 +00005719void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5720 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5721 scoped_unlock unlock(mLock);
5722 mPolicy->notifyUntrustedTouch(obscuringPackage);
5723 };
5724 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005725}
5726
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005727void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5728 if (connection == nullptr) {
5729 LOG_ALWAYS_FATAL("Caller must check for nullness");
5730 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005731 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5732 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005733 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005734 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005735 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005736 return;
5737 }
5738 /**
5739 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5740 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5741 * has changed. This could cause newer entries to time out before the already dispatched
5742 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5743 * processes the events linearly. So providing information about the oldest entry seems to be
5744 * most useful.
5745 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005746 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005747 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5748 std::string reason =
5749 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005750 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005751 ns2ms(currentWait),
5752 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005753 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005754 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005755
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005756 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5757
5758 // Stop waking up for events on this connection, it is already unresponsive
5759 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005760}
5761
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005762void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5763 std::string reason =
5764 StringPrintf("%s does not have a focused window", application->getName().c_str());
5765 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005766
Prabir Pradhancef936d2021-07-21 16:17:52 +00005767 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5768 scoped_unlock unlock(mLock);
5769 mPolicy->notifyNoFocusedWindowAnr(application);
5770 };
5771 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005772}
5773
chaviw98318de2021-05-19 16:45:23 -05005774void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005775 const std::string& reason) {
5776 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5777 updateLastAnrStateLocked(windowLabel, reason);
5778}
5779
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005780void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5781 const std::string& reason) {
5782 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005783 updateLastAnrStateLocked(windowLabel, reason);
5784}
5785
5786void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5787 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005789 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 struct tm tm;
5791 localtime_r(&t, &tm);
5792 char timestr[64];
5793 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005794 mLastAnrState.clear();
5795 mLastAnrState += INDENT "ANR:\n";
5796 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005797 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5798 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005799 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800}
5801
Prabir Pradhancef936d2021-07-21 16:17:52 +00005802void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5803 KeyEntry& entry) {
5804 const KeyEvent event = createKeyEvent(entry);
5805 nsecs_t delay = 0;
5806 { // release lock
5807 scoped_unlock unlock(mLock);
5808 android::base::Timer t;
5809 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5810 entry.policyFlags);
5811 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5812 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5813 std::to_string(t.duration().count()).c_str());
5814 }
5815 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816
5817 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005818 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005819 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005820 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005822 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5823 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825}
5826
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005827void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005828 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5829 scoped_unlock unlock(mLock);
5830 mPolicy->notifyMonitorUnresponsive(pid, reason);
5831 };
5832 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005833}
5834
Prabir Pradhancef936d2021-07-21 16:17:52 +00005835void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005836 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005837 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5838 scoped_unlock unlock(mLock);
5839 mPolicy->notifyWindowUnresponsive(token, reason);
5840 };
5841 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005842}
5843
5844void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005845 auto command = [this, pid]() REQUIRES(mLock) {
5846 scoped_unlock unlock(mLock);
5847 mPolicy->notifyMonitorResponsive(pid);
5848 };
5849 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005850}
5851
Prabir Pradhancef936d2021-07-21 16:17:52 +00005852void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5853 auto command = [this, connectionToken]() REQUIRES(mLock) {
5854 scoped_unlock unlock(mLock);
5855 mPolicy->notifyWindowResponsive(connectionToken);
5856 };
5857 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005858}
5859
5860/**
5861 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5862 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5863 * command entry to the command queue.
5864 */
5865void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5866 std::string reason) {
5867 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5868 if (connection.monitor) {
5869 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5870 reason.c_str());
5871 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5872 if (!pid.has_value()) {
5873 ALOGE("Could not find unresponsive monitor for connection %s",
5874 connection.inputChannel->getName().c_str());
5875 return;
5876 }
5877 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5878 return;
5879 }
5880 // If not a monitor, must be a window
5881 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5882 reason.c_str());
5883 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5884}
5885
5886/**
5887 * Tell the policy that a connection has become responsive so that it can stop ANR.
5888 */
5889void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5890 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5891 if (connection.monitor) {
5892 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5893 if (!pid.has_value()) {
5894 ALOGE("Could not find responsive monitor for connection %s",
5895 connection.inputChannel->getName().c_str());
5896 return;
5897 }
5898 sendMonitorResponsiveCommandLocked(pid.value());
5899 return;
5900 }
5901 // If not a monitor, must be a window
5902 sendWindowResponsiveCommandLocked(connectionToken);
5903}
5904
Prabir Pradhancef936d2021-07-21 16:17:52 +00005905bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005906 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005907 KeyEntry& keyEntry, bool handled) {
5908 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005909 if (!handled) {
5910 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005912 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913 return false;
5914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005916 // Get the fallback key state.
5917 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005918 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005919 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005920 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005921 connection->inputState.removeFallbackKey(originalKeyCode);
5922 }
5923
5924 if (handled || !dispatchEntry->hasForegroundTarget()) {
5925 // If the application handles the original key for which we previously
5926 // generated a fallback or if the window is not a foreground window,
5927 // then cancel the associated fallback key, if any.
5928 if (fallbackKeyCode != -1) {
5929 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005930 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5931 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5932 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5933 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5934 keyEntry.policyFlags);
5935 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005936 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005937 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938
5939 mLock.unlock();
5940
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005941 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005942 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943
5944 mLock.lock();
5945
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005946 // Cancel the fallback key.
5947 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005949 "application handled the original non-fallback key "
5950 "or is no longer a foreground target, "
5951 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 options.keyCode = fallbackKeyCode;
5953 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955 connection->inputState.removeFallbackKey(originalKeyCode);
5956 }
5957 } else {
5958 // If the application did not handle a non-fallback key, first check
5959 // that we are in a good state to perform unhandled key event processing
5960 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005961 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005962 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005963 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5964 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5965 "since this is not an initial down. "
5966 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5967 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5968 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005969 return false;
5970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005972 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005973 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5974 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5975 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5976 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5977 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005978 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005979
5980 mLock.unlock();
5981
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005982 bool fallback =
5983 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005984 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985
5986 mLock.lock();
5987
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005988 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005989 connection->inputState.removeFallbackKey(originalKeyCode);
5990 return false;
5991 }
5992
5993 // Latch the fallback keycode for this key on an initial down.
5994 // The fallback keycode cannot change at any other point in the lifecycle.
5995 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005996 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005997 fallbackKeyCode = event.getKeyCode();
5998 } else {
5999 fallbackKeyCode = AKEYCODE_UNKNOWN;
6000 }
6001 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6002 }
6003
6004 ALOG_ASSERT(fallbackKeyCode != -1);
6005
6006 // Cancel the fallback key if the policy decides not to send it anymore.
6007 // We will continue to dispatch the key to the policy but we will no
6008 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006009 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6010 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006011 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6012 if (fallback) {
6013 ALOGD("Unhandled key event: Policy requested to send key %d"
6014 "as a fallback for %d, but on the DOWN it had requested "
6015 "to send %d instead. Fallback canceled.",
6016 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6017 } else {
6018 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6019 "but on the DOWN it had requested to send %d. "
6020 "Fallback canceled.",
6021 originalKeyCode, fallbackKeyCode);
6022 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006023 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006024
6025 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6026 "canceling fallback, policy no longer desires it");
6027 options.keyCode = fallbackKeyCode;
6028 synthesizeCancelationEventsForConnectionLocked(connection, options);
6029
6030 fallback = false;
6031 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006033 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034 }
6035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006037 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6038 {
6039 std::string msg;
6040 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6041 connection->inputState.getFallbackKeys();
6042 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6043 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6044 }
6045 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6046 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006048 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006049
6050 if (fallback) {
6051 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 keyEntry.eventTime = event.getEventTime();
6053 keyEntry.deviceId = event.getDeviceId();
6054 keyEntry.source = event.getSource();
6055 keyEntry.displayId = event.getDisplayId();
6056 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6057 keyEntry.keyCode = fallbackKeyCode;
6058 keyEntry.scanCode = event.getScanCode();
6059 keyEntry.metaState = event.getMetaState();
6060 keyEntry.repeatCount = event.getRepeatCount();
6061 keyEntry.downTime = event.getDownTime();
6062 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006064 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6065 ALOGD("Unhandled key event: Dispatching fallback key. "
6066 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6067 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6068 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 return true; // restart the event
6070 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006071 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6072 ALOGD("Unhandled key event: No fallback key.");
6073 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006074
6075 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006076 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006077 }
6078 }
6079 return false;
6080}
6081
Prabir Pradhancef936d2021-07-21 16:17:52 +00006082bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006083 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006084 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085 return false;
6086}
6087
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088void InputDispatcher::traceInboundQueueLengthLocked() {
6089 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006090 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 }
6092}
6093
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006094void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 if (ATRACE_ENABLED()) {
6096 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006097 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6098 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 }
6100}
6101
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006102void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 if (ATRACE_ENABLED()) {
6104 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006105 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6106 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 }
6108}
6109
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006110void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006111 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006113 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114 dumpDispatchStateLocked(dump);
6115
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006116 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006117 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006118 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 }
6120}
6121
6122void InputDispatcher::monitor() {
6123 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006124 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006125 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006126 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006127}
6128
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006129/**
6130 * Wake up the dispatcher and wait until it processes all events and commands.
6131 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6132 * this method can be safely called from any thread, as long as you've ensured that
6133 * the work you are interested in completing has already been queued.
6134 */
6135bool InputDispatcher::waitForIdle() {
6136 /**
6137 * Timeout should represent the longest possible time that a device might spend processing
6138 * events and commands.
6139 */
6140 constexpr std::chrono::duration TIMEOUT = 100ms;
6141 std::unique_lock lock(mLock);
6142 mLooper->wake();
6143 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6144 return result == std::cv_status::no_timeout;
6145}
6146
Vishnu Naire798b472020-07-23 13:52:21 -07006147/**
6148 * Sets focus to the window identified by the token. This must be called
6149 * after updating any input window handles.
6150 *
6151 * Params:
6152 * request.token - input channel token used to identify the window that should gain focus.
6153 * request.focusedToken - the token that the caller expects currently to be focused. If the
6154 * specified token does not match the currently focused window, this request will be dropped.
6155 * If the specified focused token matches the currently focused window, the call will succeed.
6156 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6157 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6158 * when requesting the focus change. This determines which request gets
6159 * precedence if there is a focus change request from another source such as pointer down.
6160 */
Vishnu Nair958da932020-08-21 17:12:37 -07006161void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6162 { // acquire lock
6163 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006164 std::optional<FocusResolver::FocusChanges> changes =
6165 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6166 if (changes) {
6167 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006168 }
6169 } // release lock
6170 // Wake up poll loop since it may need to make new input dispatching choices.
6171 mLooper->wake();
6172}
6173
Vishnu Nairc519ff72021-01-21 08:23:08 -08006174void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6175 if (changes.oldFocus) {
6176 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006177 if (focusedInputChannel) {
6178 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6179 "focus left window");
6180 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006181 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006182 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006183 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006184 if (changes.newFocus) {
6185 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006186 }
6187
Prabir Pradhan99987712020-11-10 18:43:05 -08006188 // If a window has pointer capture, then it must have focus. We need to ensure that this
6189 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6190 // If the window loses focus before it loses pointer capture, then the window can be in a state
6191 // where it has pointer capture but not focus, violating the contract. Therefore we must
6192 // dispatch the pointer capture event before the focus event. Since focus events are added to
6193 // the front of the queue (above), we add the pointer capture event to the front of the queue
6194 // after the focus events are added. This ensures the pointer capture event ends up at the
6195 // front.
6196 disablePointerCaptureForcedLocked();
6197
Vishnu Nairc519ff72021-01-21 08:23:08 -08006198 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006199 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006200 }
6201}
Vishnu Nair958da932020-08-21 17:12:37 -07006202
Prabir Pradhan99987712020-11-10 18:43:05 -08006203void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006204 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006205 return;
6206 }
6207
6208 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6209
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006210 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006211 setPointerCaptureLocked(false);
6212 }
6213
6214 if (!mWindowTokenWithPointerCapture) {
6215 // No need to send capture changes because no window has capture.
6216 return;
6217 }
6218
6219 if (mPendingEvent != nullptr) {
6220 // Move the pending event to the front of the queue. This will give the chance
6221 // for the pending event to be dropped if it is a captured event.
6222 mInboundQueue.push_front(mPendingEvent);
6223 mPendingEvent = nullptr;
6224 }
6225
6226 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006227 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006228 mInboundQueue.push_front(std::move(entry));
6229}
6230
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006231void InputDispatcher::setPointerCaptureLocked(bool enable) {
6232 mCurrentPointerCaptureRequest.enable = enable;
6233 mCurrentPointerCaptureRequest.seq++;
6234 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006235 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006236 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006237 };
6238 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006239}
6240
Vishnu Nair599f1412021-06-21 10:39:58 -07006241void InputDispatcher::displayRemoved(int32_t displayId) {
6242 { // acquire lock
6243 std::scoped_lock _l(mLock);
6244 // Set an empty list to remove all handles from the specific display.
6245 setInputWindowsLocked(/* window handles */ {}, displayId);
6246 setFocusedApplicationLocked(displayId, nullptr);
6247 // Call focus resolver to clean up stale requests. This must be called after input windows
6248 // have been removed for the removed display.
6249 mFocusResolver.displayRemoved(displayId);
6250 } // release lock
6251
6252 // Wake up poll loop since it may need to make new input dispatching choices.
6253 mLooper->wake();
6254}
6255
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006256void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6257 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006258 // The listener sends the windows as a flattened array. Separate the windows by display for
6259 // more convenient parsing.
6260 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006261 for (const auto& info : windowInfos) {
6262 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6263 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6264 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006265
6266 { // acquire lock
6267 std::scoped_lock _l(mLock);
6268 mDisplayInfos.clear();
6269 for (const auto& displayInfo : displayInfos) {
6270 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6271 }
6272
6273 for (const auto& [displayId, handles] : handlesPerDisplay) {
6274 setInputWindowsLocked(handles, displayId);
6275 }
6276 }
6277 // Wake up poll loop since it may need to make new input dispatching choices.
6278 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006279}
6280
Vishnu Nair062a8672021-09-03 16:07:44 -07006281bool InputDispatcher::shouldDropInput(
6282 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6283 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6284 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6285 isWindowObscuredLocked(windowHandle))) {
6286 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6287 "%" PRId32 ".",
6288 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6289 windowHandle->getInfo()->inputFeatures.string().c_str(),
6290 windowHandle->getInfo()->displayId);
6291 return true;
6292 }
6293 return false;
6294}
6295
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006296void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6297 const std::vector<gui::WindowInfo>& windowInfos,
6298 const std::vector<DisplayInfo>& displayInfos) {
6299 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6300}
6301
Arthur Hungdfd528e2021-12-08 13:23:04 +00006302void InputDispatcher::cancelCurrentTouch() {
6303 {
6304 std::scoped_lock _l(mLock);
6305 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6306 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6307 "cancel current touch");
6308 synthesizeCancelationEventsForAllConnectionsLocked(options);
6309
6310 mTouchStatesByDisplay.clear();
6311 mLastHoverWindowHandle.clear();
6312 }
6313 // Wake up poll loop since there might be work to do.
6314 mLooper->wake();
6315}
6316
Garfield Tane84e6f92019-08-29 17:28:41 -07006317} // namespace android::inputdispatcher