blob: bfdd22c3dfca756144ce133d8ebb4bb832351947 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000031#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010033#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
Michael Wright44753b12020-07-08 13:48:11 +010036#include <cerrno>
37#include <cinttypes>
38#include <climits>
39#include <cstddef>
40#include <ctime>
41#include <queue>
42#include <sstream>
43
44#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070045#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010046
Michael Wrightd02c5b62014-02-10 15:10:22 -080047#define INDENT " "
48#define INDENT2 " "
49#define INDENT3 " "
50#define INDENT4 " "
51
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000053using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080054using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070055using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050056using android::gui::FocusRequest;
57using android::gui::TouchOcclusionMode;
58using android::gui::WindowInfo;
59using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100061using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::InputEventInjectionResult;
63using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Garfield Tane84e6f92019-08-29 17:28:41 -070065namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Prabir Pradhancef936d2021-07-21 16:17:52 +000067namespace {
68
Siarhei Vishniakou63138b62022-03-03 11:33:19 -080069/**
70 * Log detailed debug messages about each inbound event notification to the dispatcher.
71 * Enable this via "adb shell setprop log.tag.InputDispatcherInboundEvent DEBUG" (requires restart)
72 */
73const bool DEBUG_INBOUND_EVENT_DETAILS =
74 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "InboundEvent", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +000075
Siarhei Vishniakou63138b62022-03-03 11:33:19 -080076/**
77 * Log detailed debug messages about each outbound event processed by the dispatcher.
78 * Enable this via "adb shell setprop log.tag.InputDispatcherOutboundEvent DEBUG" (requires restart)
79 */
80const bool DEBUG_OUTBOUND_EVENT_DETAILS =
81 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "OutboundEvent", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +000082
Siarhei Vishniakou63138b62022-03-03 11:33:19 -080083/**
84 * Log debug messages about the dispatch cycle.
85 * Enable this via "adb shell setprop log.tag.InputDispatcherDispatchCycle DEBUG" (requires restart)
86 */
87const bool DEBUG_DISPATCH_CYCLE =
88 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "DispatchCycle", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +000089
Siarhei Vishniakou63138b62022-03-03 11:33:19 -080090/**
91 * Log debug messages about channel creation
92 * Enable this via "adb shell setprop log.tag.InputDispatcherChannelCreation DEBUG" (requires
93 * restart)
94 */
95const bool DEBUG_CHANNEL_CREATION =
96 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "ChannelCreation", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +000097
Siarhei Vishniakou63138b62022-03-03 11:33:19 -080098/**
99 * Log debug messages about input event injection.
100 * Enable this via "adb shell setprop log.tag.InputDispatcherInjection DEBUG" (requires restart)
101 */
102const bool DEBUG_INJECTION =
103 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Injection", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000104
Siarhei Vishniakou63138b62022-03-03 11:33:19 -0800105/**
106 * Log debug messages about input focus tracking.
107 * Enable this via "adb shell setprop log.tag.InputDispatcherFocus DEBUG" (requires restart)
108 */
109const bool DEBUG_FOCUS =
110 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Focus", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000111
Siarhei Vishniakou63138b62022-03-03 11:33:19 -0800112/**
113 * Log debug messages about touch mode event
114 * Enable this via "adb shell setprop log.tag.InputDispatcherTouchMode DEBUG" (requires restart)
115 */
116const bool DEBUG_TOUCH_MODE =
117 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "TouchMode", ANDROID_LOG_INFO);
Antonio Kantekf16f2832021-09-28 04:39:20 +0000118
Siarhei Vishniakou63138b62022-03-03 11:33:19 -0800119/**
120 * Log debug messages about touch occlusion
121 * Enable this via "adb shell setprop log.tag.InputDispatcherTouchOcclusion DEBUG" (requires
122 * restart)
123 */
124const bool DEBUG_TOUCH_OCCLUSION =
125 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "TouchOcclusion", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000126
Siarhei Vishniakou63138b62022-03-03 11:33:19 -0800127/**
128 * Log debug messages about the app switch latency optimization.
129 * Enable this via "adb shell setprop log.tag.InputDispatcherAppSwitch DEBUG" (requires restart)
130 */
131const bool DEBUG_APP_SWITCH =
132 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "AppSwitch", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133
Siarhei Vishniakou63138b62022-03-03 11:33:19 -0800134/**
135 * Log debug messages about hover events.
136 * Enable this via "adb shell setprop log.tag.InputDispatcherHover DEBUG" (requires restart)
137 */
138const bool DEBUG_HOVER =
139 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Hover", ANDROID_LOG_INFO);
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000140
Prabir Pradhancef936d2021-07-21 16:17:52 +0000141// Temporarily releases a held mutex for the lifetime of the instance.
142// Named to match std::scoped_lock
143class scoped_unlock {
144public:
145 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
146 ~scoped_unlock() { mMutex.lock(); }
147
148private:
149 std::mutex& mMutex;
150};
151
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152// Default input dispatching timeout if there is no focused application or paused window
153// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800154const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
155 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
156 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157
158// Amount of time to allow for all pending events to be processed when an app switch
159// key is on the way. This is used to preempt input dispatch and drop input events
160// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000161constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162
163// Amount of time to allow for an event to be dispatched (measured since its eventTime)
164// before considering it stale and dropping it.
Vadim Tryshev78548252022-01-27 19:32:46 +0000165const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL // 10sec
166 * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168// 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 +0000169constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
170
171// Log a warning when an interception call takes longer than this to process.
172constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700174// Additional key latency in case a connection is still processing some motion events.
175// This will help with the case when a user touched a button that opens a new window,
176// and gives us the chance to dispatch the key to this new window.
177constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
178
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000180constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
181
Antonio Kantekea47acb2021-12-23 12:41:25 -0800182// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000183constexpr int LOGTAG_INPUT_INTERACTION = 62000;
184constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000185constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000186
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000187inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 return systemTime(SYSTEM_TIME_MONOTONIC);
189}
190
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000191inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 return value ? "true" : "false";
193}
194
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000195inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000196 if (binder == nullptr) {
197 return "<null>";
198 }
199 return StringPrintf("%p", binder.get());
200}
201
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000202inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700203 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
204 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700209 case AKEY_EVENT_ACTION_DOWN:
210 case AKEY_EVENT_ACTION_UP:
211 return true;
212 default:
213 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
215}
216
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000217bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700218 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 ALOGE("Key event has invalid action code 0x%x", action);
220 return false;
221 }
222 return true;
223}
224
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000225bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700227 case AMOTION_EVENT_ACTION_DOWN:
228 case AMOTION_EVENT_ACTION_UP:
229 case AMOTION_EVENT_ACTION_CANCEL:
230 case AMOTION_EVENT_ACTION_MOVE:
231 case AMOTION_EVENT_ACTION_OUTSIDE:
232 case AMOTION_EVENT_ACTION_HOVER_ENTER:
233 case AMOTION_EVENT_ACTION_HOVER_MOVE:
234 case AMOTION_EVENT_ACTION_HOVER_EXIT:
235 case AMOTION_EVENT_ACTION_SCROLL:
236 return true;
237 case AMOTION_EVENT_ACTION_POINTER_DOWN:
238 case AMOTION_EVENT_ACTION_POINTER_UP: {
239 int32_t index = getMotionEventActionPointerIndex(action);
240 return index >= 0 && index < pointerCount;
241 }
242 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
243 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
244 return actionButton != 0;
245 default:
246 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 }
248}
249
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000250int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500251 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
252}
253
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000254bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
255 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700256 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 ALOGE("Motion event has invalid action code 0x%x", action);
258 return false;
259 }
260 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800261 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700262 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 return false;
264 }
265 BitSet32 pointerIdBits;
266 for (size_t i = 0; i < pointerCount; i++) {
267 int32_t id = pointerProperties[i].id;
268 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700269 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
270 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 return false;
272 }
273 if (pointerIdBits.hasBit(id)) {
274 ALOGE("Motion event has duplicate pointer id %d", id);
275 return false;
276 }
277 pointerIdBits.markBit(id);
278 }
279 return true;
280}
281
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000282std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000284 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285 }
286
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000287 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 bool first = true;
289 Region::const_iterator cur = region.begin();
290 Region::const_iterator const tail = region.end();
291 while (cur != tail) {
292 if (first) {
293 first = false;
294 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800295 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800297 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800298 cur++;
299 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000300 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301}
302
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000303std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500304 constexpr size_t maxEntries = 50; // max events to print
305 constexpr size_t skipBegin = maxEntries / 2;
306 const size_t skipEnd = queue.size() - maxEntries / 2;
307 // skip from maxEntries / 2 ... size() - maxEntries/2
308 // only print from 0 .. skipBegin and then from skipEnd .. size()
309
310 std::string dump;
311 for (size_t i = 0; i < queue.size(); i++) {
312 const DispatchEntry& entry = *queue[i];
313 if (i >= skipBegin && i < skipEnd) {
314 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
315 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
316 continue;
317 }
318 dump.append(INDENT4);
319 dump += entry.eventEntry->getDescription();
320 dump += StringPrintf(", seq=%" PRIu32
321 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
322 entry.seq, entry.targetFlags, entry.resolvedAction,
323 ns2ms(currentTime - entry.eventEntry->eventTime));
324 if (entry.deliveryTime != 0) {
325 // This entry was delivered, so add information on how long we've been waiting
326 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
327 }
328 dump.append("\n");
329 }
330 return dump;
331}
332
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700333/**
334 * Find the entry in std::unordered_map by key, and return it.
335 * If the entry is not found, return a default constructed entry.
336 *
337 * Useful when the entries are vectors, since an empty vector will be returned
338 * if the entry is not found.
339 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
340 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700341template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000342V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700343 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700344 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800345}
346
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000347bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700348 if (first == second) {
349 return true;
350 }
351
352 if (first == nullptr || second == nullptr) {
353 return false;
354 }
355
356 return first->getToken() == second->getToken();
357}
358
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000359bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000360 if (first == nullptr || second == nullptr) {
361 return false;
362 }
363 return first->applicationInfo.token != nullptr &&
364 first->applicationInfo.token == second->applicationInfo.token;
365}
366
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000367bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800368 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
369}
370
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000371std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
372 std::shared_ptr<EventEntry> eventEntry,
373 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700374 if (inputTarget.useDefaultPointerTransform()) {
375 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700376 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700377 inputTarget.displayTransform,
378 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 }
380
381 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
382 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
383
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700384 std::vector<PointerCoords> pointerCoords;
385 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386
387 // Use the first pointer information to normalize all other pointers. This could be any pointer
388 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700389 // uses the transform for the normalized pointer.
390 const ui::Transform& firstPointerTransform =
391 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
392 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000393
394 // Iterate through all pointers in the event to normalize against the first.
395 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
396 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
397 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700398 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399
400 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700401 // First, apply the current pointer's transform to update the coordinates into
402 // window space.
403 pointerCoords[pointerIndex].transform(currTransform);
404 // Next, apply the inverse transform of the normalized coordinates so the
405 // current coordinates are transformed into the normalized coordinate space.
406 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000407 }
408
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700409 std::unique_ptr<MotionEntry> combinedMotionEntry =
410 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
411 motionEntry.deviceId, motionEntry.source,
412 motionEntry.displayId, motionEntry.policyFlags,
413 motionEntry.action, motionEntry.actionButton,
414 motionEntry.flags, motionEntry.metaState,
415 motionEntry.buttonState, motionEntry.classification,
416 motionEntry.edgeFlags, motionEntry.xPrecision,
417 motionEntry.yPrecision, motionEntry.xCursorPosition,
418 motionEntry.yCursorPosition, motionEntry.downTime,
419 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000420 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000421
422 if (motionEntry.injectionState) {
423 combinedMotionEntry->injectionState = motionEntry.injectionState;
424 combinedMotionEntry->injectionState->refCount += 1;
425 }
426
427 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700428 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700429 firstPointerTransform, inputTarget.displayTransform,
430 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000431 return dispatchEntry;
432}
433
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000434status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
435 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700436 std::unique_ptr<InputChannel> uniqueServerChannel;
437 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
438
439 serverChannel = std::move(uniqueServerChannel);
440 return result;
441}
442
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500443template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000444bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500445 if (lhs == nullptr && rhs == nullptr) {
446 return true;
447 }
448 if (lhs == nullptr || rhs == nullptr) {
449 return false;
450 }
451 return *lhs == *rhs;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000455 KeyEvent event;
456 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
457 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
458 entry.repeatCount, entry.downTime, entry.eventTime);
459 return event;
460}
461
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000462bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000463 // Do not keep track of gesture monitors. They receive every event and would disproportionately
464 // affect the statistics.
465 if (connection.monitor) {
466 return false;
467 }
468 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
469 if (!connection.responsive) {
470 return false;
471 }
472 return true;
473}
474
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000475bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000476 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
477 const int32_t& inputEventId = eventEntry.id;
478 if (inputEventId != dispatchEntry.resolvedEventId) {
479 // Event was transmuted
480 return false;
481 }
482 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
483 return false;
484 }
485 // Only track latency for events that originated from hardware
486 if (eventEntry.isSynthesized()) {
487 return false;
488 }
489 const EventEntry::Type& inputEventEntryType = eventEntry.type;
490 if (inputEventEntryType == EventEntry::Type::KEY) {
491 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
492 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
493 return false;
494 }
495 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
496 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
497 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
498 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
499 return false;
500 }
501 } else {
502 // Not a key or a motion
503 return false;
504 }
505 if (!shouldReportMetricsForConnection(connection)) {
506 return false;
507 }
508 return true;
509}
510
Prabir Pradhancef936d2021-07-21 16:17:52 +0000511/**
512 * Connection is responsive if it has no events in the waitQueue that are older than the
513 * current time.
514 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000515bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000516 const nsecs_t currentTime = now();
517 for (const DispatchEntry* entry : connection.waitQueue) {
518 if (entry->timeoutTime < currentTime) {
519 return false;
520 }
521 }
522 return true;
523}
524
Antonio Kantekf16f2832021-09-28 04:39:20 +0000525// Returns true if the event type passed as argument represents a user activity.
526bool isUserActivityEvent(const EventEntry& eventEntry) {
527 switch (eventEntry.type) {
528 case EventEntry::Type::FOCUS:
529 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
530 case EventEntry::Type::DRAG:
531 case EventEntry::Type::TOUCH_MODE_CHANGED:
532 case EventEntry::Type::SENSOR:
533 case EventEntry::Type::CONFIGURATION_CHANGED:
534 return false;
535 case EventEntry::Type::DEVICE_RESET:
536 case EventEntry::Type::KEY:
537 case EventEntry::Type::MOTION:
538 return true;
539 }
540}
541
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800542// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700543bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
544 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800545 const auto inputConfig = windowInfo.inputConfig;
546 if (windowInfo.displayId != displayId ||
547 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800548 return false;
549 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700550 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800551 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800552 return false;
553 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800554 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800555 return false;
556 }
557 return true;
558}
559
Prabir Pradhand65552b2021-10-07 11:23:50 -0700560bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
561 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
562 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
563 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
564}
565
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000566} // namespace
567
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568// --- InputDispatcher ---
569
Garfield Tan00f511d2019-06-12 16:55:40 -0700570InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
571 : mPolicy(policy),
572 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700573 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800574 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700575 mAppSwitchSawKeyDown(false),
576 mAppSwitchDueTime(LONG_LONG_MAX),
577 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800578 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700579 mDispatchEnabled(false),
580 mDispatchFrozen(false),
581 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800582 // mInTouchMode will be initialized by the WindowManager to the default device config.
583 // To avoid leaking stack in case that call never comes, and for tests,
584 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000585 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100586 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000587 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800588 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000589 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800590 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800592 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700594 mWindowInfoListener = new DispatcherWindowListener(*this);
595 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
596
Yi Kong9b14ac62018-07-17 13:48:38 -0700597 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598
599 policy->getDispatcherConfiguration(&mConfig);
600}
601
602InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000603 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604
Prabir Pradhancef936d2021-07-21 16:17:52 +0000605 resetKeyRepeatLocked();
606 releasePendingEventLocked();
607 drainInboundQueueLocked();
608 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000610 while (!mConnectionsByToken.empty()) {
611 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000612 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
613 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 }
615}
616
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700617status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700618 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700619 return ALREADY_EXISTS;
620 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700621 mThread = std::make_unique<InputThread>(
622 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
623 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700624}
625
626status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700627 if (mThread && mThread->isCallingThread()) {
628 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700629 return INVALID_OPERATION;
630 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700631 mThread.reset();
632 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700633}
634
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635void InputDispatcher::dispatchOnce() {
636 nsecs_t nextWakeupTime = LONG_LONG_MAX;
637 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800638 std::scoped_lock _l(mLock);
639 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640
641 // Run a dispatch loop if there are no pending commands.
642 // The dispatch loop might enqueue commands to run afterwards.
643 if (!haveCommandsLocked()) {
644 dispatchOnceInnerLocked(&nextWakeupTime);
645 }
646
647 // Run all pending commands if there are any.
648 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000649 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 nextWakeupTime = LONG_LONG_MIN;
651 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800652
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700653 // If we are still waiting for ack on some events,
654 // we might have to wake up earlier to check if an app is anr'ing.
655 const nsecs_t nextAnrCheck = processAnrsLocked();
656 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
657
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800658 // We are about to enter an infinitely long sleep, because we have no commands or
659 // pending or queued events
660 if (nextWakeupTime == LONG_LONG_MAX) {
661 mDispatcherEnteredIdle.notify_all();
662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 } // release lock
664
665 // Wait for callback or timeout or wake. (make sure we round up, not down)
666 nsecs_t currentTime = now();
667 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
668 mLooper->pollOnce(timeoutMillis);
669}
670
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500672 * Raise ANR if there is no focused window.
673 * Before the ANR is raised, do a final state check:
674 * 1. The currently focused application must be the same one we are waiting for.
675 * 2. Ensure we still don't have a focused window.
676 */
677void InputDispatcher::processNoFocusedWindowAnrLocked() {
678 // Check if the application that we are waiting for is still focused.
679 std::shared_ptr<InputApplicationHandle> focusedApplication =
680 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
681 if (focusedApplication == nullptr ||
682 focusedApplication->getApplicationToken() !=
683 mAwaitedFocusedApplication->getApplicationToken()) {
684 // Unexpected because we should have reset the ANR timer when focused application changed
685 ALOGE("Waited for a focused window, but focused application has already changed to %s",
686 focusedApplication->getName().c_str());
687 return; // The focused application has changed.
688 }
689
chaviw98318de2021-05-19 16:45:23 -0500690 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500691 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
692 if (focusedWindowHandle != nullptr) {
693 return; // We now have a focused window. No need for ANR.
694 }
695 onAnrLocked(mAwaitedFocusedApplication);
696}
697
698/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700699 * Check if any of the connections' wait queues have events that are too old.
700 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
701 * Return the time at which we should wake up next.
702 */
703nsecs_t InputDispatcher::processAnrsLocked() {
704 const nsecs_t currentTime = now();
705 nsecs_t nextAnrCheck = LONG_LONG_MAX;
706 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
707 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
708 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500709 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700710 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500711 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 return LONG_LONG_MIN;
713 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500714 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700715 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
716 }
717 }
718
719 // Check if any connection ANRs are due
720 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
721 if (currentTime < nextAnrCheck) { // most likely scenario
722 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
723 }
724
725 // If we reached here, we have an unresponsive connection.
726 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
727 if (connection == nullptr) {
728 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
729 return nextAnrCheck;
730 }
731 connection->responsive = false;
732 // Stop waking up for this unresponsive connection
733 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000734 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700735 return LONG_LONG_MIN;
736}
737
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800738std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
739 const sp<Connection>& connection) {
740 if (connection->monitor) {
741 return mMonitorDispatchingTimeout;
742 }
743 const sp<WindowInfoHandle> window =
744 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700745 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500746 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700747 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500748 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700749}
750
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
752 nsecs_t currentTime = now();
753
Jeff Browndc5992e2014-04-11 01:27:26 -0700754 // Reset the key repeat timer whenever normal dispatch is suspended while the
755 // device is in a non-interactive state. This is to ensure that we abort a key
756 // repeat if the device is just coming out of sleep.
757 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 resetKeyRepeatLocked();
759 }
760
761 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
762 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100763 if (DEBUG_FOCUS) {
764 ALOGD("Dispatch frozen. Waiting some more.");
765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 return;
767 }
768
769 // Optimize latency of app switches.
770 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
771 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
772 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
773 if (mAppSwitchDueTime < *nextWakeupTime) {
774 *nextWakeupTime = mAppSwitchDueTime;
775 }
776
777 // Ready to start a new event.
778 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700780 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 if (isAppSwitchDue) {
782 // The inbound queue is empty so the app switch key we were waiting
783 // for will never arrive. Stop waiting for it.
784 resetPendingAppSwitchLocked(false);
785 isAppSwitchDue = false;
786 }
787
788 // Synthesize a key repeat if appropriate.
789 if (mKeyRepeatState.lastKeyEntry) {
790 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
791 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
792 } else {
793 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
794 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
795 }
796 }
797 }
798
799 // Nothing to do if there is no pending event.
800 if (!mPendingEvent) {
801 return;
802 }
803 } else {
804 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700805 mPendingEvent = mInboundQueue.front();
806 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 traceInboundQueueLengthLocked();
808 }
809
810 // Poke user activity for this event.
811 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700812 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 }
815
816 // Now we have an event to dispatch.
817 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700818 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700822 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700824 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 }
826
827 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700828 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 }
830
831 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700832 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700833 const ConfigurationChangedEntry& typedEntry =
834 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700836 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700837 break;
838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700840 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700841 const DeviceResetEntry& typedEntry =
842 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700844 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700845 break;
846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100848 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 std::shared_ptr<FocusEntry> typedEntry =
850 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100851 dispatchFocusLocked(currentTime, typedEntry);
852 done = true;
853 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
854 break;
855 }
856
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700857 case EventEntry::Type::TOUCH_MODE_CHANGED: {
858 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
859 dispatchTouchModeChangeLocked(currentTime, typedEntry);
860 done = true;
861 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
862 break;
863 }
864
Prabir Pradhan99987712020-11-10 18:43:05 -0800865 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
866 const auto typedEntry =
867 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
868 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
869 done = true;
870 break;
871 }
872
arthurhungb89ccb02020-12-30 16:19:01 +0800873 case EventEntry::Type::DRAG: {
874 std::shared_ptr<DragEntry> typedEntry =
875 std::static_pointer_cast<DragEntry>(mPendingEvent);
876 dispatchDragLocked(currentTime, typedEntry);
877 done = true;
878 break;
879 }
880
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700881 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700884 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 resetPendingAppSwitchLocked(true);
886 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 } else if (dropReason == DropReason::NOT_DROPPED) {
888 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 }
890 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700891 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700892 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
895 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700897 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 break;
899 }
900
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700901 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902 std::shared_ptr<MotionEntry> motionEntry =
903 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700904 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
905 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700907 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700908 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700910 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
911 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700913 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 }
Chris Yef59a2f42020-10-16 12:55:26 -0700916
917 case EventEntry::Type::SENSOR: {
918 std::shared_ptr<SensorEntry> sensorEntry =
919 std::static_pointer_cast<SensorEntry>(mPendingEvent);
920 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
921 dropReason = DropReason::APP_SWITCH;
922 }
923 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
924 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
925 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
926 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
927 dropReason = DropReason::STALE;
928 }
929 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
930 done = true;
931 break;
932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 }
934
935 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700936 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700937 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 }
Michael Wright3a981722015-06-10 15:26:13 +0100939 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940
941 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700942 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 }
944}
945
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700946/**
947 * Return true if the events preceding this incoming motion event should be dropped
948 * Return false otherwise (the default behaviour)
949 */
950bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700951 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700952 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700953
954 // Optimize case where the current application is unresponsive and the user
955 // decides to touch a window in a different application.
956 // If the application takes too long to catch up then we drop all events preceding
957 // the touch into the other window.
958 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700959 int32_t displayId = motionEntry.displayId;
960 int32_t x = static_cast<int32_t>(
961 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
962 int32_t y = static_cast<int32_t>(
963 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700964
965 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500966 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700967 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700968 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700969 touchedWindowHandle->getApplicationToken() !=
970 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700971 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700972 ALOGI("Pruning input queue because user touched a different application while waiting "
973 "for %s",
974 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700975 return true;
976 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700977
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800978 // Alternatively, maybe there's a spy window that could handle this event.
979 const std::vector<sp<WindowInfoHandle>> touchedSpies =
980 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
981 for (const auto& windowHandle : touchedSpies) {
982 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000983 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800984 // This spy window could take more input. Drop all events preceding this
985 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700986 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800987 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700988 mAwaitedFocusedApplication->getName().c_str());
989 return true;
990 }
991 }
992 }
993
994 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
995 // yet been processed by some connections, the dispatcher will wait for these motion
996 // events to be processed before dispatching the key event. This is because these motion events
997 // may cause a new window to be launched, which the user might expect to receive focus.
998 // To prevent waiting forever for such events, just send the key to the currently focused window
999 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1000 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1001 "just send the pending key event to the focused window.");
1002 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001003 }
1004 return false;
1005}
1006
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001007bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001008 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001009 mInboundQueue.push_back(std::move(newEntry));
1010 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 traceInboundQueueLengthLocked();
1012
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001013 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001014 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 // Optimize app switch latency.
1016 // If the application takes too long to catch up then we drop all events preceding
1017 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001018 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001020 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001022 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001024 if (DEBUG_APP_SWITCH) {
1025 ALOGD("App switch is pending!");
1026 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001027 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 mAppSwitchSawKeyDown = false;
1029 needWake = true;
1030 }
1031 }
1032 }
1033 break;
1034 }
1035
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001036 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001037 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1038 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001039 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001043 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001044 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1045 break;
1046 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001047 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001048 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001049 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001050 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001051 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1052 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001053 // nothing to do
1054 break;
1055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057
1058 return needWake;
1059}
1060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001061void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001062 // Do not store sensor event in recent queue to avoid flooding the queue.
1063 if (entry->type != EventEntry::Type::SENSOR) {
1064 mRecentQueue.push_back(entry);
1065 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001066 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001067 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069}
1070
chaviw98318de2021-05-19 16:45:23 -05001071sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1072 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001073 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001074 bool addOutsideTargets,
1075 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001076 if (addOutsideTargets && touchState == nullptr) {
1077 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001080 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001081 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001082 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001083 continue;
1084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001086 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001087 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001088 return windowHandle;
1089 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001090
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001091 if (addOutsideTargets &&
1092 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001093 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1094 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001097 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098}
1099
Prabir Pradhand65552b2021-10-07 11:23:50 -07001100std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1101 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001102 // Traverse windows from front to back and gather the touched spy windows.
1103 std::vector<sp<WindowInfoHandle>> spyWindows;
1104 const auto& windowHandles = getWindowHandlesLocked(displayId);
1105 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1106 const WindowInfo& info = *windowHandle->getInfo();
1107
Prabir Pradhand65552b2021-10-07 11:23:50 -07001108 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001109 continue;
1110 }
1111 if (!info.isSpy()) {
1112 // The first touched non-spy window was found, so return the spy windows touched so far.
1113 return spyWindows;
1114 }
1115 spyWindows.push_back(windowHandle);
1116 }
1117 return spyWindows;
1118}
1119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001120void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 const char* reason;
1122 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001124 if (DEBUG_INBOUND_EVENT_DETAILS) {
1125 ALOGD("Dropped event because policy consumed it.");
1126 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 reason = "inbound event was dropped because the policy consumed it";
1128 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 case DropReason::DISABLED:
1130 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 ALOGI("Dropped event because input dispatch is disabled.");
1132 }
1133 reason = "inbound event was dropped because input dispatch is disabled";
1134 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 ALOGI("Dropped event because of pending overdue app switch.");
1137 reason = "inbound event was dropped because of pending overdue app switch";
1138 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001139 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 ALOGI("Dropped event because the current application is not responding and the user "
1141 "has started interacting with a different application.");
1142 reason = "inbound event was dropped because the current application is not responding "
1143 "and the user has started interacting with a different application";
1144 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001145 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 ALOGI("Dropped event because it is stale.");
1147 reason = "inbound event was dropped because it is stale";
1148 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001149 case DropReason::NO_POINTER_CAPTURE:
1150 ALOGI("Dropped event because there is no window with Pointer Capture.");
1151 reason = "inbound event was dropped because there is no window with Pointer Capture";
1152 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001153 case DropReason::NOT_DROPPED: {
1154 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001159 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001160 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1162 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001165 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1167 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1169 synthesizeCancelationEventsForAllConnectionsLocked(options);
1170 } else {
1171 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1172 synthesizeCancelationEventsForAllConnectionsLocked(options);
1173 }
1174 break;
1175 }
Chris Yef59a2f42020-10-16 12:55:26 -07001176 case EventEntry::Type::SENSOR: {
1177 break;
1178 }
arthurhungb89ccb02020-12-30 16:19:01 +08001179 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1180 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001181 break;
1182 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001183 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001184 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001185 case EventEntry::Type::CONFIGURATION_CHANGED:
1186 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001187 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001188 break;
1189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191}
1192
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001193static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1195 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196}
1197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001198bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1199 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1200 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1201 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202}
1203
1204bool InputDispatcher::isAppSwitchPendingLocked() {
1205 return mAppSwitchDueTime != LONG_LONG_MAX;
1206}
1207
1208void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1209 mAppSwitchDueTime = LONG_LONG_MAX;
1210
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001211 if (DEBUG_APP_SWITCH) {
1212 if (handled) {
1213 ALOGD("App switch has arrived.");
1214 } else {
1215 ALOGD("App switch was abandoned.");
1216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218}
1219
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001221 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222}
1223
Prabir Pradhancef936d2021-07-21 16:17:52 +00001224bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001225 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 return false;
1227 }
1228
1229 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001230 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001231 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001232 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1233 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001234 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 return true;
1236}
1237
Prabir Pradhancef936d2021-07-21 16:17:52 +00001238void InputDispatcher::postCommandLocked(Command&& command) {
1239 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240}
1241
1242void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001243 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001245 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 releaseInboundEventLocked(entry);
1247 }
1248 traceInboundQueueLengthLocked();
1249}
1250
1251void InputDispatcher::releasePendingEventLocked() {
1252 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001254 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256}
1257
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001258void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001260 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001261 if (DEBUG_DISPATCH_CYCLE) {
1262 ALOGD("Injected inbound event was dropped.");
1263 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001264 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001267 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 }
1269 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270}
1271
1272void InputDispatcher::resetKeyRepeatLocked() {
1273 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001274 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 }
1276}
1277
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1279 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
Michael Wright2e732952014-09-24 13:26:59 -07001281 uint32_t policyFlags = entry->policyFlags &
1282 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001284 std::shared_ptr<KeyEntry> newEntry =
1285 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1286 entry->source, entry->displayId, policyFlags, entry->action,
1287 entry->flags, entry->keyCode, entry->scanCode,
1288 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 newEntry->syntheticRepeat = true;
1291 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001293 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294}
1295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001297 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001298 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1299 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301
1302 // Reset key repeating in case a keyboard device was added or removed or something.
1303 resetKeyRepeatLocked();
1304
1305 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001306 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1307 scoped_unlock unlock(mLock);
1308 mPolicy->notifyConfigurationChanged(eventTime);
1309 };
1310 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 return true;
1312}
1313
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1315 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001316 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1317 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1318 entry.deviceId);
1319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320
liushenxiang42232912021-05-21 20:24:09 +08001321 // Reset key repeating in case a keyboard device was disabled or enabled.
1322 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1323 resetKeyRepeatLocked();
1324 }
1325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001326 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001327 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 synthesizeCancelationEventsForAllConnectionsLocked(options);
1329 return true;
1330}
1331
Vishnu Nairad321cd2020-08-20 16:40:21 -07001332void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001333 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001334 if (mPendingEvent != nullptr) {
1335 // Move the pending event to the front of the queue. This will give the chance
1336 // for the pending event to get dispatched to the newly focused window
1337 mInboundQueue.push_front(mPendingEvent);
1338 mPendingEvent = nullptr;
1339 }
1340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341 std::unique_ptr<FocusEntry> focusEntry =
1342 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1343 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001344
1345 // This event should go to the front of the queue, but behind all other focus events
1346 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001347 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001348 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001349 [](const std::shared_ptr<EventEntry>& event) {
1350 return event->type == EventEntry::Type::FOCUS;
1351 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001352
1353 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001355}
1356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001357void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001358 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001359 if (channel == nullptr) {
1360 return; // Window has gone away
1361 }
1362 InputTarget target;
1363 target.inputChannel = channel;
1364 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1365 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001366 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1367 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001368 std::string reason = std::string("reason=").append(entry->reason);
1369 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001370 dispatchEventLocked(currentTime, entry, {target});
1371}
1372
Prabir Pradhan99987712020-11-10 18:43:05 -08001373void InputDispatcher::dispatchPointerCaptureChangedLocked(
1374 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1375 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001376 dropReason = DropReason::NOT_DROPPED;
1377
Prabir Pradhan99987712020-11-10 18:43:05 -08001378 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001379 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001380
1381 if (entry->pointerCaptureRequest.enable) {
1382 // Enable Pointer Capture.
1383 if (haveWindowWithPointerCapture &&
1384 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1385 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1386 "to the window.");
1387 }
1388 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001389 // This can happen if a window requests capture and immediately releases capture.
1390 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001391 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 return;
1393 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001394 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1395 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1396 return;
1397 }
1398
Vishnu Nairc519ff72021-01-21 08:23:08 -08001399 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001400 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1401 mWindowTokenWithPointerCapture = token;
1402 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001403 // Disable Pointer Capture.
1404 // We do not check if the sequence number matches for requests to disable Pointer Capture
1405 // for two reasons:
1406 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1407 // to disable capture with the same sequence number: one generated by
1408 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1409 // Capture being disabled in InputReader.
1410 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1411 // actual Pointer Capture state that affects events being generated by input devices is
1412 // in InputReader.
1413 if (!haveWindowWithPointerCapture) {
1414 // Pointer capture was already forcefully disabled because of focus change.
1415 dropReason = DropReason::NOT_DROPPED;
1416 return;
1417 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001418 token = mWindowTokenWithPointerCapture;
1419 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001420 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001421 setPointerCaptureLocked(false);
1422 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001423 }
1424
1425 auto channel = getInputChannelLocked(token);
1426 if (channel == nullptr) {
1427 // Window has gone away, clean up Pointer Capture state.
1428 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001429 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001430 setPointerCaptureLocked(false);
1431 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001432 return;
1433 }
1434 InputTarget target;
1435 target.inputChannel = channel;
1436 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1437 entry->dispatchInProgress = true;
1438 dispatchEventLocked(currentTime, entry, {target});
1439
1440 dropReason = DropReason::NOT_DROPPED;
1441}
1442
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001443void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1444 const std::shared_ptr<TouchModeEntry>& entry) {
1445 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1446 getWindowHandlesLocked(mFocusedDisplayId);
1447 if (windowHandles.empty()) {
1448 return;
1449 }
1450 const std::vector<InputTarget> inputTargets =
1451 getInputTargetsFromWindowHandlesLocked(windowHandles);
1452 if (inputTargets.empty()) {
1453 return;
1454 }
1455 entry->dispatchInProgress = true;
1456 dispatchEventLocked(currentTime, entry, inputTargets);
1457}
1458
1459std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1460 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1461 std::vector<InputTarget> inputTargets;
1462 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1463 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1464 const sp<IBinder>& token = handle->getToken();
1465 if (token == nullptr) {
1466 continue;
1467 }
1468 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1469 if (channel == nullptr) {
1470 continue; // Window has gone away
1471 }
1472 InputTarget target;
1473 target.inputChannel = channel;
1474 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1475 inputTargets.push_back(target);
1476 }
1477 return inputTargets;
1478}
1479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001480bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 if (!entry->dispatchInProgress) {
1484 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1485 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1486 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1487 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001488 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 // We have seen two identical key downs in a row which indicates that the device
1490 // driver is automatically generating key repeats itself. We take note of the
1491 // repeat here, but we disable our own next key repeat timer since it is clear that
1492 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001493 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1494 // Make sure we don't get key down from a different device. If a different
1495 // device Id has same key pressed down, the new device Id will replace the
1496 // current one to hold the key repeat with repeat count reset.
1497 // In the future when got a KEY_UP on the device id, drop it and do not
1498 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1500 resetKeyRepeatLocked();
1501 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1502 } else {
1503 // Not a repeat. Save key down state in case we do see a repeat later.
1504 resetKeyRepeatLocked();
1505 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1506 }
1507 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001508 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1509 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001511 if (DEBUG_INBOUND_EVENT_DETAILS) {
1512 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1513 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001514 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 resetKeyRepeatLocked();
1516 }
1517
1518 if (entry->repeatCount == 1) {
1519 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1520 } else {
1521 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1522 }
1523
1524 entry->dispatchInProgress = true;
1525
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 }
1528
1529 // Handle case where the policy asked us to try again later last time.
1530 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1531 if (currentTime < entry->interceptKeyWakeupTime) {
1532 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1533 *nextWakeupTime = entry->interceptKeyWakeupTime;
1534 }
1535 return false; // wait until next wakeup
1536 }
1537 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1538 entry->interceptKeyWakeupTime = 0;
1539 }
1540
1541 // Give the policy a chance to intercept the key.
1542 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1543 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001544 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001545 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001546
1547 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1548 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1549 };
1550 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 return false; // wait for the command to run
1552 } else {
1553 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1554 }
1555 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001556 if (*dropReason == DropReason::NOT_DROPPED) {
1557 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 }
1559 }
1560
1561 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001562 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001563 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1565 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001566 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return true;
1568 }
1569
1570 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001571 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001572 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001573 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 return false;
1576 }
1577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001579 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 return true;
1581 }
1582
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001583 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001584 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585
1586 // Dispatch the key.
1587 dispatchEventLocked(currentTime, entry, inputTargets);
1588 return true;
1589}
1590
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001591void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1593 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1594 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1595 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1596 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1597 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1598 entry.metaState, entry.repeatCount, entry.downTime);
1599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600}
1601
Prabir Pradhancef936d2021-07-21 16:17:52 +00001602void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1603 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001604 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001605 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1606 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1607 "source=0x%x, sensorType=%s",
1608 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001609 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001610 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001611 auto command = [this, entry]() REQUIRES(mLock) {
1612 scoped_unlock unlock(mLock);
1613
1614 if (entry->accuracyChanged) {
1615 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1616 }
1617 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1618 entry->hwTimestamp, entry->values);
1619 };
1620 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001621}
1622
1623bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1625 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001626 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001627 }
Chris Yef59a2f42020-10-16 12:55:26 -07001628 { // acquire lock
1629 std::scoped_lock _l(mLock);
1630
1631 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1632 std::shared_ptr<EventEntry> entry = *it;
1633 if (entry->type == EventEntry::Type::SENSOR) {
1634 it = mInboundQueue.erase(it);
1635 releaseInboundEventLocked(entry);
1636 }
1637 }
1638 }
1639 return true;
1640}
1641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001643 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001644 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 entry->dispatchInProgress = true;
1648
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 }
1651
1652 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001653 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001654 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001655 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1656 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return true;
1658 }
1659
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001660 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661
1662 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001663 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
1665 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001666 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 if (isPointerEvent) {
1668 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001669 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001671 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 } else {
1673 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001677 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 return false;
1679 }
1680
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001681 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001682 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001683 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1684 return true;
1685 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001686 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001687 CancelationOptions::Mode mode(isPointerEvent
1688 ? CancelationOptions::CANCEL_POINTER_EVENTS
1689 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1690 CancelationOptions options(mode, "input event injection failed");
1691 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 return true;
1693 }
1694
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001695 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697
1698 // Dispatch the motion.
1699 if (conflictingPointerActions) {
1700 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001701 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 synthesizeCancelationEventsForAllConnectionsLocked(options);
1703 }
1704 dispatchEventLocked(currentTime, entry, inputTargets);
1705 return true;
1706}
1707
chaviw98318de2021-05-19 16:45:23 -05001708void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001709 bool isExiting, const MotionEntry& motionEntry) {
1710 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1711 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1712 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1713 PointerCoords pointerCoords;
1714 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1715 pointerCoords.transform(windowHandle->getInfo()->transform);
1716
1717 std::unique_ptr<DragEntry> dragEntry =
1718 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1719 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1720 pointerCoords.getY());
1721
1722 enqueueInboundEventLocked(std::move(dragEntry));
1723}
1724
1725void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1726 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1727 if (channel == nullptr) {
1728 return; // Window has gone away
1729 }
1730 InputTarget target;
1731 target.inputChannel = channel;
1732 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1733 entry->dispatchInProgress = true;
1734 dispatchEventLocked(currentTime, entry, {target});
1735}
1736
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001738 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1739 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1740 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001741 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001742 "metaState=0x%x, buttonState=0x%x,"
1743 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1744 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001745 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1746 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1747 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001749 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1750 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1751 "x=%f, y=%f, pressure=%f, size=%f, "
1752 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1753 "orientation=%f",
1754 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1756 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1760 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1761 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1762 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1763 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766}
1767
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001768void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1769 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001770 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001771 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001772 if (DEBUG_DISPATCH_CYCLE) {
1773 ALOGD("dispatchEventToCurrentInputTargets");
1774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001776 updateInteractionTokensLocked(*eventEntry, inputTargets);
1777
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1779
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001780 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001782 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001783 sp<Connection> connection =
1784 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001785 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001786 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001788 if (DEBUG_FOCUS) {
1789 ALOGD("Dropping event delivery to target with channel '%s' because it "
1790 "is no longer registered with the input dispatcher.",
1791 inputTarget.inputChannel->getName().c_str());
1792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794 }
1795}
1796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1798 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1799 // If the policy decides to close the app, we will get a channel removal event via
1800 // unregisterInputChannel, and will clean up the connection that way. We are already not
1801 // sending new pointers to the connection when it blocked, but focused events will continue to
1802 // pile up.
1803 ALOGW("Canceling events for %s because it is unresponsive",
1804 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001805 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001806 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1807 "application not responding");
1808 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
1810}
1811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001813 if (DEBUG_FOCUS) {
1814 ALOGD("Resetting ANR timeouts.");
1815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001819 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820}
1821
Tiger Huang721e26f2018-07-24 22:26:19 +08001822/**
1823 * Get the display id that the given event should go to. If this event specifies a valid display id,
1824 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1825 * Focused display is the display that the user most recently interacted with.
1826 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001828 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001830 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1832 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001833 break;
1834 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001835 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1837 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 break;
1839 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001840 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001841 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001842 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001843 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001844 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001845 case EventEntry::Type::SENSOR:
1846 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001847 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001848 return ADISPLAY_ID_NONE;
1849 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001850 }
1851 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1852}
1853
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1855 const char* focusedWindowName) {
1856 if (mAnrTracker.empty()) {
1857 // already processed all events that we waited for
1858 mKeyIsWaitingForEventsTimeout = std::nullopt;
1859 return false;
1860 }
1861
1862 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1863 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001864 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001865 mKeyIsWaitingForEventsTimeout = currentTime +
1866 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1867 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001868 return true;
1869 }
1870
1871 // We still have pending events, and already started the timer
1872 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1873 return true; // Still waiting
1874 }
1875
1876 // Waited too long, and some connection still hasn't processed all motions
1877 // Just send the key to the focused window
1878 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1879 focusedWindowName);
1880 mKeyIsWaitingForEventsTimeout = std::nullopt;
1881 return false;
1882}
1883
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1885 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1886 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001887 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888
Tiger Huang721e26f2018-07-24 22:26:19 +08001889 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001890 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001891 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001892 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1893
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 // If there is no currently focused window and no focused application
1895 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001896 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1897 ALOGI("Dropping %s event because there is no focused window or focused application in "
1898 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001899 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
1902
Vishnu Nair062a8672021-09-03 16:07:44 -07001903 // Drop key events if requested by input feature
1904 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1905 return InputEventInjectionResult::FAILED;
1906 }
1907
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1909 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1910 // start interacting with another application via touch (app switch). This code can be removed
1911 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1912 // an app is expected to have a focused window.
1913 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1914 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1915 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001916 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1917 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1918 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001919 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001920 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001921 ALOGW("Waiting because no window has focus but %s may eventually add a "
1922 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001923 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001925 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001926 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1927 // Already raised ANR. Drop the event
1928 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001929 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001930 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 } else {
1932 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 }
1935 }
1936
1937 // we have a valid, non-null focused window
1938 resetNoFocusedWindowTimeoutLocked();
1939
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001941 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 }
1944
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001945 if (focusedWindowHandle->getInfo()->inputConfig.test(
1946 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001947 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001948 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949 }
1950
1951 // If the event is a key event, then we must wait for all previous events to
1952 // complete before delivering it because previous events may have the
1953 // side-effect of transferring focus to a different window and we want to
1954 // ensure that the following keys are sent to the new window.
1955 //
1956 // Suppose the user touches a button in a window then immediately presses "A".
1957 // If the button causes a pop-up window to appear then we want to ensure that
1958 // the "A" key is delivered to the new pop-up window. This is because users
1959 // often anticipate pending UI changes when typing on a keyboard.
1960 // To obtain this behavior, we must serialize key events with respect to all
1961 // prior input events.
1962 if (entry.type == EventEntry::Type::KEY) {
1963 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1964 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 }
1968
1969 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001970 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1972 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973
1974 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001975 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976}
1977
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001978/**
1979 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1980 * that are currently unresponsive.
1981 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001982std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1983 const std::vector<Monitor>& monitors) const {
1984 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001986 [this](const Monitor& monitor) REQUIRES(mLock) {
1987 sp<Connection> connection =
1988 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 if (connection == nullptr) {
1990 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001991 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 return false;
1993 }
1994 if (!connection->responsive) {
1995 ALOGW("Unresponsive monitor %s will not get the new gesture",
1996 connection->inputChannel->getName().c_str());
1997 return false;
1998 }
1999 return true;
2000 });
2001 return responsiveMonitors;
2002}
2003
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002004InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2005 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2006 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002007 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 enum InjectionPermission {
2009 INJECTION_PERMISSION_UNKNOWN,
2010 INJECTION_PERMISSION_GRANTED,
2011 INJECTION_PERMISSION_DENIED
2012 };
2013
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 // For security reasons, we defer updating the touch state until we are sure that
2015 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002016 const int32_t displayId = entry.displayId;
2017 const int32_t action = entry.action;
2018 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019
2020 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002021 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05002023 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2024 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002026 // Copy current touch state into tempTouchState.
2027 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2028 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002029 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002030 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002031 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2032 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002033 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002034 }
2035
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002036 bool isSplit = tempTouchState.split;
2037 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2038 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2039 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002040
2041 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2042 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2043 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2044 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2045 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002046 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 bool wrongDevice = false;
2048 if (newGesture) {
2049 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002050 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002051 ALOGI("Dropping event because a pointer for a different device is already down "
2052 "in display %" PRId32,
2053 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002054 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002055 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 switchedDevice = false;
2057 wrongDevice = true;
2058 goto Failed;
2059 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002060 tempTouchState.reset();
2061 tempTouchState.down = down;
2062 tempTouchState.deviceId = entry.deviceId;
2063 tempTouchState.source = entry.source;
2064 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002066 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002067 ALOGI("Dropping move event because a pointer for a different device is already active "
2068 "in display %" PRId32,
2069 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002070 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002071 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002072 switchedDevice = false;
2073 wrongDevice = true;
2074 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
2076
2077 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2078 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2079
Garfield Tan00f511d2019-06-12 16:55:40 -07002080 int32_t x;
2081 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002082 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002083 // Always dispatch mouse events to cursor position.
2084 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 x = int32_t(entry.xCursorPosition);
2086 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002087 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002088 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2089 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002090 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002091 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002092 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002093 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002094 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002095
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002097 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002098 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2099 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002101 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002102 }
2103
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002104 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002105 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002106 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2107 // New window supports splitting, but we should never split mouse events.
2108 isSplit = !isFromMouse;
2109 } else if (isSplit) {
2110 // New window does not support splitting but we have already split events.
2111 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112 newTouchedWindowHandle = nullptr;
2113 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002114 } else {
2115 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002116 // be delivered to a new window which supports split touch. Pointers from a mouse device
2117 // should never be split.
2118 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002119 }
2120
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002121 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002122 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002123 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2124 newHoverWindowHandle = nullptr;
2125 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002126 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002127 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002128 }
2129
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002130 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002131 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002132 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002133 // Process the foreground window first so that it is the first to receive the event.
2134 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002135 }
2136
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002137 if (newTouchedWindows.empty()) {
2138 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2139 x, y, displayId);
2140 injectionResult = InputEventInjectionResult::FAILED;
2141 goto Failed;
2142 }
2143
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002144 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2145 const WindowInfo& info = *windowHandle->getInfo();
2146
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002147 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148 ALOGI("Not sending touch event to %s because it is paused",
2149 windowHandle->getName().c_str());
2150 continue;
2151 }
2152
2153 // Ensure the window has a connection and the connection is responsive
2154 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2155 if (!isResponsive) {
2156 ALOGW("Not sending touch gesture to %s because it is not responsive",
2157 windowHandle->getName().c_str());
2158 continue;
2159 }
2160
2161 // Drop events that can't be trusted due to occlusion
2162 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2163 TouchOcclusionInfo occlusionInfo =
2164 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2165 if (!isTouchTrustedLocked(occlusionInfo)) {
2166 if (DEBUG_TOUCH_OCCLUSION) {
2167 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2168 for (const auto& log : occlusionInfo.debugInfo) {
2169 ALOGD("%s", log.c_str());
2170 }
2171 }
2172 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2173 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2174 ALOGW("Dropping untrusted touch event due to %s/%d",
2175 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2176 continue;
2177 }
2178 }
2179 }
2180
2181 // Drop touch events if requested by input feature
2182 if (shouldDropInput(entry, windowHandle)) {
2183 continue;
2184 }
2185
2186 // Set target flags.
2187 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2188
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002189 if (!info.isSpy()) {
2190 // There should only be one new foreground (non-spy) window at this location.
2191 targetFlags |= InputTarget::FLAG_FOREGROUND;
2192 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002193
2194 if (isSplit) {
2195 targetFlags |= InputTarget::FLAG_SPLIT;
2196 }
2197 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2198 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2199 } else if (isWindowObscuredLocked(windowHandle)) {
2200 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2201 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002202
2203 // Update the temporary touch state.
2204 BitSet32 pointerIds;
2205 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002206 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002207 pointerIds.markBit(pointerId);
2208 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002209
2210 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 } else {
2213 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2214
2215 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002216 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002217 if (DEBUG_FOCUS) {
2218 ALOGD("Dropping event because the pointer is not down or we previously "
2219 "dropped the pointer down event in display %" PRId32,
2220 displayId);
2221 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002222 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 goto Failed;
2224 }
2225
arthurhung6d4bed92021-03-17 11:59:33 +08002226 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002227
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002229 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002230 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002231 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2232 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233
Prabir Pradhand65552b2021-10-07 11:23:50 -07002234 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002235 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002236 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002237 newTouchedWindowHandle =
2238 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002239
2240 // Drop touch events if requested by input feature
2241 if (newTouchedWindowHandle != nullptr &&
2242 shouldDropInput(entry, newTouchedWindowHandle)) {
2243 newTouchedWindowHandle = nullptr;
2244 }
2245
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2247 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002248 if (DEBUG_FOCUS) {
2249 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2250 oldTouchedWindowHandle->getName().c_str(),
2251 newTouchedWindowHandle->getName().c_str(), displayId);
2252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2255 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2256 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257
2258 // Make a slippery entrance into the new window.
2259 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002260 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
2262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002263 int32_t targetFlags =
2264 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (isSplit) {
2266 targetFlags |= InputTarget::FLAG_SPLIT;
2267 }
2268 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2269 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002270 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2271 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273
2274 BitSet32 pointerIds;
2275 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002276 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
2280 }
2281 }
2282
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285 // Let the previous window know that the hover sequence is over, unless we already did
2286 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002287 if (mLastHoverWindowHandle != nullptr &&
2288 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2289 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002290 if (DEBUG_HOVER) {
2291 ALOGD("Sending hover exit event to window %s.",
2292 mLastHoverWindowHandle->getName().c_str());
2293 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002294 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2295 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
Garfield Tandf26e862020-07-01 20:18:19 -07002298 // Let the new window know that the hover sequence is starting, unless we already did it
2299 // when dispatching it as is to newTouchedWindowHandle.
2300 if (newHoverWindowHandle != nullptr &&
2301 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2302 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002303 if (DEBUG_HOVER) {
2304 ALOGD("Sending hover enter event to window %s.",
2305 newHoverWindowHandle->getName().c_str());
2306 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002307 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2308 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2309 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311 }
2312
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002313 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2314 // of the touched windows we previously found if they became paused or unresponsive or were
2315 // removed.
2316 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2317 [](const TouchedWindow& touchedWindow) {
2318 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2319 touchedWindow.windowHandle->getInfo()->isSpy();
2320 })) {
2321 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2322 displayId);
2323 injectionResult = InputEventInjectionResult::FAILED;
2324 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002327 // Check permission to inject into all touched foreground windows.
2328 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2329 [this, &entry](const TouchedWindow& touchedWindow) {
2330 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2331 !checkInjectionPermission(touchedWindow.windowHandle,
2332 entry.injectionState);
2333 })) {
2334 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2335 injectionPermission = INJECTION_PERMISSION_DENIED;
2336 goto Failed;
2337 }
2338 // Permission granted to inject into all touched foreground windows.
2339 injectionPermission = INJECTION_PERMISSION_GRANTED;
2340
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 // Check whether windows listening for outside touches are owned by the same UID. If it is
2342 // set the policy flag that we will not reveal coordinate information to this window.
2343 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002344 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002345 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002346 if (foregroundWindowHandle) {
2347 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002348 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002349 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002350 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2351 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2352 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002353 InputTarget::FLAG_ZERO_COORDS,
2354 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357 }
2358 }
2359 }
2360
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 // If this is the first pointer going down and the touched window has a wallpaper
2362 // then also add the touched wallpaper windows so they are locked in for the duration
2363 // of the touch gesture.
2364 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2365 // engine only supports touch events. We would need to add a mechanism similar
2366 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2367 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002368 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002369 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002370 if (foregroundWindowHandle &&
2371 foregroundWindowHandle->getInfo()->inputConfig.test(
2372 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002373 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002374 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002375 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2376 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002377 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002378 windowHandle->getInfo()->inputConfig.test(
2379 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002380 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 .addOrUpdateWindow(windowHandle,
2382 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2383 InputTarget::
2384 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2385 InputTarget::FLAG_DISPATCH_AS_IS,
2386 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
2388 }
2389 }
2390 }
2391
2392 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002393 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002395 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
2399
2400 // Drop the outside or hover touch windows since we will not care about them
2401 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002402 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403
2404Failed:
2405 // Check injection permission once and for all.
2406 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002407 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 injectionPermission = INJECTION_PERMISSION_GRANTED;
2409 } else {
2410 injectionPermission = INJECTION_PERMISSION_DENIED;
2411 }
2412 }
2413
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002414 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2415 return injectionResult;
2416 }
2417
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002419 if (!wrongDevice) {
2420 if (switchedDevice) {
2421 if (DEBUG_FOCUS) {
2422 ALOGD("Conflicting pointer actions: Switched to a different device.");
2423 }
2424 *outConflictingPointerActions = true;
2425 }
2426
2427 if (isHoverAction) {
2428 // Started hovering, therefore no longer down.
2429 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002430 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002431 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2432 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 *outConflictingPointerActions = true;
2435 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002436 tempTouchState.reset();
2437 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2438 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2439 tempTouchState.deviceId = entry.deviceId;
2440 tempTouchState.source = entry.source;
2441 tempTouchState.displayId = displayId;
2442 }
2443 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2444 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2445 // All pointers up or canceled.
2446 tempTouchState.reset();
2447 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2448 // First pointer went down.
2449 if (oldState && oldState->down) {
2450 if (DEBUG_FOCUS) {
2451 ALOGD("Conflicting pointer actions: Down received while already down.");
2452 }
2453 *outConflictingPointerActions = true;
2454 }
2455 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2456 // One pointer went up.
2457 if (isSplit) {
2458 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2459 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002461 for (size_t i = 0; i < tempTouchState.windows.size();) {
2462 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2463 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2464 touchedWindow.pointerIds.clearBit(pointerId);
2465 if (touchedWindow.pointerIds.isEmpty()) {
2466 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2467 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002470 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002472 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002473 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002474
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002475 // Save changes unless the action was scroll in which case the temporary touch
2476 // state was only valid for this one action.
2477 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2478 if (tempTouchState.displayId >= 0) {
2479 mTouchStatesByDisplay[displayId] = tempTouchState;
2480 } else {
2481 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002485 // Update hover state.
2486 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 }
2488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 return injectionResult;
2490}
2491
arthurhung6d4bed92021-03-17 11:59:33 +08002492void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002493 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2494 // have an explicit reason to support it.
2495 constexpr bool isStylus = false;
2496
chaviw98318de2021-05-19 16:45:23 -05002497 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002498 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002499 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002500 if (dropWindow) {
2501 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002502 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002503 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002504 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002505 }
2506 mDragState.reset();
2507}
2508
2509void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2510 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002511 return;
2512 }
2513
arthurhung6d4bed92021-03-17 11:59:33 +08002514 if (!mDragState->isStartDrag) {
2515 mDragState->isStartDrag = true;
2516 mDragState->isStylusButtonDownAtStart =
2517 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2518 }
2519
arthurhungb89ccb02020-12-30 16:19:01 +08002520 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2521 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2522 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2523 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002524 // Handle the special case : stylus button no longer pressed.
2525 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2526 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2527 finishDragAndDrop(entry.displayId, x, y);
2528 return;
2529 }
2530
Prabir Pradhand65552b2021-10-07 11:23:50 -07002531 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2532 // we have an explicit reason to support it.
2533 constexpr bool isStylus = false;
2534
chaviw98318de2021-05-19 16:45:23 -05002535 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002536 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002537 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002538 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002539 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2540 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2541 if (mDragState->dragHoverWindowHandle != nullptr) {
2542 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2543 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002544 }
arthurhung6d4bed92021-03-17 11:59:33 +08002545 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002546 }
2547 // enqueue drag location if needed.
2548 if (hoverWindowHandle != nullptr) {
2549 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2550 }
arthurhung6d4bed92021-03-17 11:59:33 +08002551 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2552 finishDragAndDrop(entry.displayId, x, y);
2553 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002554 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002555 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002556 }
2557}
2558
chaviw98318de2021-05-19 16:45:23 -05002559void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 int32_t targetFlags, BitSet32 pointerIds,
2561 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002562 std::vector<InputTarget>::iterator it =
2563 std::find_if(inputTargets.begin(), inputTargets.end(),
2564 [&windowHandle](const InputTarget& inputTarget) {
2565 return inputTarget.inputChannel->getConnectionToken() ==
2566 windowHandle->getToken();
2567 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002568
chaviw98318de2021-05-19 16:45:23 -05002569 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002570
2571 if (it == inputTargets.end()) {
2572 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002573 std::shared_ptr<InputChannel> inputChannel =
2574 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002575 if (inputChannel == nullptr) {
2576 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2577 return;
2578 }
2579 inputTarget.inputChannel = inputChannel;
2580 inputTarget.flags = targetFlags;
2581 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002582 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2583 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002584 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002585 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002586 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002587 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002588 inputTargets.push_back(inputTarget);
2589 it = inputTargets.end() - 1;
2590 }
2591
2592 ALOG_ASSERT(it->flags == targetFlags);
2593 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2594
chaviw1ff3d1e2020-07-01 15:53:47 -07002595 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596}
2597
Michael Wright3dd60e22019-03-27 22:06:44 +00002598void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002599 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002600 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2601 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002602
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002603 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2604 InputTarget target;
2605 target.inputChannel = monitor.inputChannel;
2606 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2607 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2608 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002609 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002610 target.setDefaultPointerTransform(target.displayTransform);
2611 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 }
2613}
2614
chaviw98318de2021-05-19 16:45:23 -05002615bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002616 const InjectionState* injectionState) {
2617 if (injectionState &&
2618 (windowHandle == nullptr ||
2619 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2620 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002621 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 "owned by uid %d",
2624 injectionState->injectorPid, injectionState->injectorUid,
2625 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 } else {
2627 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 }
2630 return false;
2631 }
2632 return true;
2633}
2634
Robert Carrc9bf1d32020-04-13 17:21:08 -07002635/**
2636 * Indicate whether one window handle should be considered as obscuring
2637 * another window handle. We only check a few preconditions. Actually
2638 * checking the bounds is left to the caller.
2639 */
chaviw98318de2021-05-19 16:45:23 -05002640static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2641 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002642 // Compare by token so cloned layers aren't counted
2643 if (haveSameToken(windowHandle, otherHandle)) {
2644 return false;
2645 }
2646 auto info = windowHandle->getInfo();
2647 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002648 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002649 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002650 } else if (otherInfo->alpha == 0 &&
2651 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002652 // Those act as if they were invisible, so we don't need to flag them.
2653 // We do want to potentially flag touchable windows even if they have 0
2654 // opacity, since they can consume touches and alter the effects of the
2655 // user interaction (eg. apps that rely on
2656 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2657 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2658 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002659 } else if (info->ownerUid == otherInfo->ownerUid) {
2660 // If ownerUid is the same we don't generate occlusion events as there
2661 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002662 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002663 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002664 return false;
2665 } else if (otherInfo->displayId != info->displayId) {
2666 return false;
2667 }
2668 return true;
2669}
2670
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002671/**
2672 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2673 * untrusted, one should check:
2674 *
2675 * 1. If result.hasBlockingOcclusion is true.
2676 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2677 * BLOCK_UNTRUSTED.
2678 *
2679 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2680 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2681 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2682 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2683 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2684 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2685 *
2686 * If neither of those is true, then it means the touch can be allowed.
2687 */
2688InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002689 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2690 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002691 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002692 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002693 TouchOcclusionInfo info;
2694 info.hasBlockingOcclusion = false;
2695 info.obscuringOpacity = 0;
2696 info.obscuringUid = -1;
2697 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002698 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002699 if (windowHandle == otherHandle) {
2700 break; // All future windows are below us. Exit early.
2701 }
chaviw98318de2021-05-19 16:45:23 -05002702 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002703 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2704 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002705 if (DEBUG_TOUCH_OCCLUSION) {
2706 info.debugInfo.push_back(
2707 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2708 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002709 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2710 // we perform the checks below to see if the touch can be propagated or not based on the
2711 // window's touch occlusion mode
2712 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2713 info.hasBlockingOcclusion = true;
2714 info.obscuringUid = otherInfo->ownerUid;
2715 info.obscuringPackage = otherInfo->packageName;
2716 break;
2717 }
2718 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2719 uint32_t uid = otherInfo->ownerUid;
2720 float opacity =
2721 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2722 // Given windows A and B:
2723 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2724 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2725 opacityByUid[uid] = opacity;
2726 if (opacity > info.obscuringOpacity) {
2727 info.obscuringOpacity = opacity;
2728 info.obscuringUid = uid;
2729 info.obscuringPackage = otherInfo->packageName;
2730 }
2731 }
2732 }
2733 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002734 if (DEBUG_TOUCH_OCCLUSION) {
2735 info.debugInfo.push_back(
2736 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2737 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002738 return info;
2739}
2740
chaviw98318de2021-05-19 16:45:23 -05002741std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002742 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002743 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2744 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2745 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2746 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002747 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2748 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2749 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2750 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2751 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002752 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002753 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002754}
2755
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002756bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2757 if (occlusionInfo.hasBlockingOcclusion) {
2758 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2759 occlusionInfo.obscuringUid);
2760 return false;
2761 }
2762 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2763 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2764 "%.2f, maximum allowed = %.2f)",
2765 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2766 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2767 return false;
2768 }
2769 return true;
2770}
2771
chaviw98318de2021-05-19 16:45:23 -05002772bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002775 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2776 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002777 if (windowHandle == otherHandle) {
2778 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
chaviw98318de2021-05-19 16:45:23 -05002780 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002781 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002782 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 return true;
2784 }
2785 }
2786 return false;
2787}
2788
chaviw98318de2021-05-19 16:45:23 -05002789bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002790 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002791 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2792 const WindowInfo* windowInfo = windowHandle->getInfo();
2793 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002794 if (windowHandle == otherHandle) {
2795 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002796 }
chaviw98318de2021-05-19 16:45:23 -05002797 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002798 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002799 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002800 return true;
2801 }
2802 }
2803 return false;
2804}
2805
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002806std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002807 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002808 if (applicationHandle != nullptr) {
2809 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002810 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 } else {
2812 return applicationHandle->getName();
2813 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002814 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002815 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002817 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
2819}
2820
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002821void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002822 if (!isUserActivityEvent(eventEntry)) {
2823 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002824 return;
2825 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002826 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002827 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002828 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002829 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002830 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002831 if (DEBUG_DISPATCH_CYCLE) {
2832 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 return;
2835 }
2836 }
2837
2838 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002839 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002840 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002841 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2842 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 return;
2844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002846 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 eventType = USER_ACTIVITY_EVENT_TOUCH;
2848 }
2849 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002851 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002852 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2853 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 return;
2855 }
2856 eventType = USER_ACTIVITY_EVENT_BUTTON;
2857 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002859 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002860 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002861 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002862 break;
2863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
2865
Prabir Pradhancef936d2021-07-21 16:17:52 +00002866 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2867 REQUIRES(mLock) {
2868 scoped_unlock unlock(mLock);
2869 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2870 };
2871 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872}
2873
2874void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002877 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002878 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002880 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002881 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002882 ATRACE_NAME(message.c_str());
2883 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002884 if (DEBUG_DISPATCH_CYCLE) {
2885 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2886 "globalScaleFactor=%f, pointerIds=0x%x %s",
2887 connection->getInputChannelName().c_str(), inputTarget.flags,
2888 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2889 inputTarget.getPointerInfoString().c_str());
2890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891
2892 // Skip this event if the connection status is not normal.
2893 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002894 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002895 if (DEBUG_DISPATCH_CYCLE) {
2896 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002897 connection->getInputChannelName().c_str(),
2898 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 return;
2901 }
2902
2903 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002904 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2905 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2906 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002907 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002909 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002910 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002911 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002912 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 if (!splitMotionEntry) {
2914 return; // split event was dropped
2915 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002916 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2917 std::string reason = std::string("reason=pointer cancel on split window");
2918 android_log_event_list(LOGTAG_INPUT_CANCEL)
2919 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2920 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002921 if (DEBUG_FOCUS) {
2922 ALOGD("channel '%s' ~ Split motion event.",
2923 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002924 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002925 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002926 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2927 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 return;
2929 }
2930 }
2931
2932 // Not splitting. Enqueue dispatch entries for the event as is.
2933 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2934}
2935
2936void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002937 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002938 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002939 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002940 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002942 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002943 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002944 ATRACE_NAME(message.c_str());
2945 }
2946
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002947 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
2949 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002950 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002952 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002954 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002956 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002958 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002960 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962
2963 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002964 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 startDispatchCycleLocked(currentTime, connection);
2966 }
2967}
2968
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002970 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002971 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002973 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2975 connection->getInputChannelName().c_str(),
2976 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002977 ATRACE_NAME(message.c_str());
2978 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002979 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 if (!(inputTargetFlags & dispatchMode)) {
2981 return;
2982 }
2983 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2984
2985 // This is a new event.
2986 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002987 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002988 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002990 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2991 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002992 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002994 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002995 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002996 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002997 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998 dispatchEntry->resolvedAction = keyEntry.action;
2999 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3002 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003003 if (DEBUG_DISPATCH_CYCLE) {
3004 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3005 "event",
3006 connection->getInputChannelName().c_str());
3007 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 return; // skip the inconsistent event
3009 }
3010 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003013 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003014 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003015 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3016 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3017 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3018 static_cast<int32_t>(IdGenerator::Source::OTHER);
3019 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003020 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3021 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3022 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3023 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3024 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3025 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3026 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3027 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3028 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3029 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3030 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003031 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003032 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003033 }
3034 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003035 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3036 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003037 if (DEBUG_DISPATCH_CYCLE) {
3038 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3039 "enter event",
3040 connection->getInputChannelName().c_str());
3041 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003042 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3043 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003047 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3049 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3050 }
3051 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3052 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3056 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003057 if (DEBUG_DISPATCH_CYCLE) {
3058 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3059 "event",
3060 connection->getInputChannelName().c_str());
3061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 return; // skip the inconsistent event
3063 }
3064
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003065 dispatchEntry->resolvedEventId =
3066 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3067 ? mIdGenerator.nextId()
3068 : motionEntry.id;
3069 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3070 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3071 ") to MotionEvent(id=0x%" PRIx32 ").",
3072 motionEntry.id, dispatchEntry->resolvedEventId);
3073 ATRACE_NAME(message.c_str());
3074 }
3075
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003076 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3077 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3078 // Skip reporting pointer down outside focus to the policy.
3079 break;
3080 }
3081
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003082 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003083 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084
3085 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003087 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003088 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003089 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3090 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003091 break;
3092 }
Chris Yef59a2f42020-10-16 12:55:26 -07003093 case EventEntry::Type::SENSOR: {
3094 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3095 break;
3096 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003097 case EventEntry::Type::CONFIGURATION_CHANGED:
3098 case EventEntry::Type::DEVICE_RESET: {
3099 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003100 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003101 break;
3102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
3104
3105 // Remember that we are waiting for this dispatch to complete.
3106 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003107 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 }
3109
3110 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003111 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003112 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003113}
3114
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003115/**
3116 * This function is purely for debugging. It helps us understand where the user interaction
3117 * was taking place. For example, if user is touching launcher, we will see a log that user
3118 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3119 * We will see both launcher and wallpaper in that list.
3120 * Once the interaction with a particular set of connections starts, no new logs will be printed
3121 * until the set of interacted connections changes.
3122 *
3123 * The following items are skipped, to reduce the logspam:
3124 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3125 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3126 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3127 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3128 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003129 */
3130void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3131 const std::vector<InputTarget>& targets) {
3132 // Skip ACTION_UP events, and all events other than keys and motions
3133 if (entry.type == EventEntry::Type::KEY) {
3134 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3135 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3136 return;
3137 }
3138 } else if (entry.type == EventEntry::Type::MOTION) {
3139 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3140 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3141 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3142 return;
3143 }
3144 } else {
3145 return; // Not a key or a motion
3146 }
3147
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003148 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003149 std::vector<sp<Connection>> newConnections;
3150 for (const InputTarget& target : targets) {
3151 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3152 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3153 continue; // Skip windows that receive ACTION_OUTSIDE
3154 }
3155
3156 sp<IBinder> token = target.inputChannel->getConnectionToken();
3157 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003158 if (connection == nullptr) {
3159 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003160 }
3161 newConnectionTokens.insert(std::move(token));
3162 newConnections.emplace_back(connection);
3163 }
3164 if (newConnectionTokens == mInteractionConnectionTokens) {
3165 return; // no change
3166 }
3167 mInteractionConnectionTokens = newConnectionTokens;
3168
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003169 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003170 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003171 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003172 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003173 std::string message = "Interaction with: " + targetList;
3174 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003175 message += "<none>";
3176 }
3177 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3178}
3179
chaviwfd6d3512019-03-25 13:23:49 -07003180void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003181 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003182 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003183 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3184 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003185 return;
3186 }
3187
Vishnu Nairc519ff72021-01-21 08:23:08 -08003188 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003189 if (focusedToken == token) {
3190 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003191 return;
3192 }
3193
Prabir Pradhancef936d2021-07-21 16:17:52 +00003194 auto command = [this, token]() REQUIRES(mLock) {
3195 scoped_unlock unlock(mLock);
3196 mPolicy->onPointerDownOutsideFocus(token);
3197 };
3198 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199}
3200
3201void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003203 if (ATRACE_ENABLED()) {
3204 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003206 ATRACE_NAME(message.c_str());
3207 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003208 if (DEBUG_DISPATCH_CYCLE) {
3209 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003212 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003213 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003215 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003216 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217
3218 // Publish the event.
3219 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003220 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3221 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003222 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003223 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3224 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003227 status = connection->inputPublisher
3228 .publishKeyEvent(dispatchEntry->seq,
3229 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3230 keyEntry.source, keyEntry.displayId,
3231 std::move(hmac), dispatchEntry->resolvedAction,
3232 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3233 keyEntry.scanCode, keyEntry.metaState,
3234 keyEntry.repeatCount, keyEntry.downTime,
3235 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 }
3238
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003239 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003243 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244
chaviw82357092020-01-28 13:13:06 -08003245 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003246 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3248 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003249 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3251 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003252 // Don't apply window scale here since we don't want scale to affect raw
3253 // coordinates. The scale will be sent back to the client and applied
3254 // later when requesting relative coordinates.
3255 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3256 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 }
3258 usingCoords = scaledCoords;
3259 }
3260 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 // We don't want the dispatch target to know.
3262 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003263 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 scaledCoords[i].clear();
3265 }
3266 usingCoords = scaledCoords;
3267 }
3268 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003270 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271
3272 // Publish the motion event.
3273 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003274 .publishMotionEvent(dispatchEntry->seq,
3275 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003276 motionEntry.deviceId, motionEntry.source,
3277 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003278 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003279 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003281 motionEntry.edgeFlags, motionEntry.metaState,
3282 motionEntry.buttonState,
3283 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003284 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 motionEntry.xPrecision, motionEntry.yPrecision,
3286 motionEntry.xCursorPosition,
3287 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003288 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003289 motionEntry.downTime, motionEntry.eventTime,
3290 motionEntry.pointerCount,
3291 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 break;
3293 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003294
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003295 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003297 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003298 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003299 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003300 break;
3301 }
3302
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003303 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3304 const TouchModeEntry& touchModeEntry =
3305 static_cast<const TouchModeEntry&>(eventEntry);
3306 status = connection->inputPublisher
3307 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3308 touchModeEntry.inTouchMode);
3309
3310 break;
3311 }
3312
Prabir Pradhan99987712020-11-10 18:43:05 -08003313 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3314 const auto& captureEntry =
3315 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3316 status = connection->inputPublisher
3317 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003318 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003319 break;
3320 }
3321
arthurhungb89ccb02020-12-30 16:19:01 +08003322 case EventEntry::Type::DRAG: {
3323 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3324 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3325 dragEntry.id, dragEntry.x,
3326 dragEntry.y,
3327 dragEntry.isExiting);
3328 break;
3329 }
3330
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003331 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003332 case EventEntry::Type::DEVICE_RESET:
3333 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003334 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003335 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 }
3339
3340 // Check the result.
3341 if (status) {
3342 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003343 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003345 "This is unexpected because the wait queue is empty, so the pipe "
3346 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003347 "event to it, status=%s(%d)",
3348 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3349 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3351 } else {
3352 // Pipe is full and we are waiting for the app to finish process some events
3353 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003354 if (DEBUG_DISPATCH_CYCLE) {
3355 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3356 "waiting for the application to catch up",
3357 connection->getInputChannelName().c_str());
3358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 }
3360 } else {
3361 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003362 "status=%s(%d)",
3363 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3364 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3366 }
3367 return;
3368 }
3369
3370 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003371 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3372 connection->outboundQueue.end(),
3373 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003374 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003375 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003376 if (connection->responsive) {
3377 mAnrTracker.insert(dispatchEntry->timeoutTime,
3378 connection->inputChannel->getConnectionToken());
3379 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003380 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
3382}
3383
chaviw09c8d2d2020-08-24 15:48:26 -07003384std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3385 size_t size;
3386 switch (event.type) {
3387 case VerifiedInputEvent::Type::KEY: {
3388 size = sizeof(VerifiedKeyEvent);
3389 break;
3390 }
3391 case VerifiedInputEvent::Type::MOTION: {
3392 size = sizeof(VerifiedMotionEvent);
3393 break;
3394 }
3395 }
3396 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3397 return mHmacKeyManager.sign(start, size);
3398}
3399
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003400const std::array<uint8_t, 32> InputDispatcher::getSignature(
3401 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003402 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3403 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003404 // Only sign events up and down events as the purely move events
3405 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003406 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003407 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003408
3409 VerifiedMotionEvent verifiedEvent =
3410 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3411 verifiedEvent.actionMasked = actionMasked;
3412 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3413 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003414}
3415
3416const std::array<uint8_t, 32> InputDispatcher::getSignature(
3417 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3418 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3419 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3420 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003421 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003422}
3423
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003425 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003426 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003427 if (DEBUG_DISPATCH_CYCLE) {
3428 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3429 connection->getInputChannelName().c_str(), seq, toString(handled));
3430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003432 if (connection->status == Connection::Status::BROKEN ||
3433 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 return;
3435 }
3436
3437 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003438 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3439 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3440 };
3441 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442}
3443
3444void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 const sp<Connection>& connection,
3446 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003447 if (DEBUG_DISPATCH_CYCLE) {
3448 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3449 connection->getInputChannelName().c_str(), toString(notify));
3450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
3452 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003453 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003454 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003455 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003456 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457
3458 // The connection appears to be unrecoverably broken.
3459 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003460 if (connection->status == Connection::Status::NORMAL) {
3461 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462
3463 if (notify) {
3464 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003465 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3466 connection->getInputChannelName().c_str());
3467
3468 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003469 scoped_unlock unlock(mLock);
3470 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3471 };
3472 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 }
3474 }
3475}
3476
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003477void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3478 while (!queue.empty()) {
3479 DispatchEntry* dispatchEntry = queue.front();
3480 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003481 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
3483}
3484
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003485void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003487 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 }
3489 delete dispatchEntry;
3490}
3491
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003492int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3493 std::scoped_lock _l(mLock);
3494 sp<Connection> connection = getConnectionLocked(connectionToken);
3495 if (connection == nullptr) {
3496 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3497 connectionToken.get(), events);
3498 return 0; // remove the callback
3499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003501 bool notify;
3502 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3503 if (!(events & ALOOPER_EVENT_INPUT)) {
3504 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3505 "events=0x%x",
3506 connection->getInputChannelName().c_str(), events);
3507 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
3509
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003510 nsecs_t currentTime = now();
3511 bool gotOne = false;
3512 status_t status = OK;
3513 for (;;) {
3514 Result<InputPublisher::ConsumerResponse> result =
3515 connection->inputPublisher.receiveConsumerResponse();
3516 if (!result.ok()) {
3517 status = result.error().code();
3518 break;
3519 }
3520
3521 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3522 const InputPublisher::Finished& finish =
3523 std::get<InputPublisher::Finished>(*result);
3524 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3525 finish.consumeTime);
3526 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003527 if (shouldReportMetricsForConnection(*connection)) {
3528 const InputPublisher::Timeline& timeline =
3529 std::get<InputPublisher::Timeline>(*result);
3530 mLatencyTracker
3531 .trackGraphicsLatency(timeline.inputEventId,
3532 connection->inputChannel->getConnectionToken(),
3533 std::move(timeline.graphicsTimeline));
3534 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003535 }
3536 gotOne = true;
3537 }
3538 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003539 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003540 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 return 1;
3542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003545 notify = status != DEAD_OBJECT || !connection->monitor;
3546 if (notify) {
3547 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3548 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3549 status);
3550 }
3551 } else {
3552 // Monitor channels are never explicitly unregistered.
3553 // We do it automatically when the remote endpoint is closed so don't warn about them.
3554 const bool stillHaveWindowHandle =
3555 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3556 notify = !connection->monitor && stillHaveWindowHandle;
3557 if (notify) {
3558 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3559 connection->getInputChannelName().c_str(), events);
3560 }
3561 }
3562
3563 // Remove the channel.
3564 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3565 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566}
3567
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003568void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003570 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003571 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 }
3573}
3574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003575void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003576 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003577 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003578 for (const Monitor& monitor : monitors) {
3579 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003580 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003581 }
3582}
3583
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003585 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003586 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003587 if (connection == nullptr) {
3588 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003590
3591 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592}
3593
3594void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3595 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003596 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 return;
3598 }
3599
3600 nsecs_t currentTime = now();
3601
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003603 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003605 if (cancelationEvents.empty()) {
3606 return;
3607 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003608 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3609 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3610 "with reality: %s, mode=%d.",
3611 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3612 options.mode);
3613 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003614
Arthur Hungb3307ee2021-10-14 10:57:37 +00003615 std::string reason = std::string("reason=").append(options.reason);
3616 android_log_event_list(LOGTAG_INPUT_CANCEL)
3617 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3618
Svet Ganov5d3bc372020-01-26 23:11:07 -08003619 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003620 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003621 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3622 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003623 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003624 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003625 target.globalScaleFactor = windowInfo->globalScaleFactor;
3626 }
3627 target.inputChannel = connection->inputChannel;
3628 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3629
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003630 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003631 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003632 switch (cancelationEventEntry->type) {
3633 case EventEntry::Type::KEY: {
3634 logOutboundKeyDetails("cancel - ",
3635 static_cast<const KeyEntry&>(*cancelationEventEntry));
3636 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003638 case EventEntry::Type::MOTION: {
3639 logOutboundMotionDetails("cancel - ",
3640 static_cast<const MotionEntry&>(*cancelationEventEntry));
3641 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003643 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003644 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003645 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3646 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003647 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003648 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003649 break;
3650 }
3651 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003652 case EventEntry::Type::DEVICE_RESET:
3653 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003654 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003655 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003656 break;
3657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 }
3659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3661 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003663
3664 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665}
3666
Svet Ganov5d3bc372020-01-26 23:11:07 -08003667void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3668 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003669 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 return;
3671 }
3672
3673 nsecs_t currentTime = now();
3674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 connection->inputState.synthesizePointerDownEvents(currentTime);
3677
3678 if (downEvents.empty()) {
3679 return;
3680 }
3681
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003682 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003683 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3684 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003685 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003686
3687 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003688 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003689 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3690 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003691 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003692 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003693 target.globalScaleFactor = windowInfo->globalScaleFactor;
3694 }
3695 target.inputChannel = connection->inputChannel;
3696 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3697
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003698 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003699 switch (downEventEntry->type) {
3700 case EventEntry::Type::MOTION: {
3701 logOutboundMotionDetails("down - ",
3702 static_cast<const MotionEntry&>(*downEventEntry));
3703 break;
3704 }
3705
3706 case EventEntry::Type::KEY:
3707 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003708 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003709 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003710 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003711 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003712 case EventEntry::Type::SENSOR:
3713 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003714 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003715 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 break;
3717 }
3718 }
3719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003720 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3721 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003722 }
3723
3724 startDispatchCycleLocked(currentTime, connection);
3725}
3726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003727std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3728 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 ALOG_ASSERT(pointerIds.value != 0);
3730
3731 uint32_t splitPointerIndexMap[MAX_POINTERS];
3732 PointerProperties splitPointerProperties[MAX_POINTERS];
3733 PointerCoords splitPointerCoords[MAX_POINTERS];
3734
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003735 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 uint32_t splitPointerCount = 0;
3737
3738 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003741 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 uint32_t pointerId = uint32_t(pointerProperties.id);
3743 if (pointerIds.hasBit(pointerId)) {
3744 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3745 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3746 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003747 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 splitPointerCount += 1;
3749 }
3750 }
3751
3752 if (splitPointerCount != pointerIds.count()) {
3753 // This is bad. We are missing some of the pointers that we expected to deliver.
3754 // Most likely this indicates that we received an ACTION_MOVE events that has
3755 // different pointer ids than we expected based on the previous ACTION_DOWN
3756 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3757 // in this way.
3758 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003759 "we expected there to be %d pointers. This probably means we received "
3760 "a broken sequence of pointer ids from the input device.",
3761 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003762 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 }
3764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003765 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003767 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3768 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3770 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003771 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 uint32_t pointerId = uint32_t(pointerProperties.id);
3773 if (pointerIds.hasBit(pointerId)) {
3774 if (pointerIds.count() == 1) {
3775 // The first/last pointer went down/up.
3776 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003778 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3779 ? AMOTION_EVENT_ACTION_CANCEL
3780 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 } else {
3782 // A secondary pointer went down/up.
3783 uint32_t splitPointerIndex = 0;
3784 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3785 splitPointerIndex += 1;
3786 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 action = maskedAction |
3788 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 }
3790 } else {
3791 // An unrelated pointer changed.
3792 action = AMOTION_EVENT_ACTION_MOVE;
3793 }
3794 }
3795
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003796 int32_t newId = mIdGenerator.nextId();
3797 if (ATRACE_ENABLED()) {
3798 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3799 ") to MotionEvent(id=0x%" PRIx32 ").",
3800 originalMotionEntry.id, newId);
3801 ATRACE_NAME(message.c_str());
3802 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003803 std::unique_ptr<MotionEntry> splitMotionEntry =
3804 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3805 originalMotionEntry.deviceId, originalMotionEntry.source,
3806 originalMotionEntry.displayId,
3807 originalMotionEntry.policyFlags, action,
3808 originalMotionEntry.actionButton,
3809 originalMotionEntry.flags, originalMotionEntry.metaState,
3810 originalMotionEntry.buttonState,
3811 originalMotionEntry.classification,
3812 originalMotionEntry.edgeFlags,
3813 originalMotionEntry.xPrecision,
3814 originalMotionEntry.yPrecision,
3815 originalMotionEntry.xCursorPosition,
3816 originalMotionEntry.yCursorPosition,
3817 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003818 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003820 if (originalMotionEntry.injectionState) {
3821 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 splitMotionEntry->injectionState->refCount += 1;
3823 }
3824
3825 return splitMotionEntry;
3826}
3827
3828void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003829 if (DEBUG_INBOUND_EVENT_DETAILS) {
3830 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
Antonio Kantekf16f2832021-09-28 04:39:20 +00003833 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003835 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003837 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3838 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3839 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 } // release lock
3841
3842 if (needWake) {
3843 mLooper->wake();
3844 }
3845}
3846
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003847/**
3848 * If one of the meta shortcuts is detected, process them here:
3849 * Meta + Backspace -> generate BACK
3850 * Meta + Enter -> generate HOME
3851 * This will potentially overwrite keyCode and metaState.
3852 */
3853void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003855 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3856 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3857 if (keyCode == AKEYCODE_DEL) {
3858 newKeyCode = AKEYCODE_BACK;
3859 } else if (keyCode == AKEYCODE_ENTER) {
3860 newKeyCode = AKEYCODE_HOME;
3861 }
3862 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003863 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003864 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003865 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003866 keyCode = newKeyCode;
3867 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3868 }
3869 } else if (action == AKEY_EVENT_ACTION_UP) {
3870 // In order to maintain a consistent stream of up and down events, check to see if the key
3871 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3872 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003873 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003874 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003875 auto replacementIt = mReplacedKeys.find(replacement);
3876 if (replacementIt != mReplacedKeys.end()) {
3877 keyCode = replacementIt->second;
3878 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003879 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3880 }
3881 }
3882}
3883
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003885 if (DEBUG_INBOUND_EVENT_DETAILS) {
3886 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3887 "policyFlags=0x%x, action=0x%x, "
3888 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3889 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3890 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3891 args->downTime);
3892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 if (!validateKeyEvent(args->action)) {
3894 return;
3895 }
3896
3897 uint32_t policyFlags = args->policyFlags;
3898 int32_t flags = args->flags;
3899 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003900 // InputDispatcher tracks and generates key repeats on behalf of
3901 // whatever notifies it, so repeatCount should always be set to 0
3902 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3904 policyFlags |= POLICY_FLAG_VIRTUAL;
3905 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 if (policyFlags & POLICY_FLAG_FUNCTION) {
3908 metaState |= AMETA_FUNCTION_ON;
3909 }
3910
3911 policyFlags |= POLICY_FLAG_TRUSTED;
3912
Michael Wright78f24442014-08-06 15:55:28 -07003913 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003914 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003915
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003917 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003918 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3919 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920
Michael Wright2b3c3302018-03-02 17:19:13 +00003921 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003923 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3924 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
Antonio Kantekf16f2832021-09-28 04:39:20 +00003928 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 { // acquire lock
3930 mLock.lock();
3931
3932 if (shouldSendKeyToInputFilterLocked(args)) {
3933 mLock.unlock();
3934
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003935 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3937 return; // event was consumed by the filter
3938 }
3939
3940 mLock.lock();
3941 }
3942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003943 std::unique_ptr<KeyEntry> newEntry =
3944 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3945 args->displayId, policyFlags, args->action, flags,
3946 keyCode, args->scanCode, metaState, repeatCount,
3947 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003949 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 mLock.unlock();
3951 } // release lock
3952
3953 if (needWake) {
3954 mLooper->wake();
3955 }
3956}
3957
3958bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3959 return mInputFilterEnabled;
3960}
3961
3962void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003963 if (DEBUG_INBOUND_EVENT_DETAILS) {
3964 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3965 "displayId=%" PRId32 ", policyFlags=0x%x, "
3966 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3967 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3968 "yCursorPosition=%f, downTime=%" PRId64,
3969 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3970 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3971 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3972 args->xCursorPosition, args->yCursorPosition, args->downTime);
3973 for (uint32_t i = 0; i < args->pointerCount; i++) {
3974 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3975 "x=%f, y=%f, pressure=%f, size=%f, "
3976 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3977 "orientation=%f",
3978 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3979 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3980 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3981 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3982 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3983 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3984 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3985 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3986 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3987 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3991 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 return;
3993 }
3994
3995 uint32_t policyFlags = args->policyFlags;
3996 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003997
3998 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003999 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004000 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4001 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004002 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Antonio Kantekf16f2832021-09-28 04:39:20 +00004005 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 { // acquire lock
4007 mLock.lock();
4008
4009 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004010 ui::Transform displayTransform;
4011 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4012 displayTransform = it->second.transform;
4013 }
4014
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 mLock.unlock();
4016
4017 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004018 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4019 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004020 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004021 displayTransform, args->xPrecision, args->yPrecision,
4022 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004023 args->downTime, args->eventTime, args->pointerCount,
4024 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
4026 policyFlags |= POLICY_FLAG_FILTERED;
4027 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4028 return; // event was consumed by the filter
4029 }
4030
4031 mLock.lock();
4032 }
4033
4034 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004035 std::unique_ptr<MotionEntry> newEntry =
4036 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4037 args->source, args->displayId, policyFlags,
4038 args->action, args->actionButton, args->flags,
4039 args->metaState, args->buttonState,
4040 args->classification, args->edgeFlags,
4041 args->xPrecision, args->yPrecision,
4042 args->xCursorPosition, args->yCursorPosition,
4043 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004044 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004046 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4047 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4048 !mInputFilterEnabled) {
4049 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4050 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4051 }
4052
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004053 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 mLock.unlock();
4055 } // release lock
4056
4057 if (needWake) {
4058 mLooper->wake();
4059 }
4060}
4061
Chris Yef59a2f42020-10-16 12:55:26 -07004062void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004063 if (DEBUG_INBOUND_EVENT_DETAILS) {
4064 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4065 " sensorType=%s",
4066 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004067 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004068 }
Chris Yef59a2f42020-10-16 12:55:26 -07004069
Antonio Kantekf16f2832021-09-28 04:39:20 +00004070 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004071 { // acquire lock
4072 mLock.lock();
4073
4074 // Just enqueue a new sensor event.
4075 std::unique_ptr<SensorEntry> newEntry =
4076 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4077 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4078 args->sensorType, args->accuracy,
4079 args->accuracyChanged, args->values);
4080
4081 needWake = enqueueInboundEventLocked(std::move(newEntry));
4082 mLock.unlock();
4083 } // release lock
4084
4085 if (needWake) {
4086 mLooper->wake();
4087 }
4088}
4089
Chris Yefb552902021-02-03 17:18:37 -08004090void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004091 if (DEBUG_INBOUND_EVENT_DETAILS) {
4092 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4093 args->deviceId, args->isOn);
4094 }
Chris Yefb552902021-02-03 17:18:37 -08004095 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4096}
4097
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004099 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100}
4101
4102void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004103 if (DEBUG_INBOUND_EVENT_DETAILS) {
4104 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4105 "switchMask=0x%08x",
4106 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108
4109 uint32_t policyFlags = args->policyFlags;
4110 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004111 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112}
4113
4114void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004115 if (DEBUG_INBOUND_EVENT_DETAILS) {
4116 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4117 args->deviceId);
4118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
Antonio Kantekf16f2832021-09-28 04:39:20 +00004120 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004122 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004124 std::unique_ptr<DeviceResetEntry> newEntry =
4125 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4126 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 } // release lock
4128
4129 if (needWake) {
4130 mLooper->wake();
4131 }
4132}
4133
Prabir Pradhan7e186182020-11-10 13:56:45 -08004134void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004135 if (DEBUG_INBOUND_EVENT_DETAILS) {
4136 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004137 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004138 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004139
Antonio Kantekf16f2832021-09-28 04:39:20 +00004140 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004141 { // acquire lock
4142 std::scoped_lock _l(mLock);
4143 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004144 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004145 needWake = enqueueInboundEventLocked(std::move(entry));
4146 } // release lock
4147
4148 if (needWake) {
4149 mLooper->wake();
4150 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004151}
4152
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004153InputEventInjectionResult InputDispatcher::injectInputEvent(
4154 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4155 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004156 if (DEBUG_INBOUND_EVENT_DETAILS) {
4157 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4158 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4159 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4160 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004161 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
4163 policyFlags |= POLICY_FLAG_INJECTED;
4164 if (hasInjectionPermission(injectorPid, injectorUid)) {
4165 policyFlags |= POLICY_FLAG_TRUSTED;
4166 }
4167
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004168 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004169 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4170 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4171 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4172 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4173 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004174 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004175 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004177 }
4178
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004182 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4183 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004185 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004188 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004189 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4190 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4191 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004192 int32_t keyCode = incomingKey.getKeyCode();
4193 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004194 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004196 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004197 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004198 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4199 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4200 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4203 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004204 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205
4206 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4207 android::base::Timer t;
4208 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4209 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4210 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4211 std::to_string(t.duration().count()).c_str());
4212 }
4213 }
4214
4215 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004216 std::unique_ptr<KeyEntry> injectedEntry =
4217 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004218 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004219 incomingKey.getDisplayId(), policyFlags, action,
4220 flags, keyCode, incomingKey.getScanCode(), metaState,
4221 incomingKey.getRepeatCount(),
4222 incomingKey.getDownTime());
4223 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 }
4226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004229 const int32_t action = motionEvent.getAction();
4230 const bool isPointerEvent =
4231 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4232 // If a pointer event has no displayId specified, inject it to the default display.
4233 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4234 ? ADISPLAY_ID_DEFAULT
4235 : event->getDisplayId();
4236 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004238 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004239 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004241 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 }
4243
4244 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004245 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 android::base::Timer t;
4247 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4248 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4249 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4250 std::to_string(t.duration().count()).c_str());
4251 }
4252 }
4253
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004254 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4255 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4256 }
4257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004259 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4260 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004261 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4263 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004264 displayId, policyFlags, action, actionButton,
4265 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004266 motionEvent.getButtonState(),
4267 motionEvent.getClassification(),
4268 motionEvent.getEdgeFlags(),
4269 motionEvent.getXPrecision(),
4270 motionEvent.getYPrecision(),
4271 motionEvent.getRawXCursorPosition(),
4272 motionEvent.getRawYCursorPosition(),
4273 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004274 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004275 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004277 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 sampleEventTimes += 1;
4279 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004280 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004281 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4282 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004283 displayId, policyFlags, action, actionButton,
4284 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004285 motionEvent.getButtonState(),
4286 motionEvent.getClassification(),
4287 motionEvent.getEdgeFlags(),
4288 motionEvent.getXPrecision(),
4289 motionEvent.getYPrecision(),
4290 motionEvent.getRawXCursorPosition(),
4291 motionEvent.getRawYCursorPosition(),
4292 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004293 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004294 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004295 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4296 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004297 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004298 }
4299 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004302 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004303 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004304 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 }
4306
4307 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004308 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 injectionState->injectionIsAsync = true;
4310 }
4311
4312 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004313 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314
4315 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004316 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004317 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004318 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 }
4320
4321 mLock.unlock();
4322
4323 if (needWake) {
4324 mLooper->wake();
4325 }
4326
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004327 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004329 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004331 if (syncMode == InputEventInjectionSync::NONE) {
4332 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 } else {
4334 for (;;) {
4335 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004336 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 break;
4338 }
4339
4340 nsecs_t remainingTimeout = endTime - now();
4341 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004342 if (DEBUG_INJECTION) {
4343 ALOGD("injectInputEvent - Timed out waiting for injection result "
4344 "to become available.");
4345 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004346 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 break;
4348 }
4349
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004350 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 }
4352
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004353 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4354 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004356 if (DEBUG_INJECTION) {
4357 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4358 injectionState->pendingForegroundDispatches);
4359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 nsecs_t remainingTimeout = endTime - now();
4361 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004362 if (DEBUG_INJECTION) {
4363 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4364 "dispatches to finish.");
4365 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004366 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 break;
4368 }
4369
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004370 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372 }
4373 }
4374
4375 injectionState->release();
4376 } // release lock
4377
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004378 if (DEBUG_INJECTION) {
4379 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4380 injectionResult, injectorPid, injectorUid);
4381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
4383 return injectionResult;
4384}
4385
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004386std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004387 std::array<uint8_t, 32> calculatedHmac;
4388 std::unique_ptr<VerifiedInputEvent> result;
4389 switch (event.getType()) {
4390 case AINPUT_EVENT_TYPE_KEY: {
4391 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4392 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4393 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004394 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004395 break;
4396 }
4397 case AINPUT_EVENT_TYPE_MOTION: {
4398 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4399 VerifiedMotionEvent verifiedMotionEvent =
4400 verifiedMotionEventFromMotionEvent(motionEvent);
4401 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004402 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004403 break;
4404 }
4405 default: {
4406 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4407 return nullptr;
4408 }
4409 }
4410 if (calculatedHmac == INVALID_HMAC) {
4411 return nullptr;
4412 }
4413 if (calculatedHmac != event.getHmac()) {
4414 return nullptr;
4415 }
4416 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004417}
4418
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 return injectorUid == 0 ||
4421 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422}
4423
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004424void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004425 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004428 if (DEBUG_INJECTION) {
4429 ALOGD("Setting input event injection result to %d. "
4430 "injectorPid=%d, injectorUid=%d",
4431 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004434 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 // Log the outcome since the injector did not wait for the injection result.
4436 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004437 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004438 ALOGV("Asynchronous input event injection succeeded.");
4439 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004440 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 ALOGW("Asynchronous input event injection failed.");
4442 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004443 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 ALOGW("Asynchronous input event injection permission denied.");
4445 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004446 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004447 ALOGW("Asynchronous input event injection timed out.");
4448 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004449 case InputEventInjectionResult::PENDING:
4450 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4451 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 }
4453 }
4454
4455 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004456 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 }
4458}
4459
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004460void InputDispatcher::transformMotionEntryForInjectionLocked(
4461 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004462 // Input injection works in the logical display coordinate space, but the input pipeline works
4463 // display space, so we need to transform the injected events accordingly.
4464 const auto it = mDisplayInfos.find(entry.displayId);
4465 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004466 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004467
4468 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004469 entry.pointerCoords[i] =
4470 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4471 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004472 }
4473}
4474
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004475void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4476 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 if (injectionState) {
4478 injectionState->pendingForegroundDispatches += 1;
4479 }
4480}
4481
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004482void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4483 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 if (injectionState) {
4485 injectionState->pendingForegroundDispatches -= 1;
4486
4487 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004488 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 }
4490 }
4491}
4492
chaviw98318de2021-05-19 16:45:23 -05004493const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004494 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004495 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004496 auto it = mWindowHandlesByDisplay.find(displayId);
4497 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004498}
4499
chaviw98318de2021-05-19 16:45:23 -05004500sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004501 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004502 if (windowHandleToken == nullptr) {
4503 return nullptr;
4504 }
4505
Arthur Hungb92218b2018-08-14 12:00:21 +08004506 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004507 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4508 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004509 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004510 return windowHandle;
4511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004514 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515}
4516
chaviw98318de2021-05-19 16:45:23 -05004517sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4518 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004519 if (windowHandleToken == nullptr) {
4520 return nullptr;
4521 }
4522
chaviw98318de2021-05-19 16:45:23 -05004523 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004524 if (windowHandle->getToken() == windowHandleToken) {
4525 return windowHandle;
4526 }
4527 }
4528 return nullptr;
4529}
4530
chaviw98318de2021-05-19 16:45:23 -05004531sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4532 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004533 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004534 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4535 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004536 if (handle->getId() == windowHandle->getId() &&
4537 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004538 if (windowHandle->getInfo()->displayId != it.first) {
4539 ALOGE("Found window %s in display %" PRId32
4540 ", but it should belong to display %" PRId32,
4541 windowHandle->getName().c_str(), it.first,
4542 windowHandle->getInfo()->displayId);
4543 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004544 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 }
4547 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004548 return nullptr;
4549}
4550
chaviw98318de2021-05-19 16:45:23 -05004551sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004552 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4553 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554}
4555
chaviw98318de2021-05-19 16:45:23 -05004556bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004557 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4558 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004559 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004560 if (connection != nullptr && noInputChannel) {
4561 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4562 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4563 return false;
4564 }
4565
4566 if (connection == nullptr) {
4567 if (!noInputChannel) {
4568 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4569 }
4570 return false;
4571 }
4572 if (!connection->responsive) {
4573 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4574 return false;
4575 }
4576 return true;
4577}
4578
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004579std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4580 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004581 auto connectionIt = mConnectionsByToken.find(token);
4582 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004583 return nullptr;
4584 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004585 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004586}
4587
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004588void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004589 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4590 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004591 // Remove all handles on a display if there are no windows left.
4592 mWindowHandlesByDisplay.erase(displayId);
4593 return;
4594 }
4595
4596 // Since we compare the pointer of input window handles across window updates, we need
4597 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004598 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4599 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4600 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004601 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004602 }
4603
chaviw98318de2021-05-19 16:45:23 -05004604 std::vector<sp<WindowInfoHandle>> newHandles;
4605 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004606 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004607 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004608 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004609 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004610 const bool canReceiveInput =
4611 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4612 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004613 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004614 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004615 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004616 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004617 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004618 }
4619
4620 if (info->displayId != displayId) {
4621 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4622 handle->getName().c_str(), displayId, info->displayId);
4623 continue;
4624 }
4625
Robert Carredd13602020-04-13 17:24:34 -07004626 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4627 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004628 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004629 oldHandle->updateFrom(handle);
4630 newHandles.push_back(oldHandle);
4631 } else {
4632 newHandles.push_back(handle);
4633 }
4634 }
4635
4636 // Insert or replace
4637 mWindowHandlesByDisplay[displayId] = newHandles;
4638}
4639
Arthur Hung72d8dc32020-03-28 00:48:39 +00004640void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004641 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004642 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004643 { // acquire lock
4644 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004645 for (const auto& [displayId, handles] : handlesPerDisplay) {
4646 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004647 }
4648 }
4649 // Wake up poll loop since it may need to make new input dispatching choices.
4650 mLooper->wake();
4651}
4652
Arthur Hungb92218b2018-08-14 12:00:21 +08004653/**
4654 * Called from InputManagerService, update window handle list by displayId that can receive input.
4655 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4656 * If set an empty list, remove all handles from the specific display.
4657 * For focused handle, check if need to change and send a cancel event to previous one.
4658 * For removed handle, check if need to send a cancel event if already in touch.
4659 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004660void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004661 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004662 if (DEBUG_FOCUS) {
4663 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004664 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004665 windowList += iwh->getName() + " ";
4666 }
4667 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669
Prabir Pradhand65552b2021-10-07 11:23:50 -07004670 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004671 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004672 const WindowInfo& info = *window->getInfo();
4673
4674 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004675 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004676 if (noInputWindow && window->getToken() != nullptr) {
4677 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4678 window->getName().c_str());
4679 window->releaseChannel();
4680 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004681
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004682 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004683 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4684 !info.inputConfig.test(
4685 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004686 "%s has feature SPY, but is not a trusted overlay.",
4687 window->getName().c_str());
4688
Prabir Pradhand65552b2021-10-07 11:23:50 -07004689 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004690 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4691 !info.inputConfig.test(
4692 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004693 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4694 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004695 }
4696
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004698 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004700 // Save the old windows' orientation by ID before it gets updated.
4701 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004702 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004703 oldWindowOrientations.emplace(handle->getId(),
4704 handle->getInfo()->transform.getOrientation());
4705 }
4706
chaviw98318de2021-05-19 16:45:23 -05004707 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004708
chaviw98318de2021-05-19 16:45:23 -05004709 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004710 if (mLastHoverWindowHandle &&
4711 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4712 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004713 mLastHoverWindowHandle = nullptr;
4714 }
4715
Vishnu Nairc519ff72021-01-21 08:23:08 -08004716 std::optional<FocusResolver::FocusChanges> changes =
4717 mFocusResolver.setInputWindows(displayId, windowHandles);
4718 if (changes) {
4719 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004722 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4723 mTouchStatesByDisplay.find(displayId);
4724 if (stateIt != mTouchStatesByDisplay.end()) {
4725 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004726 for (size_t i = 0; i < state.windows.size();) {
4727 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004728 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004729 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004730 ALOGD("Touched window was removed: %s in display %" PRId32,
4731 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004732 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004733 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004734 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4735 if (touchedInputChannel != nullptr) {
4736 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4737 "touched window was removed");
4738 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004739 // Since we are about to drop the touch, cancel the events for the wallpaper as
4740 // well.
4741 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004742 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4743 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004744 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4745 if (wallpaper != nullptr) {
4746 sp<Connection> wallpaperConnection =
4747 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004748 if (wallpaperConnection != nullptr) {
4749 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4750 options);
4751 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004752 }
4753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004755 state.windows.erase(state.windows.begin() + i);
4756 } else {
4757 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 }
4759 }
arthurhungb89ccb02020-12-30 16:19:01 +08004760
arthurhung6d4bed92021-03-17 11:59:33 +08004761 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004762 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004763 if (mDragState &&
4764 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004765 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004766 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004767 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004768 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004769
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004770 // Determine if the orientation of any of the input windows have changed, and cancel all
4771 // pointer events if necessary.
4772 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4773 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4774 if (newWindowHandle != nullptr &&
4775 newWindowHandle->getInfo()->transform.getOrientation() !=
4776 oldWindowOrientations[oldWindowHandle->getId()]) {
4777 std::shared_ptr<InputChannel> inputChannel =
4778 getInputChannelLocked(newWindowHandle->getToken());
4779 if (inputChannel != nullptr) {
4780 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4781 "touched window's orientation changed");
4782 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004783 }
4784 }
4785 }
4786
Arthur Hung72d8dc32020-03-28 00:48:39 +00004787 // Release information for windows that are no longer present.
4788 // This ensures that unused input channels are released promptly.
4789 // Otherwise, they might stick around until the window handle is destroyed
4790 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004791 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004792 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004793 if (DEBUG_FOCUS) {
4794 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004795 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004796 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004797 }
chaviw291d88a2019-02-14 10:33:58 -08004798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799}
4800
4801void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004802 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004803 if (DEBUG_FOCUS) {
4804 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4805 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4806 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004807 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004808 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004809 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 } // release lock
4811
4812 // Wake up poll loop since it may need to make new input dispatching choices.
4813 mLooper->wake();
4814}
4815
Vishnu Nair599f1412021-06-21 10:39:58 -07004816void InputDispatcher::setFocusedApplicationLocked(
4817 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4818 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4819 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4820
4821 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4822 return; // This application is already focused. No need to wake up or change anything.
4823 }
4824
4825 // Set the new application handle.
4826 if (inputApplicationHandle != nullptr) {
4827 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4828 } else {
4829 mFocusedApplicationHandlesByDisplay.erase(displayId);
4830 }
4831
4832 // No matter what the old focused application was, stop waiting on it because it is
4833 // no longer focused.
4834 resetNoFocusedWindowTimeoutLocked();
4835}
4836
Tiger Huang721e26f2018-07-24 22:26:19 +08004837/**
4838 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4839 * the display not specified.
4840 *
4841 * We track any unreleased events for each window. If a window loses the ability to receive the
4842 * released event, we will send a cancel event to it. So when the focused display is changed, we
4843 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4844 * display. The display-specified events won't be affected.
4845 */
4846void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004847 if (DEBUG_FOCUS) {
4848 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4849 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004850 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004851 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004852
4853 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004854 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004855 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004856 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004857 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004858 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004859 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 CancelationOptions
4861 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4862 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004863 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004864 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4865 }
4866 }
4867 mFocusedDisplayId = displayId;
4868
Chris Ye3c2d6f52020-08-09 10:39:48 -07004869 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004870 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004871 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004872
Vishnu Nairad321cd2020-08-20 16:40:21 -07004873 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004874 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004875 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004876 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004877 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004878 }
4879 }
4880 }
4881
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004882 if (DEBUG_FOCUS) {
4883 logDispatchStateLocked();
4884 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004885 } // release lock
4886
4887 // Wake up poll loop since it may need to make new input dispatching choices.
4888 mLooper->wake();
4889}
4890
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004892 if (DEBUG_FOCUS) {
4893 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895
4896 bool changed;
4897 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004898 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899
4900 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4901 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 }
4904
4905 if (mDispatchEnabled && !enabled) {
4906 resetAndDropEverythingLocked("dispatcher is being disabled");
4907 }
4908
4909 mDispatchEnabled = enabled;
4910 mDispatchFrozen = frozen;
4911 changed = true;
4912 } else {
4913 changed = false;
4914 }
4915
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004916 if (DEBUG_FOCUS) {
4917 logDispatchStateLocked();
4918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 } // release lock
4920
4921 if (changed) {
4922 // Wake up poll loop since it may need to make new input dispatching choices.
4923 mLooper->wake();
4924 }
4925}
4926
4927void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004928 if (DEBUG_FOCUS) {
4929 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931
4932 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004933 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934
4935 if (mInputFilterEnabled == enabled) {
4936 return;
4937 }
4938
4939 mInputFilterEnabled = enabled;
4940 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4941 } // release lock
4942
4943 // Wake up poll loop since there might be work to do to drop everything.
4944 mLooper->wake();
4945}
4946
Antonio Kantekea47acb2021-12-23 12:41:25 -08004947bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4948 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004949 bool needWake = false;
4950 {
4951 std::scoped_lock lock(mLock);
4952 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004953 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004954 }
4955 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004956 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4957 "hasPermission=%s)",
4958 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4959 }
4960 if (!hasPermission) {
4961 const sp<IBinder> focusedToken =
4962 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4963
Antonio Kantek019eb662022-02-08 13:41:52 -08004964 // TODO(b/218541064): if no window is currently focused, then we need to check the last
Antonio Kantekea47acb2021-12-23 12:41:25 -08004965 // interacted window (within 1 second timeout). We should allow touch mode change
4966 // if the last interacted window owner's pid/uid match the calling ones.
4967 if (focusedToken == nullptr) {
4968 return false;
4969 }
4970 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4971 if (windowHandle == nullptr) {
4972 return false;
4973 }
4974 const WindowInfo* windowInfo = windowHandle->getInfo();
4975 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4976 return false;
4977 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004978 }
4979
4980 // TODO(b/198499018): Store touch mode per display.
4981 mInTouchMode = inTouchMode;
4982
Antonio Kantekf16f2832021-09-28 04:39:20 +00004983 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4984 needWake = enqueueInboundEventLocked(std::move(entry));
4985 } // release lock
4986
4987 if (needWake) {
4988 mLooper->wake();
4989 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004990 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004991}
4992
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004993void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4994 if (opacity < 0 || opacity > 1) {
4995 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4996 return;
4997 }
4998
4999 std::scoped_lock lock(mLock);
5000 mMaximumObscuringOpacityForTouch = opacity;
5001}
5002
5003void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5004 std::scoped_lock lock(mLock);
5005 mBlockUntrustedTouchesMode = mode;
5006}
5007
Arthur Hungabbb9d82021-09-01 14:52:30 +00005008std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5009 const sp<IBinder>& token) {
5010 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5011 for (TouchedWindow& w : state.windows) {
5012 if (w.windowHandle->getToken() == token) {
5013 return std::make_pair(&state, &w);
5014 }
5015 }
5016 }
5017 return std::make_pair(nullptr, nullptr);
5018}
5019
arthurhungb89ccb02020-12-30 16:19:01 +08005020bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5021 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005022 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005023 if (DEBUG_FOCUS) {
5024 ALOGD("Trivial transfer to same window.");
5025 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005026 return true;
5027 }
5028
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005030 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031
Arthur Hungabbb9d82021-09-01 14:52:30 +00005032 // Find the target touch state and touched window by fromToken.
5033 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5034 if (state == nullptr || touchedWindow == nullptr) {
5035 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 return false;
5037 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005038
5039 const int32_t displayId = state->displayId;
5040 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5041 if (toWindowHandle == nullptr) {
5042 ALOGW("Cannot transfer focus because to window not found.");
5043 return false;
5044 }
5045
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005046 if (DEBUG_FOCUS) {
5047 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005048 touchedWindow->windowHandle->getName().c_str(),
5049 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 }
5051
Arthur Hungabbb9d82021-09-01 14:52:30 +00005052 // Erase old window.
5053 int32_t oldTargetFlags = touchedWindow->targetFlags;
5054 BitSet32 pointerIds = touchedWindow->pointerIds;
5055 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056
Arthur Hungabbb9d82021-09-01 14:52:30 +00005057 // Add new window.
5058 int32_t newTargetFlags = oldTargetFlags &
5059 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5060 InputTarget::FLAG_DISPATCH_AS_IS);
5061 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062
Arthur Hungabbb9d82021-09-01 14:52:30 +00005063 // Store the dragging window.
5064 if (isDragDrop) {
5065 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005066 }
5067
Arthur Hungabbb9d82021-09-01 14:52:30 +00005068 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005069 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5070 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005071 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005072 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 CancelationOptions
5074 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5075 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005077 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078 }
5079
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005080 if (DEBUG_FOCUS) {
5081 logDispatchStateLocked();
5082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083 } // release lock
5084
5085 // Wake up poll loop since it may need to make new input dispatching choices.
5086 mLooper->wake();
5087 return true;
5088}
5089
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005090// Binder call
5091bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5092 sp<IBinder> fromToken;
5093 { // acquire lock
5094 std::scoped_lock _l(mLock);
5095
Arthur Hungabbb9d82021-09-01 14:52:30 +00005096 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5097 [](const auto& pair) { return pair.second.windows.size() == 1; });
5098 if (it == mTouchStatesByDisplay.end()) {
5099 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5100 return false;
5101 }
5102 const int32_t displayId = it->first;
5103 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005104 if (toWindowHandle == nullptr) {
5105 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5106 return false;
5107 }
5108
Arthur Hungabbb9d82021-09-01 14:52:30 +00005109 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005110 const TouchedWindow& touchedWindow = state.windows[0];
5111 fromToken = touchedWindow.windowHandle->getToken();
5112 } // release lock
5113
5114 return transferTouchFocus(fromToken, destChannelToken);
5115}
5116
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005118 if (DEBUG_FOCUS) {
5119 ALOGD("Resetting and dropping all events (%s).", reason);
5120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121
5122 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5123 synthesizeCancelationEventsForAllConnectionsLocked(options);
5124
5125 resetKeyRepeatLocked();
5126 releasePendingEventLocked();
5127 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005128 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005130 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005131 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005133 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134}
5135
5136void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005137 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 dumpDispatchStateLocked(dump);
5139
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005140 std::istringstream stream(dump);
5141 std::string line;
5142
5143 while (std::getline(stream, line, '\n')) {
5144 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146}
5147
Prabir Pradhan99987712020-11-10 18:43:05 -08005148std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5149 std::string dump;
5150
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005151 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5152 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005153
5154 std::string windowName = "None";
5155 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005156 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005157 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5158 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5159 : "token has capture without window";
5160 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005161 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005162
5163 return dump;
5164}
5165
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005166void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005167 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5168 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5169 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005170 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171
Tiger Huang721e26f2018-07-24 22:26:19 +08005172 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5173 dump += StringPrintf(INDENT "FocusedApplications:\n");
5174 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5175 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005176 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005177 const std::chrono::duration timeout =
5178 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005179 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005180 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005181 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005184 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005186
Vishnu Nairc519ff72021-01-21 08:23:08 -08005187 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005188 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005190 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005191 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005192 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5193 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005194 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005195 state.displayId, toString(state.down), toString(state.split),
5196 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005197 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005198 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005199 for (size_t i = 0; i < state.windows.size(); i++) {
5200 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005201 dump += StringPrintf(INDENT4
5202 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5203 i, touchedWindow.windowHandle->getName().c_str(),
5204 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005205 }
5206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005207 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005209 }
5210 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005211 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212 }
5213
arthurhung6d4bed92021-03-17 11:59:33 +08005214 if (mDragState) {
5215 dump += StringPrintf(INDENT "DragState:\n");
5216 mDragState->dump(dump, INDENT2);
5217 }
5218
Arthur Hungb92218b2018-08-14 12:00:21 +08005219 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005220 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5221 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5222 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5223 const auto& displayInfo = it->second;
5224 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5225 displayInfo.logicalHeight);
5226 displayInfo.transform.dump(dump, "transform", INDENT4);
5227 } else {
5228 dump += INDENT2 "No DisplayInfo found!\n";
5229 }
5230
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005231 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005232 dump += INDENT2 "Windows:\n";
5233 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005234 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5235 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005237 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005238 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005239 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005240 "applicationInfo.name=%s, "
5241 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005242 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005243 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005244 windowInfo->displayId,
5245 windowInfo->inputConfig.string().c_str(),
5246 windowInfo->alpha, windowInfo->frameLeft,
5247 windowInfo->frameTop, windowInfo->frameRight,
5248 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005249 windowInfo->applicationInfo.name.c_str(),
5250 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005251 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005252 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005253 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005254 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005255 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005256 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005257 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005258 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005259 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005260 }
5261 } else {
5262 dump += INDENT2 "Windows: <none>\n";
5263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 }
5265 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005266 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 }
5268
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005269 if (!mGlobalMonitorsByDisplay.empty()) {
5270 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5271 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005272 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005275 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005278 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279
5280 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005281 if (!mRecentQueue.empty()) {
5282 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005283 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005284 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005285 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005286 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 }
5288 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291
5292 // Dump event currently being dispatched.
5293 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005294 dump += INDENT "PendingEvent:\n";
5295 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005296 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005297 dump += StringPrintf(", age=%" PRId64 "ms\n",
5298 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005300 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 }
5302
5303 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005304 if (!mInboundQueue.empty()) {
5305 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005306 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005307 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005308 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005309 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005312 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 }
5314
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005315 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005316 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005317 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5318 const KeyReplacement& replacement = pair.first;
5319 int32_t newKeyCode = pair.second;
5320 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005321 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005322 }
5323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005324 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005325 }
5326
Prabir Pradhancef936d2021-07-21 16:17:52 +00005327 if (!mCommandQueue.empty()) {
5328 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5329 } else {
5330 dump += INDENT "CommandQueue: <empty>\n";
5331 }
5332
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005333 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005335 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005336 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005337 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005338 connection->inputChannel->getFd().get(),
5339 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005340 connection->getWindowName().c_str(),
5341 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005342 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005344 if (!connection->outboundQueue.empty()) {
5345 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5346 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005347 dump += dumpQueue(connection->outboundQueue, currentTime);
5348
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005350 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 }
5352
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005353 if (!connection->waitQueue.empty()) {
5354 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5355 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005356 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005358 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 }
5360 }
5361 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005362 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 }
5364
5365 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005366 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5367 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005369 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 }
5371
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005372 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005373 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5374 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5375 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005376 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005377 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378}
5379
Michael Wright3dd60e22019-03-27 22:06:44 +00005380void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5381 const size_t numMonitors = monitors.size();
5382 for (size_t i = 0; i < numMonitors; i++) {
5383 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005384 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005385 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5386 dump += "\n";
5387 }
5388}
5389
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005390class LooperEventCallback : public LooperCallback {
5391public:
5392 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5393 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5394
5395private:
5396 std::function<int(int events)> mCallback;
5397};
5398
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005399Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005400 if (DEBUG_CHANNEL_CREATION) {
5401 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005404 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005405 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005406 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005407
5408 if (result) {
5409 return base::Error(result) << "Failed to open input channel pair with name " << name;
5410 }
5411
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005413 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005414 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005415 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005416 sp<Connection> connection =
5417 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005419 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5420 ALOGE("Created a new connection, but the token %p is already known", token.get());
5421 }
5422 mConnectionsByToken.emplace(token, connection);
5423
5424 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5425 this, std::placeholders::_1, token);
5426
5427 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 } // release lock
5429
5430 // Wake the looper because some connections have changed.
5431 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005432 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433}
5434
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005435Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005436 const std::string& name,
5437 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005438 std::shared_ptr<InputChannel> serverChannel;
5439 std::unique_ptr<InputChannel> clientChannel;
5440 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5441 if (result) {
5442 return base::Error(result) << "Failed to open input channel pair with name " << name;
5443 }
5444
Michael Wright3dd60e22019-03-27 22:06:44 +00005445 { // acquire lock
5446 std::scoped_lock _l(mLock);
5447
5448 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005449 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5450 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005451 }
5452
Garfield Tan15601662020-09-22 15:32:38 -07005453 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005454 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005455 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005456
5457 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5458 ALOGE("Created a new connection, but the token %p is already known", token.get());
5459 }
5460 mConnectionsByToken.emplace(token, connection);
5461 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5462 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005463
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005464 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005465
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005466 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005467 }
Garfield Tan15601662020-09-22 15:32:38 -07005468
Michael Wright3dd60e22019-03-27 22:06:44 +00005469 // Wake the looper because some connections have changed.
5470 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005471 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005472}
5473
Garfield Tan15601662020-09-22 15:32:38 -07005474status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005476 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477
Garfield Tan15601662020-09-22 15:32:38 -07005478 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 if (status) {
5480 return status;
5481 }
5482 } // release lock
5483
5484 // Wake the poll loop because removing the connection may have changed the current
5485 // synchronization state.
5486 mLooper->wake();
5487 return OK;
5488}
5489
Garfield Tan15601662020-09-22 15:32:38 -07005490status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5491 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005492 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005493 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005494 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 return BAD_VALUE;
5496 }
5497
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005498 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005499
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005501 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 }
5503
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005504 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505
5506 nsecs_t currentTime = now();
5507 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5508
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005509 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510 return OK;
5511}
5512
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005513void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005514 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5515 auto& [displayId, monitors] = *it;
5516 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5517 return monitor.inputChannel->getConnectionToken() == connectionToken;
5518 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005519
Michael Wright3dd60e22019-03-27 22:06:44 +00005520 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005521 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005522 } else {
5523 ++it;
5524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 }
5526}
5527
Michael Wright3dd60e22019-03-27 22:06:44 +00005528status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005529 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005530
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005531 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5532 if (!requestingChannel) {
5533 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5534 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005535 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005536
5537 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5538 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5539 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5540 " Ignoring.");
5541 return BAD_VALUE;
5542 }
5543
5544 TouchState& state = *statePtr;
5545
5546 // Send cancel events to all the input channels we're stealing from.
5547 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5548 "input channel stole pointer stream");
5549 options.deviceId = state.deviceId;
5550 options.displayId = state.displayId;
5551 std::string canceledWindows;
5552 for (const TouchedWindow& window : state.windows) {
5553 const std::shared_ptr<InputChannel> channel =
5554 getInputChannelLocked(window.windowHandle->getToken());
5555 if (channel != nullptr && channel->getConnectionToken() != token) {
5556 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5557 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5558 canceledWindows += channel->getName();
5559 }
5560 }
5561 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5562 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5563 canceledWindows.c_str());
5564
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005565 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005566 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005567 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005568 return OK;
5569}
5570
Prabir Pradhan99987712020-11-10 18:43:05 -08005571void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5572 { // acquire lock
5573 std::scoped_lock _l(mLock);
5574 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005575 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005576 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5577 windowHandle != nullptr ? windowHandle->getName().c_str()
5578 : "token without window");
5579 }
5580
Vishnu Nairc519ff72021-01-21 08:23:08 -08005581 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005582 if (focusedToken != windowToken) {
5583 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5584 enabled ? "enable" : "disable");
5585 return;
5586 }
5587
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005588 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005589 ALOGW("Ignoring request to %s Pointer Capture: "
5590 "window has %s requested pointer capture.",
5591 enabled ? "enable" : "disable", enabled ? "already" : "not");
5592 return;
5593 }
5594
Christine Franksb768bb42021-11-29 12:11:31 -08005595 if (enabled) {
5596 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5597 mIneligibleDisplaysForPointerCapture.end(),
5598 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5599 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5600 return;
5601 }
5602 }
5603
Prabir Pradhan99987712020-11-10 18:43:05 -08005604 setPointerCaptureLocked(enabled);
5605 } // release lock
5606
5607 // Wake the thread to process command entries.
5608 mLooper->wake();
5609}
5610
Christine Franksb768bb42021-11-29 12:11:31 -08005611void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5612 { // acquire lock
5613 std::scoped_lock _l(mLock);
5614 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5615 if (!isEligible) {
5616 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5617 }
5618 } // release lock
5619}
5620
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005621std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5622 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005623 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005624 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005625 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005626 }
5627 }
5628 }
5629 return std::nullopt;
5630}
5631
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005632sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005633 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005634 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005635 }
5636
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005637 for (const auto& [token, connection] : mConnectionsByToken) {
5638 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005639 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641 }
Robert Carr4e670e52018-08-15 13:26:12 -07005642
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005643 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644}
5645
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005646std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5647 sp<Connection> connection = getConnectionLocked(connectionToken);
5648 if (connection == nullptr) {
5649 return "<nullptr>";
5650 }
5651 return connection->getInputChannelName();
5652}
5653
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005654void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005655 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005656 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005657}
5658
Prabir Pradhancef936d2021-07-21 16:17:52 +00005659void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5660 const sp<Connection>& connection, uint32_t seq,
5661 bool handled, nsecs_t consumeTime) {
5662 // Handle post-event policy actions.
5663 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5664 if (dispatchEntryIt == connection->waitQueue.end()) {
5665 return;
5666 }
5667 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5668 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5669 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5670 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5671 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5672 }
5673 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5674 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5675 connection->inputChannel->getConnectionToken(),
5676 dispatchEntry->deliveryTime, consumeTime, finishTime);
5677 }
5678
5679 bool restartEvent;
5680 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5681 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5682 restartEvent =
5683 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5684 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5685 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5686 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5687 handled);
5688 } else {
5689 restartEvent = false;
5690 }
5691
5692 // Dequeue the event and start the next cycle.
5693 // Because the lock might have been released, it is possible that the
5694 // contents of the wait queue to have been drained, so we need to double-check
5695 // a few things.
5696 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5697 if (dispatchEntryIt != connection->waitQueue.end()) {
5698 dispatchEntry = *dispatchEntryIt;
5699 connection->waitQueue.erase(dispatchEntryIt);
5700 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5701 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5702 if (!connection->responsive) {
5703 connection->responsive = isConnectionResponsive(*connection);
5704 if (connection->responsive) {
5705 // The connection was unresponsive, and now it's responsive.
5706 processConnectionResponsiveLocked(*connection);
5707 }
5708 }
5709 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005710 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005711 connection->outboundQueue.push_front(dispatchEntry);
5712 traceOutboundQueueLength(*connection);
5713 } else {
5714 releaseDispatchEntry(dispatchEntry);
5715 }
5716 }
5717
5718 // Start the next dispatch cycle for this connection.
5719 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720}
5721
Prabir Pradhancef936d2021-07-21 16:17:52 +00005722void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5723 const sp<IBinder>& newToken) {
5724 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5725 scoped_unlock unlock(mLock);
5726 mPolicy->notifyFocusChanged(oldToken, newToken);
5727 };
5728 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729}
5730
Prabir Pradhancef936d2021-07-21 16:17:52 +00005731void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5732 auto command = [this, token, x, y]() REQUIRES(mLock) {
5733 scoped_unlock unlock(mLock);
5734 mPolicy->notifyDropWindow(token, x, y);
5735 };
5736 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005737}
5738
Prabir Pradhancef936d2021-07-21 16:17:52 +00005739void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5740 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5741 scoped_unlock unlock(mLock);
5742 mPolicy->notifyUntrustedTouch(obscuringPackage);
5743 };
5744 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005745}
5746
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005747void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5748 if (connection == nullptr) {
5749 LOG_ALWAYS_FATAL("Caller must check for nullness");
5750 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005751 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5752 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005753 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005754 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005755 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005756 return;
5757 }
5758 /**
5759 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5760 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5761 * has changed. This could cause newer entries to time out before the already dispatched
5762 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5763 * processes the events linearly. So providing information about the oldest entry seems to be
5764 * most useful.
5765 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005766 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005767 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5768 std::string reason =
5769 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005770 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005771 ns2ms(currentWait),
5772 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005773 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005774 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005775
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005776 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5777
5778 // Stop waking up for events on this connection, it is already unresponsive
5779 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005780}
5781
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005782void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5783 std::string reason =
5784 StringPrintf("%s does not have a focused window", application->getName().c_str());
5785 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005786
Prabir Pradhancef936d2021-07-21 16:17:52 +00005787 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5788 scoped_unlock unlock(mLock);
5789 mPolicy->notifyNoFocusedWindowAnr(application);
5790 };
5791 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005792}
5793
chaviw98318de2021-05-19 16:45:23 -05005794void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005795 const std::string& reason) {
5796 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5797 updateLastAnrStateLocked(windowLabel, reason);
5798}
5799
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005800void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5801 const std::string& reason) {
5802 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803 updateLastAnrStateLocked(windowLabel, reason);
5804}
5805
5806void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5807 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005809 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 struct tm tm;
5811 localtime_r(&t, &tm);
5812 char timestr[64];
5813 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005814 mLastAnrState.clear();
5815 mLastAnrState += INDENT "ANR:\n";
5816 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005817 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5818 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005819 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820}
5821
Prabir Pradhancef936d2021-07-21 16:17:52 +00005822void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5823 KeyEntry& entry) {
5824 const KeyEvent event = createKeyEvent(entry);
5825 nsecs_t delay = 0;
5826 { // release lock
5827 scoped_unlock unlock(mLock);
5828 android::base::Timer t;
5829 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5830 entry.policyFlags);
5831 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5832 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5833 std::to_string(t.duration().count()).c_str());
5834 }
5835 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
5837 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005838 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005840 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005842 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5843 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845}
5846
Prabir Pradhancef936d2021-07-21 16:17:52 +00005847void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005848 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005849 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005850 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005851 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005852 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005853 };
5854 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005855}
5856
Prabir Pradhanedd96402022-02-15 01:46:16 -08005857void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5858 std::optional<int32_t> pid) {
5859 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005860 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005861 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005862 };
5863 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005864}
5865
5866/**
5867 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5868 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5869 * command entry to the command queue.
5870 */
5871void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5872 std::string reason) {
5873 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005874 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005875 if (connection.monitor) {
5876 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5877 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005878 pid = findMonitorPidByTokenLocked(connectionToken);
5879 } else {
5880 // The connection is a window
5881 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5882 reason.c_str());
5883 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5884 if (handle != nullptr) {
5885 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005886 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005887 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005888 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005889}
5890
5891/**
5892 * Tell the policy that a connection has become responsive so that it can stop ANR.
5893 */
5894void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5895 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005896 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005897 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005898 pid = findMonitorPidByTokenLocked(connectionToken);
5899 } else {
5900 // The connection is a window
5901 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5902 if (handle != nullptr) {
5903 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005904 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005905 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005906 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005907}
5908
Prabir Pradhancef936d2021-07-21 16:17:52 +00005909bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005910 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005911 KeyEntry& keyEntry, bool handled) {
5912 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005913 if (!handled) {
5914 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005915 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005916 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005917 return false;
5918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005920 // Get the fallback key state.
5921 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005922 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005923 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005924 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925 connection->inputState.removeFallbackKey(originalKeyCode);
5926 }
5927
5928 if (handled || !dispatchEntry->hasForegroundTarget()) {
5929 // If the application handles the original key for which we previously
5930 // generated a fallback or if the window is not a foreground window,
5931 // then cancel the associated fallback key, if any.
5932 if (fallbackKeyCode != -1) {
5933 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005934 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5935 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5936 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5937 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5938 keyEntry.policyFlags);
5939 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005940 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005941 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942
5943 mLock.unlock();
5944
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005945 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005946 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947
5948 mLock.lock();
5949
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950 // Cancel the fallback key.
5951 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005953 "application handled the original non-fallback key "
5954 "or is no longer a foreground target, "
5955 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 options.keyCode = fallbackKeyCode;
5957 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 connection->inputState.removeFallbackKey(originalKeyCode);
5960 }
5961 } else {
5962 // If the application did not handle a non-fallback key, first check
5963 // that we are in a good state to perform unhandled key event processing
5964 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005965 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005966 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005967 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5968 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5969 "since this is not an initial down. "
5970 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5971 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5972 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973 return false;
5974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005977 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5978 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5979 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5980 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5981 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005982 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983
5984 mLock.unlock();
5985
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005986 bool fallback =
5987 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005988 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005989
5990 mLock.lock();
5991
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005992 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 connection->inputState.removeFallbackKey(originalKeyCode);
5994 return false;
5995 }
5996
5997 // Latch the fallback keycode for this key on an initial down.
5998 // The fallback keycode cannot change at any other point in the lifecycle.
5999 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006000 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006001 fallbackKeyCode = event.getKeyCode();
6002 } else {
6003 fallbackKeyCode = AKEYCODE_UNKNOWN;
6004 }
6005 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6006 }
6007
6008 ALOG_ASSERT(fallbackKeyCode != -1);
6009
6010 // Cancel the fallback key if the policy decides not to send it anymore.
6011 // We will continue to dispatch the key to the policy but we will no
6012 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006013 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6014 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006015 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6016 if (fallback) {
6017 ALOGD("Unhandled key event: Policy requested to send key %d"
6018 "as a fallback for %d, but on the DOWN it had requested "
6019 "to send %d instead. Fallback canceled.",
6020 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6021 } else {
6022 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6023 "but on the DOWN it had requested to send %d. "
6024 "Fallback canceled.",
6025 originalKeyCode, fallbackKeyCode);
6026 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006027 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006028
6029 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6030 "canceling fallback, policy no longer desires it");
6031 options.keyCode = fallbackKeyCode;
6032 synthesizeCancelationEventsForConnectionLocked(connection, options);
6033
6034 fallback = false;
6035 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006036 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006037 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006038 }
6039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006041 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6042 {
6043 std::string msg;
6044 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6045 connection->inputState.getFallbackKeys();
6046 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6047 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6048 }
6049 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6050 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006052 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053
6054 if (fallback) {
6055 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006056 keyEntry.eventTime = event.getEventTime();
6057 keyEntry.deviceId = event.getDeviceId();
6058 keyEntry.source = event.getSource();
6059 keyEntry.displayId = event.getDisplayId();
6060 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6061 keyEntry.keyCode = fallbackKeyCode;
6062 keyEntry.scanCode = event.getScanCode();
6063 keyEntry.metaState = event.getMetaState();
6064 keyEntry.repeatCount = event.getRepeatCount();
6065 keyEntry.downTime = event.getDownTime();
6066 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006068 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6069 ALOGD("Unhandled key event: Dispatching fallback key. "
6070 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6071 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6072 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006073 return true; // restart the event
6074 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006075 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6076 ALOGD("Unhandled key event: No fallback key.");
6077 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006078
6079 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006080 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 }
6082 }
6083 return false;
6084}
6085
Prabir Pradhancef936d2021-07-21 16:17:52 +00006086bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006087 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006088 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 return false;
6090}
6091
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092void InputDispatcher::traceInboundQueueLengthLocked() {
6093 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006094 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 }
6096}
6097
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006098void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 if (ATRACE_ENABLED()) {
6100 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006101 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6102 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 }
6104}
6105
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006106void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 if (ATRACE_ENABLED()) {
6108 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006109 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6110 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
6112}
6113
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006114void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006115 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006117 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118 dumpDispatchStateLocked(dump);
6119
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006120 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006121 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006122 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 }
6124}
6125
6126void InputDispatcher::monitor() {
6127 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006128 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006129 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006130 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131}
6132
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006133/**
6134 * Wake up the dispatcher and wait until it processes all events and commands.
6135 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6136 * this method can be safely called from any thread, as long as you've ensured that
6137 * the work you are interested in completing has already been queued.
6138 */
6139bool InputDispatcher::waitForIdle() {
6140 /**
6141 * Timeout should represent the longest possible time that a device might spend processing
6142 * events and commands.
6143 */
6144 constexpr std::chrono::duration TIMEOUT = 100ms;
6145 std::unique_lock lock(mLock);
6146 mLooper->wake();
6147 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6148 return result == std::cv_status::no_timeout;
6149}
6150
Vishnu Naire798b472020-07-23 13:52:21 -07006151/**
6152 * Sets focus to the window identified by the token. This must be called
6153 * after updating any input window handles.
6154 *
6155 * Params:
6156 * request.token - input channel token used to identify the window that should gain focus.
6157 * request.focusedToken - the token that the caller expects currently to be focused. If the
6158 * specified token does not match the currently focused window, this request will be dropped.
6159 * If the specified focused token matches the currently focused window, the call will succeed.
6160 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6161 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6162 * when requesting the focus change. This determines which request gets
6163 * precedence if there is a focus change request from another source such as pointer down.
6164 */
Vishnu Nair958da932020-08-21 17:12:37 -07006165void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6166 { // acquire lock
6167 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006168 std::optional<FocusResolver::FocusChanges> changes =
6169 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6170 if (changes) {
6171 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006172 }
6173 } // release lock
6174 // Wake up poll loop since it may need to make new input dispatching choices.
6175 mLooper->wake();
6176}
6177
Vishnu Nairc519ff72021-01-21 08:23:08 -08006178void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6179 if (changes.oldFocus) {
6180 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006181 if (focusedInputChannel) {
6182 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6183 "focus left window");
6184 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006185 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006186 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006187 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006188 if (changes.newFocus) {
6189 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006190 }
6191
Prabir Pradhan99987712020-11-10 18:43:05 -08006192 // If a window has pointer capture, then it must have focus. We need to ensure that this
6193 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6194 // If the window loses focus before it loses pointer capture, then the window can be in a state
6195 // where it has pointer capture but not focus, violating the contract. Therefore we must
6196 // dispatch the pointer capture event before the focus event. Since focus events are added to
6197 // the front of the queue (above), we add the pointer capture event to the front of the queue
6198 // after the focus events are added. This ensures the pointer capture event ends up at the
6199 // front.
6200 disablePointerCaptureForcedLocked();
6201
Vishnu Nairc519ff72021-01-21 08:23:08 -08006202 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006203 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006204 }
6205}
Vishnu Nair958da932020-08-21 17:12:37 -07006206
Prabir Pradhan99987712020-11-10 18:43:05 -08006207void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006208 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006209 return;
6210 }
6211
6212 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6213
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006214 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006215 setPointerCaptureLocked(false);
6216 }
6217
6218 if (!mWindowTokenWithPointerCapture) {
6219 // No need to send capture changes because no window has capture.
6220 return;
6221 }
6222
6223 if (mPendingEvent != nullptr) {
6224 // Move the pending event to the front of the queue. This will give the chance
6225 // for the pending event to be dropped if it is a captured event.
6226 mInboundQueue.push_front(mPendingEvent);
6227 mPendingEvent = nullptr;
6228 }
6229
6230 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006231 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006232 mInboundQueue.push_front(std::move(entry));
6233}
6234
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006235void InputDispatcher::setPointerCaptureLocked(bool enable) {
6236 mCurrentPointerCaptureRequest.enable = enable;
6237 mCurrentPointerCaptureRequest.seq++;
6238 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006239 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006240 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241 };
6242 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006243}
6244
Vishnu Nair599f1412021-06-21 10:39:58 -07006245void InputDispatcher::displayRemoved(int32_t displayId) {
6246 { // acquire lock
6247 std::scoped_lock _l(mLock);
6248 // Set an empty list to remove all handles from the specific display.
6249 setInputWindowsLocked(/* window handles */ {}, displayId);
6250 setFocusedApplicationLocked(displayId, nullptr);
6251 // Call focus resolver to clean up stale requests. This must be called after input windows
6252 // have been removed for the removed display.
6253 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006254 // Reset pointer capture eligibility, regardless of previous state.
6255 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006256 } // release lock
6257
6258 // Wake up poll loop since it may need to make new input dispatching choices.
6259 mLooper->wake();
6260}
6261
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006262void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6263 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006264 // The listener sends the windows as a flattened array. Separate the windows by display for
6265 // more convenient parsing.
6266 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006267 for (const auto& info : windowInfos) {
6268 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6269 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6270 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006271
6272 { // acquire lock
6273 std::scoped_lock _l(mLock);
6274 mDisplayInfos.clear();
6275 for (const auto& displayInfo : displayInfos) {
6276 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6277 }
6278
6279 for (const auto& [displayId, handles] : handlesPerDisplay) {
6280 setInputWindowsLocked(handles, displayId);
6281 }
6282 }
6283 // Wake up poll loop since it may need to make new input dispatching choices.
6284 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006285}
6286
Vishnu Nair062a8672021-09-03 16:07:44 -07006287bool InputDispatcher::shouldDropInput(
6288 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006289 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6290 (windowHandle->getInfo()->inputConfig.test(
6291 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006292 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006293 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6294 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006295 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006296 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006297 windowHandle->getInfo()->displayId);
6298 return true;
6299 }
6300 return false;
6301}
6302
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006303void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6304 const std::vector<gui::WindowInfo>& windowInfos,
6305 const std::vector<DisplayInfo>& displayInfos) {
6306 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6307}
6308
Arthur Hungdfd528e2021-12-08 13:23:04 +00006309void InputDispatcher::cancelCurrentTouch() {
6310 {
6311 std::scoped_lock _l(mLock);
6312 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6313 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6314 "cancel current touch");
6315 synthesizeCancelationEventsForAllConnectionsLocked(options);
6316
6317 mTouchStatesByDisplay.clear();
6318 mLastHoverWindowHandle.clear();
6319 }
6320 // Wake up poll loop since there might be work to do.
6321 mLooper->wake();
6322}
6323
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006324void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6325 std::scoped_lock _l(mLock);
6326 mMonitorDispatchingTimeout = timeout;
6327}
6328
Garfield Tane84e6f92019-08-29 17:28:41 -07006329} // namespace android::inputdispatcher