blob: 7852b30875abad5185e68d164ef294a48e3c6ad9 [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
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800163const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165// 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 +0000166constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
167
168// Log a warning when an interception call takes longer than this to process.
169constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800170
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700171// Additional key latency in case a connection is still processing some motion events.
172// This will help with the case when a user touched a button that opens a new window,
173// and gives us the chance to dispatch the key to this new window.
174constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
175
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000177constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
178
Antonio Kantekea47acb2021-12-23 12:41:25 -0800179// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000180constexpr int LOGTAG_INPUT_INTERACTION = 62000;
181constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000182constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000183
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000184inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 return systemTime(SYSTEM_TIME_MONOTONIC);
186}
187
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000188inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return value ? "true" : "false";
190}
191
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000192inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000193 if (binder == nullptr) {
194 return "<null>";
195 }
196 return StringPrintf("%p", binder.get());
197}
198
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000199inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
201 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202}
203
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000204bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700206 case AKEY_EVENT_ACTION_DOWN:
207 case AKEY_EVENT_ACTION_UP:
208 return true;
209 default:
210 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212}
213
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000214bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700215 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 ALOGE("Key event has invalid action code 0x%x", action);
217 return false;
218 }
219 return true;
220}
221
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000222bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700224 case AMOTION_EVENT_ACTION_DOWN:
225 case AMOTION_EVENT_ACTION_UP:
226 case AMOTION_EVENT_ACTION_CANCEL:
227 case AMOTION_EVENT_ACTION_MOVE:
228 case AMOTION_EVENT_ACTION_OUTSIDE:
229 case AMOTION_EVENT_ACTION_HOVER_ENTER:
230 case AMOTION_EVENT_ACTION_HOVER_MOVE:
231 case AMOTION_EVENT_ACTION_HOVER_EXIT:
232 case AMOTION_EVENT_ACTION_SCROLL:
233 return true;
234 case AMOTION_EVENT_ACTION_POINTER_DOWN:
235 case AMOTION_EVENT_ACTION_POINTER_UP: {
236 int32_t index = getMotionEventActionPointerIndex(action);
237 return index >= 0 && index < pointerCount;
238 }
239 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
240 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
241 return actionButton != 0;
242 default:
243 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244 }
245}
246
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000247int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500248 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
249}
250
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000251bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
252 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700253 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 ALOGE("Motion event has invalid action code 0x%x", action);
255 return false;
256 }
257 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800258 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700259 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 return false;
261 }
262 BitSet32 pointerIdBits;
263 for (size_t i = 0; i < pointerCount; i++) {
264 int32_t id = pointerProperties[i].id;
265 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700266 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
267 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 return false;
269 }
270 if (pointerIdBits.hasBit(id)) {
271 ALOGE("Motion event has duplicate pointer id %d", id);
272 return false;
273 }
274 pointerIdBits.markBit(id);
275 }
276 return true;
277}
278
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000279std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000281 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800282 }
283
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000284 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285 bool first = true;
286 Region::const_iterator cur = region.begin();
287 Region::const_iterator const tail = region.end();
288 while (cur != tail) {
289 if (first) {
290 first = false;
291 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800292 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800293 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800294 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295 cur++;
296 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000297 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800298}
299
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000300std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500301 constexpr size_t maxEntries = 50; // max events to print
302 constexpr size_t skipBegin = maxEntries / 2;
303 const size_t skipEnd = queue.size() - maxEntries / 2;
304 // skip from maxEntries / 2 ... size() - maxEntries/2
305 // only print from 0 .. skipBegin and then from skipEnd .. size()
306
307 std::string dump;
308 for (size_t i = 0; i < queue.size(); i++) {
309 const DispatchEntry& entry = *queue[i];
310 if (i >= skipBegin && i < skipEnd) {
311 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
312 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
313 continue;
314 }
315 dump.append(INDENT4);
316 dump += entry.eventEntry->getDescription();
317 dump += StringPrintf(", seq=%" PRIu32
318 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
319 entry.seq, entry.targetFlags, entry.resolvedAction,
320 ns2ms(currentTime - entry.eventEntry->eventTime));
321 if (entry.deliveryTime != 0) {
322 // This entry was delivered, so add information on how long we've been waiting
323 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
324 }
325 dump.append("\n");
326 }
327 return dump;
328}
329
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700330/**
331 * Find the entry in std::unordered_map by key, and return it.
332 * If the entry is not found, return a default constructed entry.
333 *
334 * Useful when the entries are vectors, since an empty vector will be returned
335 * if the entry is not found.
336 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
337 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700338template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000339V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700340 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700341 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800342}
343
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000344bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700345 if (first == second) {
346 return true;
347 }
348
349 if (first == nullptr || second == nullptr) {
350 return false;
351 }
352
353 return first->getToken() == second->getToken();
354}
355
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000356bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000357 if (first == nullptr || second == nullptr) {
358 return false;
359 }
360 return first->applicationInfo.token != nullptr &&
361 first->applicationInfo.token == second->applicationInfo.token;
362}
363
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000364std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
365 std::shared_ptr<EventEntry> eventEntry,
366 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 if (inputTarget.useDefaultPointerTransform()) {
368 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700369 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700370 inputTarget.displayTransform,
371 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372 }
373
374 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
375 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
376
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700377 std::vector<PointerCoords> pointerCoords;
378 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379
380 // Use the first pointer information to normalize all other pointers. This could be any pointer
381 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 // uses the transform for the normalized pointer.
383 const ui::Transform& firstPointerTransform =
384 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
385 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000386
387 // Iterate through all pointers in the event to normalize against the first.
388 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
389 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
390 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700391 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000392
393 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700394 // First, apply the current pointer's transform to update the coordinates into
395 // window space.
396 pointerCoords[pointerIndex].transform(currTransform);
397 // Next, apply the inverse transform of the normalized coordinates so the
398 // current coordinates are transformed into the normalized coordinate space.
399 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000400 }
401
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700402 std::unique_ptr<MotionEntry> combinedMotionEntry =
403 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
404 motionEntry.deviceId, motionEntry.source,
405 motionEntry.displayId, motionEntry.policyFlags,
406 motionEntry.action, motionEntry.actionButton,
407 motionEntry.flags, motionEntry.metaState,
408 motionEntry.buttonState, motionEntry.classification,
409 motionEntry.edgeFlags, motionEntry.xPrecision,
410 motionEntry.yPrecision, motionEntry.xCursorPosition,
411 motionEntry.yCursorPosition, motionEntry.downTime,
412 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000413 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000414
415 if (motionEntry.injectionState) {
416 combinedMotionEntry->injectionState = motionEntry.injectionState;
417 combinedMotionEntry->injectionState->refCount += 1;
418 }
419
420 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700421 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700422 firstPointerTransform, inputTarget.displayTransform,
423 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000424 return dispatchEntry;
425}
426
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000427status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
428 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700429 std::unique_ptr<InputChannel> uniqueServerChannel;
430 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
431
432 serverChannel = std::move(uniqueServerChannel);
433 return result;
434}
435
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500436template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000437bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500438 if (lhs == nullptr && rhs == nullptr) {
439 return true;
440 }
441 if (lhs == nullptr || rhs == nullptr) {
442 return false;
443 }
444 return *lhs == *rhs;
445}
446
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000447KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000448 KeyEvent event;
449 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
450 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
451 entry.repeatCount, entry.downTime, entry.eventTime);
452 return event;
453}
454
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000455bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000456 // Do not keep track of gesture monitors. They receive every event and would disproportionately
457 // affect the statistics.
458 if (connection.monitor) {
459 return false;
460 }
461 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
462 if (!connection.responsive) {
463 return false;
464 }
465 return true;
466}
467
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000468bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000469 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
470 const int32_t& inputEventId = eventEntry.id;
471 if (inputEventId != dispatchEntry.resolvedEventId) {
472 // Event was transmuted
473 return false;
474 }
475 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
476 return false;
477 }
478 // Only track latency for events that originated from hardware
479 if (eventEntry.isSynthesized()) {
480 return false;
481 }
482 const EventEntry::Type& inputEventEntryType = eventEntry.type;
483 if (inputEventEntryType == EventEntry::Type::KEY) {
484 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
485 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
486 return false;
487 }
488 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
489 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
490 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
491 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
492 return false;
493 }
494 } else {
495 // Not a key or a motion
496 return false;
497 }
498 if (!shouldReportMetricsForConnection(connection)) {
499 return false;
500 }
501 return true;
502}
503
Prabir Pradhancef936d2021-07-21 16:17:52 +0000504/**
505 * Connection is responsive if it has no events in the waitQueue that are older than the
506 * current time.
507 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000508bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000509 const nsecs_t currentTime = now();
510 for (const DispatchEntry* entry : connection.waitQueue) {
511 if (entry->timeoutTime < currentTime) {
512 return false;
513 }
514 }
515 return true;
516}
517
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518// Returns true if the event type passed as argument represents a user activity.
519bool isUserActivityEvent(const EventEntry& eventEntry) {
520 switch (eventEntry.type) {
521 case EventEntry::Type::FOCUS:
522 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
523 case EventEntry::Type::DRAG:
524 case EventEntry::Type::TOUCH_MODE_CHANGED:
525 case EventEntry::Type::SENSOR:
526 case EventEntry::Type::CONFIGURATION_CHANGED:
527 return false;
528 case EventEntry::Type::DEVICE_RESET:
529 case EventEntry::Type::KEY:
530 case EventEntry::Type::MOTION:
531 return true;
532 }
533}
534
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800535// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700536bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
537 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800538 const auto inputConfig = windowInfo.inputConfig;
539 if (windowInfo.displayId != displayId ||
540 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800541 return false;
542 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700543 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800544 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800545 return false;
546 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800547 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800548 return false;
549 }
550 return true;
551}
552
Prabir Pradhand65552b2021-10-07 11:23:50 -0700553bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
554 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
555 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
556 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
557}
558
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000559// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
560// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
561// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
562// be sent to such a window, but it is not a foreground event and doesn't use
563// InputTarget::FLAG_FOREGROUND.
564bool canReceiveForegroundTouches(const WindowInfo& info) {
565 // A non-touchable window can still receive touch events (e.g. in the case of
566 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
567 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
568}
569
Antonio Kantek48710e42022-03-24 14:19:30 -0700570bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
571 if (windowHandle == nullptr) {
572 return false;
573 }
574 const WindowInfo* windowInfo = windowHandle->getInfo();
575 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
576 return true;
577 }
578 return false;
579}
580
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000581} // namespace
582
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583// --- InputDispatcher ---
584
Garfield Tan00f511d2019-06-12 16:55:40 -0700585InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800586 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
587
588InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
589 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700590 : mPolicy(policy),
591 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700592 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800593 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700594 mAppSwitchSawKeyDown(false),
595 mAppSwitchDueTime(LONG_LONG_MAX),
596 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800597 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700598 mDispatchEnabled(false),
599 mDispatchFrozen(false),
600 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800601 // mInTouchMode will be initialized by the WindowManager to the default device config.
602 // To avoid leaking stack in case that call never comes, and for tests,
603 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000604 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100605 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000606 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800607 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800608 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000609 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800610 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800612 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700614 mWindowInfoListener = new DispatcherWindowListener(*this);
615 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
616
Yi Kong9b14ac62018-07-17 13:48:38 -0700617 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618
619 policy->getDispatcherConfiguration(&mConfig);
620}
621
622InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000623 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624
Prabir Pradhancef936d2021-07-21 16:17:52 +0000625 resetKeyRepeatLocked();
626 releasePendingEventLocked();
627 drainInboundQueueLocked();
628 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000630 while (!mConnectionsByToken.empty()) {
631 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000632 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
633 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 }
635}
636
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700637status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700638 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700639 return ALREADY_EXISTS;
640 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700641 mThread = std::make_unique<InputThread>(
642 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
643 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700644}
645
646status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700647 if (mThread && mThread->isCallingThread()) {
648 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700649 return INVALID_OPERATION;
650 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700651 mThread.reset();
652 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700653}
654
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655void InputDispatcher::dispatchOnce() {
656 nsecs_t nextWakeupTime = LONG_LONG_MAX;
657 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800658 std::scoped_lock _l(mLock);
659 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660
661 // Run a dispatch loop if there are no pending commands.
662 // The dispatch loop might enqueue commands to run afterwards.
663 if (!haveCommandsLocked()) {
664 dispatchOnceInnerLocked(&nextWakeupTime);
665 }
666
667 // Run all pending commands if there are any.
668 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000669 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 nextWakeupTime = LONG_LONG_MIN;
671 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800672
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673 // If we are still waiting for ack on some events,
674 // we might have to wake up earlier to check if an app is anr'ing.
675 const nsecs_t nextAnrCheck = processAnrsLocked();
676 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
677
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800678 // We are about to enter an infinitely long sleep, because we have no commands or
679 // pending or queued events
680 if (nextWakeupTime == LONG_LONG_MAX) {
681 mDispatcherEnteredIdle.notify_all();
682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 } // release lock
684
685 // Wait for callback or timeout or wake. (make sure we round up, not down)
686 nsecs_t currentTime = now();
687 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
688 mLooper->pollOnce(timeoutMillis);
689}
690
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500692 * Raise ANR if there is no focused window.
693 * Before the ANR is raised, do a final state check:
694 * 1. The currently focused application must be the same one we are waiting for.
695 * 2. Ensure we still don't have a focused window.
696 */
697void InputDispatcher::processNoFocusedWindowAnrLocked() {
698 // Check if the application that we are waiting for is still focused.
699 std::shared_ptr<InputApplicationHandle> focusedApplication =
700 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
701 if (focusedApplication == nullptr ||
702 focusedApplication->getApplicationToken() !=
703 mAwaitedFocusedApplication->getApplicationToken()) {
704 // Unexpected because we should have reset the ANR timer when focused application changed
705 ALOGE("Waited for a focused window, but focused application has already changed to %s",
706 focusedApplication->getName().c_str());
707 return; // The focused application has changed.
708 }
709
chaviw98318de2021-05-19 16:45:23 -0500710 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500711 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
712 if (focusedWindowHandle != nullptr) {
713 return; // We now have a focused window. No need for ANR.
714 }
715 onAnrLocked(mAwaitedFocusedApplication);
716}
717
718/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719 * Check if any of the connections' wait queues have events that are too old.
720 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
721 * Return the time at which we should wake up next.
722 */
723nsecs_t InputDispatcher::processAnrsLocked() {
724 const nsecs_t currentTime = now();
725 nsecs_t nextAnrCheck = LONG_LONG_MAX;
726 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
727 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
728 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500729 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700730 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500731 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732 return LONG_LONG_MIN;
733 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500734 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700735 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
736 }
737 }
738
739 // Check if any connection ANRs are due
740 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
741 if (currentTime < nextAnrCheck) { // most likely scenario
742 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
743 }
744
745 // If we reached here, we have an unresponsive connection.
746 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
747 if (connection == nullptr) {
748 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
749 return nextAnrCheck;
750 }
751 connection->responsive = false;
752 // Stop waking up for this unresponsive connection
753 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000754 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700755 return LONG_LONG_MIN;
756}
757
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800758std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
759 const sp<Connection>& connection) {
760 if (connection->monitor) {
761 return mMonitorDispatchingTimeout;
762 }
763 const sp<WindowInfoHandle> window =
764 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700765 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500766 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700767 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500768 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700769}
770
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
772 nsecs_t currentTime = now();
773
Jeff Browndc5992e2014-04-11 01:27:26 -0700774 // Reset the key repeat timer whenever normal dispatch is suspended while the
775 // device is in a non-interactive state. This is to ensure that we abort a key
776 // repeat if the device is just coming out of sleep.
777 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 resetKeyRepeatLocked();
779 }
780
781 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
782 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100783 if (DEBUG_FOCUS) {
784 ALOGD("Dispatch frozen. Waiting some more.");
785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 return;
787 }
788
789 // Optimize latency of app switches.
790 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
791 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
792 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
793 if (mAppSwitchDueTime < *nextWakeupTime) {
794 *nextWakeupTime = mAppSwitchDueTime;
795 }
796
797 // Ready to start a new event.
798 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700800 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 if (isAppSwitchDue) {
802 // The inbound queue is empty so the app switch key we were waiting
803 // for will never arrive. Stop waiting for it.
804 resetPendingAppSwitchLocked(false);
805 isAppSwitchDue = false;
806 }
807
808 // Synthesize a key repeat if appropriate.
809 if (mKeyRepeatState.lastKeyEntry) {
810 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
811 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
812 } else {
813 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
814 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
815 }
816 }
817 }
818
819 // Nothing to do if there is no pending event.
820 if (!mPendingEvent) {
821 return;
822 }
823 } else {
824 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700825 mPendingEvent = mInboundQueue.front();
826 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 traceInboundQueueLengthLocked();
828 }
829
830 // Poke user activity for this event.
831 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700832 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 }
835
836 // Now we have an event to dispatch.
837 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700838 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700840 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700842 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700844 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 }
846
847 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700848 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
850
851 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700852 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700853 const ConfigurationChangedEntry& typedEntry =
854 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700856 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 break;
858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700860 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 const DeviceResetEntry& typedEntry =
862 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700864 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 break;
866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100868 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 std::shared_ptr<FocusEntry> typedEntry =
870 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100871 dispatchFocusLocked(currentTime, typedEntry);
872 done = true;
873 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
874 break;
875 }
876
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700877 case EventEntry::Type::TOUCH_MODE_CHANGED: {
878 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
879 dispatchTouchModeChangeLocked(currentTime, typedEntry);
880 done = true;
881 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
882 break;
883 }
884
Prabir Pradhan99987712020-11-10 18:43:05 -0800885 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
886 const auto typedEntry =
887 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
888 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
889 done = true;
890 break;
891 }
892
arthurhungb89ccb02020-12-30 16:19:01 +0800893 case EventEntry::Type::DRAG: {
894 std::shared_ptr<DragEntry> typedEntry =
895 std::static_pointer_cast<DragEntry>(mPendingEvent);
896 dispatchDragLocked(currentTime, typedEntry);
897 done = true;
898 break;
899 }
900
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700901 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700904 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 resetPendingAppSwitchLocked(true);
906 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700907 } else if (dropReason == DropReason::NOT_DROPPED) {
908 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 }
910 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700911 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700912 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700914 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
915 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700917 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 break;
919 }
920
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700922 std::shared_ptr<MotionEntry> motionEntry =
923 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700924 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
925 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700927 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700928 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700930 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
931 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700932 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700933 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
Chris Yef59a2f42020-10-16 12:55:26 -0700936
937 case EventEntry::Type::SENSOR: {
938 std::shared_ptr<SensorEntry> sensorEntry =
939 std::static_pointer_cast<SensorEntry>(mPendingEvent);
940 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
941 dropReason = DropReason::APP_SWITCH;
942 }
943 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
944 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
945 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
946 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
947 dropReason = DropReason::STALE;
948 }
949 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
950 done = true;
951 break;
952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
954
955 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700956 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700957 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 }
Michael Wright3a981722015-06-10 15:26:13 +0100959 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960
961 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
964}
965
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800966bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
967 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
968}
969
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700970/**
971 * Return true if the events preceding this incoming motion event should be dropped
972 * Return false otherwise (the default behaviour)
973 */
974bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700975 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700976 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700977
978 // Optimize case where the current application is unresponsive and the user
979 // decides to touch a window in a different application.
980 // If the application takes too long to catch up then we drop all events preceding
981 // the touch into the other window.
982 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700983 int32_t displayId = motionEntry.displayId;
984 int32_t x = static_cast<int32_t>(
985 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
986 int32_t y = static_cast<int32_t>(
987 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700988
989 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500990 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700991 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700992 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700993 touchedWindowHandle->getApplicationToken() !=
994 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700995 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 ALOGI("Pruning input queue because user touched a different application while waiting "
997 "for %s",
998 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700999 return true;
1000 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001001
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001002 // Alternatively, maybe there's a spy window that could handle this event.
1003 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1004 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1005 for (const auto& windowHandle : touchedSpies) {
1006 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001007 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001008 // This spy window could take more input. Drop all events preceding this
1009 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001010 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001011 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001012 mAwaitedFocusedApplication->getName().c_str());
1013 return true;
1014 }
1015 }
1016 }
1017
1018 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1019 // yet been processed by some connections, the dispatcher will wait for these motion
1020 // events to be processed before dispatching the key event. This is because these motion events
1021 // may cause a new window to be launched, which the user might expect to receive focus.
1022 // To prevent waiting forever for such events, just send the key to the currently focused window
1023 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1024 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1025 "just send the pending key event to the focused window.");
1026 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001027 }
1028 return false;
1029}
1030
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001031bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 mInboundQueue.push_back(std::move(newEntry));
1034 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 traceInboundQueueLengthLocked();
1036
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001037 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001038 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 // Optimize app switch latency.
1040 // If the application takes too long to catch up then we drop all events preceding
1041 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001042 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001044 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001046 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001048 if (DEBUG_APP_SWITCH) {
1049 ALOGD("App switch is pending!");
1050 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001051 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 mAppSwitchSawKeyDown = false;
1053 needWake = true;
1054 }
1055 }
1056 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001057
1058 // If a new up event comes in, and the pending event with same key code has been asked
1059 // to try again later because of the policy. We have to reset the intercept key wake up
1060 // time for it may have been handled in the policy and could be dropped.
1061 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1062 mPendingEvent->type == EventEntry::Type::KEY) {
1063 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1064 if (pendingKey.keyCode == keyEntry.keyCode &&
1065 pendingKey.interceptKeyResult ==
1066 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1067 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1068 pendingKey.interceptKeyWakeupTime = 0;
1069 needWake = true;
1070 }
1071 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 break;
1073 }
1074
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001075 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1077 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001078 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001082 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001083 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1084 break;
1085 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001086 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001087 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001088 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001089 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001090 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1091 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001092 // nothing to do
1093 break;
1094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096
1097 return needWake;
1098}
1099
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001101 // Do not store sensor event in recent queue to avoid flooding the queue.
1102 if (entry->type != EventEntry::Type::SENSOR) {
1103 mRecentQueue.push_back(entry);
1104 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001105 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001106 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
1108}
1109
chaviw98318de2021-05-19 16:45:23 -05001110sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1111 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001112 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001113 bool addOutsideTargets,
1114 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001115 if (addOutsideTargets && touchState == nullptr) {
1116 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001119 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001120 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001121 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001122 continue;
1123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001125 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001126 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001127 return windowHandle;
1128 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001129
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001130 if (addOutsideTargets &&
1131 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001132 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1133 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 }
1135 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001136 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137}
1138
Prabir Pradhand65552b2021-10-07 11:23:50 -07001139std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1140 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001141 // Traverse windows from front to back and gather the touched spy windows.
1142 std::vector<sp<WindowInfoHandle>> spyWindows;
1143 const auto& windowHandles = getWindowHandlesLocked(displayId);
1144 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1145 const WindowInfo& info = *windowHandle->getInfo();
1146
Prabir Pradhand65552b2021-10-07 11:23:50 -07001147 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001148 continue;
1149 }
1150 if (!info.isSpy()) {
1151 // The first touched non-spy window was found, so return the spy windows touched so far.
1152 return spyWindows;
1153 }
1154 spyWindows.push_back(windowHandle);
1155 }
1156 return spyWindows;
1157}
1158
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001159void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 const char* reason;
1161 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001162 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001163 if (DEBUG_INBOUND_EVENT_DETAILS) {
1164 ALOGD("Dropped event because policy consumed it.");
1165 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 reason = "inbound event was dropped because the policy consumed it";
1167 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001168 case DropReason::DISABLED:
1169 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 ALOGI("Dropped event because input dispatch is disabled.");
1171 }
1172 reason = "inbound event was dropped because input dispatch is disabled";
1173 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001174 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 ALOGI("Dropped event because of pending overdue app switch.");
1176 reason = "inbound event was dropped because of pending overdue app switch";
1177 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001178 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 ALOGI("Dropped event because the current application is not responding and the user "
1180 "has started interacting with a different application.");
1181 reason = "inbound event was dropped because the current application is not responding "
1182 "and the user has started interacting with a different application";
1183 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001184 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001185 ALOGI("Dropped event because it is stale.");
1186 reason = "inbound event was dropped because it is stale";
1187 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001188 case DropReason::NO_POINTER_CAPTURE:
1189 ALOGI("Dropped event because there is no window with Pointer Capture.");
1190 reason = "inbound event was dropped because there is no window with Pointer Capture";
1191 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001192 case DropReason::NOT_DROPPED: {
1193 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001198 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001199 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1201 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001204 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001205 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1206 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1208 synthesizeCancelationEventsForAllConnectionsLocked(options);
1209 } else {
1210 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1211 synthesizeCancelationEventsForAllConnectionsLocked(options);
1212 }
1213 break;
1214 }
Chris Yef59a2f42020-10-16 12:55:26 -07001215 case EventEntry::Type::SENSOR: {
1216 break;
1217 }
arthurhungb89ccb02020-12-30 16:19:01 +08001218 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1219 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001220 break;
1221 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001222 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001223 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001224 case EventEntry::Type::CONFIGURATION_CHANGED:
1225 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001226 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001227 break;
1228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230}
1231
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001232static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1234 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001237bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1238 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1239 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1240 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241}
1242
1243bool InputDispatcher::isAppSwitchPendingLocked() {
1244 return mAppSwitchDueTime != LONG_LONG_MAX;
1245}
1246
1247void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1248 mAppSwitchDueTime = LONG_LONG_MAX;
1249
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001250 if (DEBUG_APP_SWITCH) {
1251 if (handled) {
1252 ALOGD("App switch has arrived.");
1253 } else {
1254 ALOGD("App switch was abandoned.");
1255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257}
1258
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001260 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261}
1262
Prabir Pradhancef936d2021-07-21 16:17:52 +00001263bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001264 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 return false;
1266 }
1267
1268 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001269 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001270 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001271 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1272 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001273 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 return true;
1275}
1276
Prabir Pradhancef936d2021-07-21 16:17:52 +00001277void InputDispatcher::postCommandLocked(Command&& command) {
1278 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279}
1280
1281void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001282 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001283 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001284 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 releaseInboundEventLocked(entry);
1286 }
1287 traceInboundQueueLengthLocked();
1288}
1289
1290void InputDispatcher::releasePendingEventLocked() {
1291 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001293 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
1295}
1296
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001297void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001299 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001300 if (DEBUG_DISPATCH_CYCLE) {
1301 ALOGD("Injected inbound event was dropped.");
1302 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 }
1305 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001306 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 }
1308 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309}
1310
1311void InputDispatcher::resetKeyRepeatLocked() {
1312 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001313 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 }
1315}
1316
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001317std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1318 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319
Michael Wright2e732952014-09-24 13:26:59 -07001320 uint32_t policyFlags = entry->policyFlags &
1321 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001323 std::shared_ptr<KeyEntry> newEntry =
1324 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1325 entry->source, entry->displayId, policyFlags, entry->action,
1326 entry->flags, entry->keyCode, entry->scanCode,
1327 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001329 newEntry->syntheticRepeat = true;
1330 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001332 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333}
1334
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001336 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001337 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1338 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340
1341 // Reset key repeating in case a keyboard device was added or removed or something.
1342 resetKeyRepeatLocked();
1343
1344 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001345 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1346 scoped_unlock unlock(mLock);
1347 mPolicy->notifyConfigurationChanged(eventTime);
1348 };
1349 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 return true;
1351}
1352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1354 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001355 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1356 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1357 entry.deviceId);
1358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359
liushenxiang42232912021-05-21 20:24:09 +08001360 // Reset key repeating in case a keyboard device was disabled or enabled.
1361 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1362 resetKeyRepeatLocked();
1363 }
1364
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001366 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 synthesizeCancelationEventsForAllConnectionsLocked(options);
1368 return true;
1369}
1370
Vishnu Nairad321cd2020-08-20 16:40:21 -07001371void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001372 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001373 if (mPendingEvent != nullptr) {
1374 // Move the pending event to the front of the queue. This will give the chance
1375 // for the pending event to get dispatched to the newly focused window
1376 mInboundQueue.push_front(mPendingEvent);
1377 mPendingEvent = nullptr;
1378 }
1379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380 std::unique_ptr<FocusEntry> focusEntry =
1381 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1382 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001383
1384 // This event should go to the front of the queue, but behind all other focus events
1385 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001386 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001387 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001388 [](const std::shared_ptr<EventEntry>& event) {
1389 return event->type == EventEntry::Type::FOCUS;
1390 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001391
1392 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001393 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001394}
1395
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001396void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001397 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001398 if (channel == nullptr) {
1399 return; // Window has gone away
1400 }
1401 InputTarget target;
1402 target.inputChannel = channel;
1403 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1404 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001405 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1406 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001407 std::string reason = std::string("reason=").append(entry->reason);
1408 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001409 dispatchEventLocked(currentTime, entry, {target});
1410}
1411
Prabir Pradhan99987712020-11-10 18:43:05 -08001412void InputDispatcher::dispatchPointerCaptureChangedLocked(
1413 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1414 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001415 dropReason = DropReason::NOT_DROPPED;
1416
Prabir Pradhan99987712020-11-10 18:43:05 -08001417 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001418 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001419
1420 if (entry->pointerCaptureRequest.enable) {
1421 // Enable Pointer Capture.
1422 if (haveWindowWithPointerCapture &&
1423 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001424 // This can happen if pointer capture is disabled and re-enabled before we notify the
1425 // app of the state change, so there is no need to notify the app.
1426 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1427 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001428 }
1429 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001430 // This can happen if a window requests capture and immediately releases capture.
1431 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001432 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001433 return;
1434 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001435 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1436 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1437 return;
1438 }
1439
Vishnu Nairc519ff72021-01-21 08:23:08 -08001440 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001441 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1442 mWindowTokenWithPointerCapture = token;
1443 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001444 // Disable Pointer Capture.
1445 // We do not check if the sequence number matches for requests to disable Pointer Capture
1446 // for two reasons:
1447 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1448 // to disable capture with the same sequence number: one generated by
1449 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1450 // Capture being disabled in InputReader.
1451 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1452 // actual Pointer Capture state that affects events being generated by input devices is
1453 // in InputReader.
1454 if (!haveWindowWithPointerCapture) {
1455 // Pointer capture was already forcefully disabled because of focus change.
1456 dropReason = DropReason::NOT_DROPPED;
1457 return;
1458 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001459 token = mWindowTokenWithPointerCapture;
1460 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001461 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001462 setPointerCaptureLocked(false);
1463 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001464 }
1465
1466 auto channel = getInputChannelLocked(token);
1467 if (channel == nullptr) {
1468 // Window has gone away, clean up Pointer Capture state.
1469 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001470 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001471 setPointerCaptureLocked(false);
1472 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001473 return;
1474 }
1475 InputTarget target;
1476 target.inputChannel = channel;
1477 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1478 entry->dispatchInProgress = true;
1479 dispatchEventLocked(currentTime, entry, {target});
1480
1481 dropReason = DropReason::NOT_DROPPED;
1482}
1483
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001484void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1485 const std::shared_ptr<TouchModeEntry>& entry) {
1486 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1487 getWindowHandlesLocked(mFocusedDisplayId);
1488 if (windowHandles.empty()) {
1489 return;
1490 }
1491 const std::vector<InputTarget> inputTargets =
1492 getInputTargetsFromWindowHandlesLocked(windowHandles);
1493 if (inputTargets.empty()) {
1494 return;
1495 }
1496 entry->dispatchInProgress = true;
1497 dispatchEventLocked(currentTime, entry, inputTargets);
1498}
1499
1500std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1501 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1502 std::vector<InputTarget> inputTargets;
1503 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1504 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1505 const sp<IBinder>& token = handle->getToken();
1506 if (token == nullptr) {
1507 continue;
1508 }
1509 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1510 if (channel == nullptr) {
1511 continue; // Window has gone away
1512 }
1513 InputTarget target;
1514 target.inputChannel = channel;
1515 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1516 inputTargets.push_back(target);
1517 }
1518 return inputTargets;
1519}
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001524 if (!entry->dispatchInProgress) {
1525 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1526 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1527 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1528 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001529 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 // We have seen two identical key downs in a row which indicates that the device
1531 // driver is automatically generating key repeats itself. We take note of the
1532 // repeat here, but we disable our own next key repeat timer since it is clear that
1533 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001534 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1535 // Make sure we don't get key down from a different device. If a different
1536 // device Id has same key pressed down, the new device Id will replace the
1537 // current one to hold the key repeat with repeat count reset.
1538 // In the future when got a KEY_UP on the device id, drop it and do not
1539 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1541 resetKeyRepeatLocked();
1542 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1543 } else {
1544 // Not a repeat. Save key down state in case we do see a repeat later.
1545 resetKeyRepeatLocked();
1546 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1547 }
1548 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001549 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1550 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001551 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001552 if (DEBUG_INBOUND_EVENT_DETAILS) {
1553 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1554 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001555 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 resetKeyRepeatLocked();
1557 }
1558
1559 if (entry->repeatCount == 1) {
1560 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1561 } else {
1562 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1563 }
1564
1565 entry->dispatchInProgress = true;
1566
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
1569
1570 // Handle case where the policy asked us to try again later last time.
1571 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1572 if (currentTime < entry->interceptKeyWakeupTime) {
1573 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1574 *nextWakeupTime = entry->interceptKeyWakeupTime;
1575 }
1576 return false; // wait until next wakeup
1577 }
1578 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1579 entry->interceptKeyWakeupTime = 0;
1580 }
1581
1582 // Give the policy a chance to intercept the key.
1583 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1584 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001585 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001586 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001587
1588 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1589 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1590 };
1591 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 return false; // wait for the command to run
1593 } else {
1594 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1595 }
1596 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001597 if (*dropReason == DropReason::NOT_DROPPED) {
1598 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600 }
1601
1602 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001603 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001604 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001605 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1606 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001607 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 return true;
1609 }
1610
1611 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001612 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001613 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001615 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 return false;
1617 }
1618
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001619 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 return true;
1622 }
1623
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001624 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001625 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626
1627 // Dispatch the key.
1628 dispatchEventLocked(currentTime, entry, inputTargets);
1629 return true;
1630}
1631
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001632void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001633 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1634 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1635 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1636 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1637 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1638 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1639 entry.metaState, entry.repeatCount, entry.downTime);
1640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641}
1642
Prabir Pradhancef936d2021-07-21 16:17:52 +00001643void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1644 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001645 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001646 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1647 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1648 "source=0x%x, sensorType=%s",
1649 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001650 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001651 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001652 auto command = [this, entry]() REQUIRES(mLock) {
1653 scoped_unlock unlock(mLock);
1654
1655 if (entry->accuracyChanged) {
1656 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1657 }
1658 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1659 entry->hwTimestamp, entry->values);
1660 };
1661 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001662}
1663
1664bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001665 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1666 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001667 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001668 }
Chris Yef59a2f42020-10-16 12:55:26 -07001669 { // acquire lock
1670 std::scoped_lock _l(mLock);
1671
1672 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1673 std::shared_ptr<EventEntry> entry = *it;
1674 if (entry->type == EventEntry::Type::SENSOR) {
1675 it = mInboundQueue.erase(it);
1676 releaseInboundEventLocked(entry);
1677 }
1678 }
1679 }
1680 return true;
1681}
1682
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001683bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001684 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001685 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001687 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 entry->dispatchInProgress = true;
1689
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001690 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 }
1692
1693 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001694 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001695 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001696 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1697 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 return true;
1699 }
1700
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001701 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702
1703 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001704 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705
1706 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001707 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 if (isPointerEvent) {
1709 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001711 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 } else {
1714 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001715 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001716 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001718 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 return false;
1720 }
1721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001722 setInjectionResult(*entry, injectionResult);
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001723 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
1724 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001725 return true;
1726 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001727 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001728 CancelationOptions::Mode mode(isPointerEvent
1729 ? CancelationOptions::CANCEL_POINTER_EVENTS
1730 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1731 CancelationOptions options(mode, "input event injection failed");
1732 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 return true;
1734 }
1735
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001736 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738
1739 // Dispatch the motion.
1740 if (conflictingPointerActions) {
1741 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001742 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 synthesizeCancelationEventsForAllConnectionsLocked(options);
1744 }
1745 dispatchEventLocked(currentTime, entry, inputTargets);
1746 return true;
1747}
1748
chaviw98318de2021-05-19 16:45:23 -05001749void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001750 bool isExiting, const int32_t rawX,
1751 const int32_t rawY) {
1752 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001753 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001754 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1755 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001756
1757 enqueueInboundEventLocked(std::move(dragEntry));
1758}
1759
1760void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1761 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1762 if (channel == nullptr) {
1763 return; // Window has gone away
1764 }
1765 InputTarget target;
1766 target.inputChannel = channel;
1767 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1768 entry->dispatchInProgress = true;
1769 dispatchEventLocked(currentTime, entry, {target});
1770}
1771
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001772void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001773 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1774 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1775 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001776 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001777 "metaState=0x%x, buttonState=0x%x,"
1778 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1779 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001780 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1781 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1782 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001784 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1785 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1786 "x=%f, y=%f, pressure=%f, size=%f, "
1787 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1788 "orientation=%f",
1789 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1796 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1797 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1798 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801}
1802
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001803void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1804 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001806 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001807 if (DEBUG_DISPATCH_CYCLE) {
1808 ALOGD("dispatchEventToCurrentInputTargets");
1809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001811 updateInteractionTokensLocked(*eventEntry, inputTargets);
1812
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1814
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001815 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001817 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001818 sp<Connection> connection =
1819 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001820 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001821 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001823 if (DEBUG_FOCUS) {
1824 ALOGD("Dropping event delivery to target with channel '%s' because it "
1825 "is no longer registered with the input dispatcher.",
1826 inputTarget.inputChannel->getName().c_str());
1827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 }
1829 }
1830}
1831
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001832void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1833 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1834 // If the policy decides to close the app, we will get a channel removal event via
1835 // unregisterInputChannel, and will clean up the connection that way. We are already not
1836 // sending new pointers to the connection when it blocked, but focused events will continue to
1837 // pile up.
1838 ALOGW("Canceling events for %s because it is unresponsive",
1839 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001840 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1842 "application not responding");
1843 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
1845}
1846
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001847void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001848 if (DEBUG_FOCUS) {
1849 ALOGD("Resetting ANR timeouts.");
1850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851
1852 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001854 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855}
1856
Tiger Huang721e26f2018-07-24 22:26:19 +08001857/**
1858 * Get the display id that the given event should go to. If this event specifies a valid display id,
1859 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1860 * Focused display is the display that the user most recently interacted with.
1861 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001862int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001863 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001864 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001865 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001866 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1867 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001868 break;
1869 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001870 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001871 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1872 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001873 break;
1874 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001875 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001876 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001877 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001878 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001879 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001880 case EventEntry::Type::SENSOR:
1881 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001882 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 return ADISPLAY_ID_NONE;
1884 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001885 }
1886 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1887}
1888
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001889bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1890 const char* focusedWindowName) {
1891 if (mAnrTracker.empty()) {
1892 // already processed all events that we waited for
1893 mKeyIsWaitingForEventsTimeout = std::nullopt;
1894 return false;
1895 }
1896
1897 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1898 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001899 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001900 mKeyIsWaitingForEventsTimeout = currentTime +
1901 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1902 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001903 return true;
1904 }
1905
1906 // We still have pending events, and already started the timer
1907 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1908 return true; // Still waiting
1909 }
1910
1911 // Waited too long, and some connection still hasn't processed all motions
1912 // Just send the key to the focused window
1913 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1914 focusedWindowName);
1915 mKeyIsWaitingForEventsTimeout = std::nullopt;
1916 return false;
1917}
1918
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001919InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1920 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1921 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001922 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923
Tiger Huang721e26f2018-07-24 22:26:19 +08001924 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001925 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001927 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1928
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 // If there is no currently focused window and no focused application
1930 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1932 ALOGI("Dropping %s event because there is no focused window or focused application in "
1933 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001934 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
Vishnu Nair062a8672021-09-03 16:07:44 -07001938 // Drop key events if requested by input feature
1939 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1940 return InputEventInjectionResult::FAILED;
1941 }
1942
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1944 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1945 // start interacting with another application via touch (app switch). This code can be removed
1946 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1947 // an app is expected to have a focused window.
1948 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1949 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1950 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001951 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1952 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1953 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001954 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001955 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 ALOGW("Waiting because no window has focus but %s may eventually add a "
1957 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001958 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001960 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1962 // Already raised ANR. Drop the event
1963 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001964 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 } else {
1967 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969 }
1970 }
1971
1972 // we have a valid, non-null focused window
1973 resetNoFocusedWindowTimeoutLocked();
1974
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001975 // Check permissions.
1976 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
1977 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
1979
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001980 if (focusedWindowHandle->getInfo()->inputConfig.test(
1981 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001982 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001983 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 }
1985
1986 // If the event is a key event, then we must wait for all previous events to
1987 // complete before delivering it because previous events may have the
1988 // side-effect of transferring focus to a different window and we want to
1989 // ensure that the following keys are sent to the new window.
1990 //
1991 // Suppose the user touches a button in a window then immediately presses "A".
1992 // If the button causes a pop-up window to appear then we want to ensure that
1993 // the "A" key is delivered to the new pop-up window. This is because users
1994 // often anticipate pending UI changes when typing on a keyboard.
1995 // To obtain this behavior, we must serialize key events with respect to all
1996 // prior input events.
1997 if (entry.type == EventEntry::Type::KEY) {
1998 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1999 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002000 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 }
2003
2004 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08002005 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002006 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
2007 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
2009 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002010 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011}
2012
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013/**
2014 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2015 * that are currently unresponsive.
2016 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002017std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2018 const std::vector<Monitor>& monitors) const {
2019 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002020 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002021 [this](const Monitor& monitor) REQUIRES(mLock) {
2022 sp<Connection> connection =
2023 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 if (connection == nullptr) {
2025 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002026 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 return false;
2028 }
2029 if (!connection->responsive) {
2030 ALOGW("Unresponsive monitor %s will not get the new gesture",
2031 connection->inputChannel->getName().c_str());
2032 return false;
2033 }
2034 return true;
2035 });
2036 return responsiveMonitors;
2037}
2038
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002039InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2040 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2041 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002042 ATRACE_CALL();
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002043 enum InjectionPermission {
2044 INJECTION_PERMISSION_UNKNOWN,
2045 INJECTION_PERMISSION_GRANTED,
2046 INJECTION_PERMISSION_DENIED
2047 };
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 // For security reasons, we defer updating the touch state until we are sure that
2050 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002051 const int32_t displayId = entry.displayId;
2052 const int32_t action = entry.action;
2053 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054
2055 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002056 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002057 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05002058 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2059 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002061 // Copy current touch state into tempTouchState.
2062 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2063 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002064 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002066 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2067 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002068 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002069 }
2070
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002071 bool isSplit = tempTouchState.split;
2072 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2073 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2074 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002075
2076 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2077 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2078 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2079 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2080 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002081 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 bool wrongDevice = false;
2083 if (newGesture) {
2084 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002085 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002086 ALOGI("Dropping event because a pointer for a different device is already down "
2087 "in display %" PRId32,
2088 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002089 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002090 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 switchedDevice = false;
2092 wrongDevice = true;
2093 goto Failed;
2094 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 tempTouchState.reset();
2096 tempTouchState.down = down;
2097 tempTouchState.deviceId = entry.deviceId;
2098 tempTouchState.source = entry.source;
2099 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002101 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002102 ALOGI("Dropping move event because a pointer for a different device is already active "
2103 "in display %" PRId32,
2104 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002105 // TODO: test multiple simultaneous input streams.
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002106 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002107 switchedDevice = false;
2108 wrongDevice = true;
2109 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 }
2111
2112 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2113 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2114
Garfield Tan00f511d2019-06-12 16:55:40 -07002115 int32_t x;
2116 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002117 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002118 // Always dispatch mouse events to cursor position.
2119 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002120 x = int32_t(entry.xCursorPosition);
2121 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002122 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002123 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2124 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002125 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002126 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002127 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002128 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002129 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002130
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002132 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002133 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2134 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002136 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002137 }
2138
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002139 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002140 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002141 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2142 // New window supports splitting, but we should never split mouse events.
2143 isSplit = !isFromMouse;
2144 } else if (isSplit) {
2145 // New window does not support splitting but we have already split events.
2146 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002147 newTouchedWindowHandle = nullptr;
2148 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002149 } else {
2150 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002151 // be delivered to a new window which supports split touch. Pointers from a mouse device
2152 // should never be split.
2153 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002154 }
2155
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002156 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002157 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002158 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2159 newHoverWindowHandle = nullptr;
2160 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002161 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002162 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002163 }
2164
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002165 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002166 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002167 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002168 // Process the foreground window first so that it is the first to receive the event.
2169 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002170 }
2171
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002172 if (newTouchedWindows.empty()) {
2173 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2174 x, y, displayId);
2175 injectionResult = InputEventInjectionResult::FAILED;
2176 goto Failed;
2177 }
2178
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2180 const WindowInfo& info = *windowHandle->getInfo();
2181
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002182 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183 ALOGI("Not sending touch event to %s because it is paused",
2184 windowHandle->getName().c_str());
2185 continue;
2186 }
2187
2188 // Ensure the window has a connection and the connection is responsive
2189 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2190 if (!isResponsive) {
2191 ALOGW("Not sending touch gesture to %s because it is not responsive",
2192 windowHandle->getName().c_str());
2193 continue;
2194 }
2195
2196 // Drop events that can't be trusted due to occlusion
2197 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2198 TouchOcclusionInfo occlusionInfo =
2199 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2200 if (!isTouchTrustedLocked(occlusionInfo)) {
2201 if (DEBUG_TOUCH_OCCLUSION) {
2202 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2203 for (const auto& log : occlusionInfo.debugInfo) {
2204 ALOGD("%s", log.c_str());
2205 }
2206 }
2207 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2208 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2209 ALOGW("Dropping untrusted touch event due to %s/%d",
2210 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2211 continue;
2212 }
2213 }
2214 }
2215
2216 // Drop touch events if requested by input feature
2217 if (shouldDropInput(entry, windowHandle)) {
2218 continue;
2219 }
2220
2221 // Set target flags.
2222 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2223
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002224 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2225 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002226 targetFlags |= InputTarget::FLAG_FOREGROUND;
2227 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002228
2229 if (isSplit) {
2230 targetFlags |= InputTarget::FLAG_SPLIT;
2231 }
2232 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2233 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2234 } else if (isWindowObscuredLocked(windowHandle)) {
2235 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2236 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002237
2238 // Update the temporary touch state.
2239 BitSet32 pointerIds;
2240 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002241 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002242 pointerIds.markBit(pointerId);
2243 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244
2245 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 } else {
2248 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2249
2250 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002252 if (DEBUG_FOCUS) {
2253 ALOGD("Dropping event because the pointer is not down or we previously "
2254 "dropped the pointer down event in display %" PRId32,
2255 displayId);
2256 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002257 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 goto Failed;
2259 }
2260
arthurhung6d4bed92021-03-17 11:59:33 +08002261 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002262
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002264 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002265 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002266 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2267 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268
Prabir Pradhand65552b2021-10-07 11:23:50 -07002269 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002270 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002271 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002272 newTouchedWindowHandle =
2273 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002274
2275 // Drop touch events if requested by input feature
2276 if (newTouchedWindowHandle != nullptr &&
2277 shouldDropInput(entry, newTouchedWindowHandle)) {
2278 newTouchedWindowHandle = nullptr;
2279 }
2280
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2282 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002283 if (DEBUG_FOCUS) {
2284 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2285 oldTouchedWindowHandle->getName().c_str(),
2286 newTouchedWindowHandle->getName().c_str(), displayId);
2287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002289 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2290 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2291 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292
2293 // Make a slippery entrance into the new window.
2294 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002295 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002298 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2299 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2300 targetFlags |= InputTarget::FLAG_FOREGROUND;
2301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 if (isSplit) {
2303 targetFlags |= InputTarget::FLAG_SPLIT;
2304 }
2305 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2306 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002307 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2308 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
2310
2311 BitSet32 pointerIds;
2312 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002313 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002315 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317 }
2318 }
2319
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002320 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 // Let the previous window know that the hover sequence is over, unless we already did
2323 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002324 if (mLastHoverWindowHandle != nullptr &&
2325 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2326 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002327 if (DEBUG_HOVER) {
2328 ALOGD("Sending hover exit event to window %s.",
2329 mLastHoverWindowHandle->getName().c_str());
2330 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002331 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2332 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 }
2334
Garfield Tandf26e862020-07-01 20:18:19 -07002335 // Let the new window know that the hover sequence is starting, unless we already did it
2336 // when dispatching it as is to newTouchedWindowHandle.
2337 if (newHoverWindowHandle != nullptr &&
2338 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2339 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002340 if (DEBUG_HOVER) {
2341 ALOGD("Sending hover enter event to window %s.",
2342 newHoverWindowHandle->getName().c_str());
2343 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002344 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2345 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2346 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 }
2348 }
2349
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002350 // Ensure that we have at least one foreground window or at least one window that cannot be a
2351 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2352 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2353 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002354 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2355 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002356 return !canReceiveForegroundTouches(
2357 *touchedWindow.windowHandle->getInfo()) ||
2358 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002359 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002360 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2361 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002362 injectionResult = InputEventInjectionResult::FAILED;
2363 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 }
2365
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002366 // Check permission to inject into all touched foreground windows.
2367 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2368 [this, &entry](const TouchedWindow& touchedWindow) {
2369 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2370 !checkInjectionPermission(touchedWindow.windowHandle,
2371 entry.injectionState);
2372 })) {
2373 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2374 injectionPermission = INJECTION_PERMISSION_DENIED;
2375 goto Failed;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002376 }
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002377 // Permission granted to inject into all touched foreground windows.
2378 injectionPermission = INJECTION_PERMISSION_GRANTED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002379
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 // Check whether windows listening for outside touches are owned by the same UID. If it is
2381 // set the policy flag that we will not reveal coordinate information to this window.
2382 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002383 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002384 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002385 if (foregroundWindowHandle) {
2386 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002387 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002388 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002389 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2390 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2391 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002392 InputTarget::FLAG_ZERO_COORDS,
2393 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396 }
2397 }
2398 }
2399
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 // If this is the first pointer going down and the touched window has a wallpaper
2401 // then also add the touched wallpaper windows so they are locked in for the duration
2402 // of the touch gesture.
2403 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2404 // engine only supports touch events. We would need to add a mechanism similar
2405 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2406 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002407 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002408 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002409 if (foregroundWindowHandle &&
2410 foregroundWindowHandle->getInfo()->inputConfig.test(
2411 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002412 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002413 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002414 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2415 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002416 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002417 windowHandle->getInfo()->inputConfig.test(
2418 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002419 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002420 .addOrUpdateWindow(windowHandle,
2421 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2422 InputTarget::
2423 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2424 InputTarget::FLAG_DISPATCH_AS_IS,
2425 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 }
2427 }
2428 }
2429 }
2430
2431 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002432 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002434 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002436 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
2438
2439 // Drop the outside or hover touch windows since we will not care about them
2440 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002441 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442
2443Failed:
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002444 // Check injection permission once and for all.
2445 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
2446 if (checkInjectionPermission(nullptr, entry.injectionState)) {
2447 injectionPermission = INJECTION_PERMISSION_GRANTED;
2448 } else {
2449 injectionPermission = INJECTION_PERMISSION_DENIED;
2450 }
2451 }
2452
2453 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2454 return injectionResult;
2455 }
2456
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002458 if (!wrongDevice) {
2459 if (switchedDevice) {
2460 if (DEBUG_FOCUS) {
2461 ALOGD("Conflicting pointer actions: Switched to a different device.");
2462 }
2463 *outConflictingPointerActions = true;
2464 }
2465
2466 if (isHoverAction) {
2467 // Started hovering, therefore no longer down.
2468 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002469 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002470 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2471 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 *outConflictingPointerActions = true;
2474 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002475 tempTouchState.reset();
2476 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2477 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2478 tempTouchState.deviceId = entry.deviceId;
2479 tempTouchState.source = entry.source;
2480 tempTouchState.displayId = displayId;
2481 }
2482 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2483 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2484 // All pointers up or canceled.
2485 tempTouchState.reset();
2486 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2487 // First pointer went down.
2488 if (oldState && oldState->down) {
2489 if (DEBUG_FOCUS) {
2490 ALOGD("Conflicting pointer actions: Down received while already down.");
2491 }
2492 *outConflictingPointerActions = true;
2493 }
2494 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2495 // One pointer went up.
2496 if (isSplit) {
2497 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2498 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002500 for (size_t i = 0; i < tempTouchState.windows.size();) {
2501 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2502 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2503 touchedWindow.pointerIds.clearBit(pointerId);
2504 if (touchedWindow.pointerIds.isEmpty()) {
2505 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2506 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002509 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002511 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002512 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002513
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002514 // Save changes unless the action was scroll in which case the temporary touch
2515 // state was only valid for this one action.
2516 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2517 if (tempTouchState.displayId >= 0) {
2518 mTouchStatesByDisplay[displayId] = tempTouchState;
2519 } else {
2520 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002524 // Update hover state.
2525 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 return injectionResult;
2529}
2530
arthurhung6d4bed92021-03-17 11:59:33 +08002531void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002532 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2533 // have an explicit reason to support it.
2534 constexpr bool isStylus = false;
2535
chaviw98318de2021-05-19 16:45:23 -05002536 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002537 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002538 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002539 if (dropWindow) {
2540 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002541 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002542 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002543 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002544 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002545 }
2546 mDragState.reset();
2547}
2548
2549void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung54745652022-04-20 07:17:41 +00002550 if (!mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002551 return;
2552 }
2553
arthurhung6d4bed92021-03-17 11:59:33 +08002554 if (!mDragState->isStartDrag) {
2555 mDragState->isStartDrag = true;
2556 mDragState->isStylusButtonDownAtStart =
2557 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2558 }
2559
Arthur Hung54745652022-04-20 07:17:41 +00002560 // Find the pointer index by id.
2561 int32_t pointerIndex = 0;
2562 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2563 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2564 if (pointerProperties.id == mDragState->pointerId) {
2565 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002566 }
Arthur Hung54745652022-04-20 07:17:41 +00002567 }
arthurhung6d4bed92021-03-17 11:59:33 +08002568
Arthur Hung54745652022-04-20 07:17:41 +00002569 if (uint32_t(pointerIndex) == entry.pointerCount) {
2570 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002571 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002572 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002573 return;
2574 }
2575
2576 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2577 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2578 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2579
2580 switch (maskedAction) {
2581 case AMOTION_EVENT_ACTION_MOVE: {
2582 // Handle the special case : stylus button no longer pressed.
2583 bool isStylusButtonDown =
2584 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2585 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2586 finishDragAndDrop(entry.displayId, x, y);
2587 return;
2588 }
2589
2590 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2591 // until we have an explicit reason to support it.
2592 constexpr bool isStylus = false;
2593
2594 const sp<WindowInfoHandle> hoverWindowHandle =
2595 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2596 isStylus, false /*addOutsideTargets*/,
2597 true /*ignoreDragWindow*/);
2598 // enqueue drag exit if needed.
2599 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2600 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2601 if (mDragState->dragHoverWindowHandle != nullptr) {
2602 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2603 y);
2604 }
2605 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2606 }
2607 // enqueue drag location if needed.
2608 if (hoverWindowHandle != nullptr) {
2609 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2610 }
2611 break;
2612 }
2613
2614 case AMOTION_EVENT_ACTION_POINTER_UP:
2615 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2616 break;
2617 }
2618 // The drag pointer is up.
2619 [[fallthrough]];
2620 case AMOTION_EVENT_ACTION_UP:
2621 finishDragAndDrop(entry.displayId, x, y);
2622 break;
2623 case AMOTION_EVENT_ACTION_CANCEL: {
2624 ALOGD("Receiving cancel when drag and drop.");
2625 sendDropWindowCommandLocked(nullptr, 0, 0);
2626 mDragState.reset();
2627 break;
2628 }
arthurhungb89ccb02020-12-30 16:19:01 +08002629 }
2630}
2631
chaviw98318de2021-05-19 16:45:23 -05002632void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002633 int32_t targetFlags, BitSet32 pointerIds,
2634 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002635 std::vector<InputTarget>::iterator it =
2636 std::find_if(inputTargets.begin(), inputTargets.end(),
2637 [&windowHandle](const InputTarget& inputTarget) {
2638 return inputTarget.inputChannel->getConnectionToken() ==
2639 windowHandle->getToken();
2640 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002641
chaviw98318de2021-05-19 16:45:23 -05002642 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002643
2644 if (it == inputTargets.end()) {
2645 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002646 std::shared_ptr<InputChannel> inputChannel =
2647 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002648 if (inputChannel == nullptr) {
2649 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2650 return;
2651 }
2652 inputTarget.inputChannel = inputChannel;
2653 inputTarget.flags = targetFlags;
2654 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002655 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2656 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002657 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002658 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002659 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002660 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002661 inputTargets.push_back(inputTarget);
2662 it = inputTargets.end() - 1;
2663 }
2664
2665 ALOG_ASSERT(it->flags == targetFlags);
2666 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2667
chaviw1ff3d1e2020-07-01 15:53:47 -07002668 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669}
2670
Michael Wright3dd60e22019-03-27 22:06:44 +00002671void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002672 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002673 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2674 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002675
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002676 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2677 InputTarget target;
2678 target.inputChannel = monitor.inputChannel;
2679 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2680 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2681 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002682 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002683 target.setDefaultPointerTransform(target.displayTransform);
2684 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 }
2686}
2687
Prabir Pradhan4df80f52022-04-05 18:33:16 +00002688bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
2689 const InjectionState* injectionState) {
2690 if (injectionState &&
2691 (windowHandle == nullptr ||
2692 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2693 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
2694 if (windowHandle != nullptr) {
2695 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
2696 "owned by uid %d",
2697 injectionState->injectorPid, injectionState->injectorUid,
2698 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
2699 } else {
2700 ALOGW("Permission denied: injecting event from pid %d uid %d",
2701 injectionState->injectorPid, injectionState->injectorUid);
2702 }
2703 return false;
2704 }
2705 return true;
2706}
2707
Robert Carrc9bf1d32020-04-13 17:21:08 -07002708/**
2709 * Indicate whether one window handle should be considered as obscuring
2710 * another window handle. We only check a few preconditions. Actually
2711 * checking the bounds is left to the caller.
2712 */
chaviw98318de2021-05-19 16:45:23 -05002713static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2714 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002715 // Compare by token so cloned layers aren't counted
2716 if (haveSameToken(windowHandle, otherHandle)) {
2717 return false;
2718 }
2719 auto info = windowHandle->getInfo();
2720 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002721 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002722 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002723 } else if (otherInfo->alpha == 0 &&
2724 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002725 // Those act as if they were invisible, so we don't need to flag them.
2726 // We do want to potentially flag touchable windows even if they have 0
2727 // opacity, since they can consume touches and alter the effects of the
2728 // user interaction (eg. apps that rely on
2729 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2730 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2731 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002732 } else if (info->ownerUid == otherInfo->ownerUid) {
2733 // If ownerUid is the same we don't generate occlusion events as there
2734 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002735 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002736 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002737 return false;
2738 } else if (otherInfo->displayId != info->displayId) {
2739 return false;
2740 }
2741 return true;
2742}
2743
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002744/**
2745 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2746 * untrusted, one should check:
2747 *
2748 * 1. If result.hasBlockingOcclusion is true.
2749 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2750 * BLOCK_UNTRUSTED.
2751 *
2752 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2753 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2754 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2755 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2756 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2757 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2758 *
2759 * If neither of those is true, then it means the touch can be allowed.
2760 */
2761InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002762 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2763 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002764 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002765 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002766 TouchOcclusionInfo info;
2767 info.hasBlockingOcclusion = false;
2768 info.obscuringOpacity = 0;
2769 info.obscuringUid = -1;
2770 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002771 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002772 if (windowHandle == otherHandle) {
2773 break; // All future windows are below us. Exit early.
2774 }
chaviw98318de2021-05-19 16:45:23 -05002775 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002776 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2777 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002778 if (DEBUG_TOUCH_OCCLUSION) {
2779 info.debugInfo.push_back(
2780 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2781 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002782 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2783 // we perform the checks below to see if the touch can be propagated or not based on the
2784 // window's touch occlusion mode
2785 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2786 info.hasBlockingOcclusion = true;
2787 info.obscuringUid = otherInfo->ownerUid;
2788 info.obscuringPackage = otherInfo->packageName;
2789 break;
2790 }
2791 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2792 uint32_t uid = otherInfo->ownerUid;
2793 float opacity =
2794 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2795 // Given windows A and B:
2796 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2797 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2798 opacityByUid[uid] = opacity;
2799 if (opacity > info.obscuringOpacity) {
2800 info.obscuringOpacity = opacity;
2801 info.obscuringUid = uid;
2802 info.obscuringPackage = otherInfo->packageName;
2803 }
2804 }
2805 }
2806 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002807 if (DEBUG_TOUCH_OCCLUSION) {
2808 info.debugInfo.push_back(
2809 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2810 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002811 return info;
2812}
2813
chaviw98318de2021-05-19 16:45:23 -05002814std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002815 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002816 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2817 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2818 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2819 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002820 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2821 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2822 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2823 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2824 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002825 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002826 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002827}
2828
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002829bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2830 if (occlusionInfo.hasBlockingOcclusion) {
2831 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2832 occlusionInfo.obscuringUid);
2833 return false;
2834 }
2835 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2836 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2837 "%.2f, maximum allowed = %.2f)",
2838 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2839 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2840 return false;
2841 }
2842 return true;
2843}
2844
chaviw98318de2021-05-19 16:45:23 -05002845bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002848 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2849 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002850 if (windowHandle == otherHandle) {
2851 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 }
chaviw98318de2021-05-19 16:45:23 -05002853 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002854 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002855 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 return true;
2857 }
2858 }
2859 return false;
2860}
2861
chaviw98318de2021-05-19 16:45:23 -05002862bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002863 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002864 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2865 const WindowInfo* windowInfo = windowHandle->getInfo();
2866 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002867 if (windowHandle == otherHandle) {
2868 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002869 }
chaviw98318de2021-05-19 16:45:23 -05002870 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002871 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002872 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002873 return true;
2874 }
2875 }
2876 return false;
2877}
2878
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002879std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002880 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002881 if (applicationHandle != nullptr) {
2882 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002883 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 } else {
2885 return applicationHandle->getName();
2886 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002887 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002888 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002890 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 }
2892}
2893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002895 if (!isUserActivityEvent(eventEntry)) {
2896 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002897 return;
2898 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002899 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002900 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002901 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002902 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002903 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002904 if (DEBUG_DISPATCH_CYCLE) {
2905 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 return;
2908 }
2909 }
2910
2911 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002913 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002914 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2915 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 return;
2917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002919 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 eventType = USER_ACTIVITY_EVENT_TOUCH;
2921 }
2922 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002924 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002925 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2926 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 return;
2928 }
2929 eventType = USER_ACTIVITY_EVENT_BUTTON;
2930 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002932 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002933 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002934 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002935 break;
2936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
2938
Prabir Pradhancef936d2021-07-21 16:17:52 +00002939 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2940 REQUIRES(mLock) {
2941 scoped_unlock unlock(mLock);
2942 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2943 };
2944 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945}
2946
2947void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002949 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002950 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002951 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002953 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002954 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002955 ATRACE_NAME(message.c_str());
2956 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002957 if (DEBUG_DISPATCH_CYCLE) {
2958 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2959 "globalScaleFactor=%f, pointerIds=0x%x %s",
2960 connection->getInputChannelName().c_str(), inputTarget.flags,
2961 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2962 inputTarget.getPointerInfoString().c_str());
2963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964
2965 // Skip this event if the connection status is not normal.
2966 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002967 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002968 if (DEBUG_DISPATCH_CYCLE) {
2969 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002970 connection->getInputChannelName().c_str(),
2971 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 return;
2974 }
2975
2976 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002977 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2978 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2979 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002980 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002982 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002983 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002985 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 if (!splitMotionEntry) {
2987 return; // split event was dropped
2988 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002989 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2990 std::string reason = std::string("reason=pointer cancel on split window");
2991 android_log_event_list(LOGTAG_INPUT_CANCEL)
2992 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2993 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002994 if (DEBUG_FOCUS) {
2995 ALOGD("channel '%s' ~ Split motion event.",
2996 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002998 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002999 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3000 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 return;
3002 }
3003 }
3004
3005 // Not splitting. Enqueue dispatch entries for the event as is.
3006 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3007}
3008
3009void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003011 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003012 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003013 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003015 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003016 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003017 ATRACE_NAME(message.c_str());
3018 }
3019
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003020 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021
3022 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003023 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003025 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003027 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003029 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003031 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003033 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035
3036 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003037 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 startDispatchCycleLocked(currentTime, connection);
3039 }
3040}
3041
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003043 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003044 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003046 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3048 connection->getInputChannelName().c_str(),
3049 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003050 ATRACE_NAME(message.c_str());
3051 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003052 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 if (!(inputTargetFlags & dispatchMode)) {
3054 return;
3055 }
3056 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3057
3058 // This is a new event.
3059 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003060 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003061 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003063 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3064 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003065 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003067 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003068 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003069 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003070 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003071 dispatchEntry->resolvedAction = keyEntry.action;
3072 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3075 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003076 if (DEBUG_DISPATCH_CYCLE) {
3077 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3078 "event",
3079 connection->getInputChannelName().c_str());
3080 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 return; // skip the inconsistent event
3082 }
3083 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003086 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003087 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003088 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3089 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3090 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3091 static_cast<int32_t>(IdGenerator::Source::OTHER);
3092 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3094 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3095 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3096 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3097 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3098 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3099 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3100 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3101 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3102 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3103 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003104 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003105 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 }
3107 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003108 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3109 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003110 if (DEBUG_DISPATCH_CYCLE) {
3111 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3112 "enter event",
3113 connection->getInputChannelName().c_str());
3114 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003115 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3116 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003120 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3122 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3123 }
3124 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3125 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3129 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003130 if (DEBUG_DISPATCH_CYCLE) {
3131 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3132 "event",
3133 connection->getInputChannelName().c_str());
3134 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 return; // skip the inconsistent event
3136 }
3137
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003138 dispatchEntry->resolvedEventId =
3139 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3140 ? mIdGenerator.nextId()
3141 : motionEntry.id;
3142 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3143 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3144 ") to MotionEvent(id=0x%" PRIx32 ").",
3145 motionEntry.id, dispatchEntry->resolvedEventId);
3146 ATRACE_NAME(message.c_str());
3147 }
3148
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003149 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3150 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3151 // Skip reporting pointer down outside focus to the policy.
3152 break;
3153 }
3154
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003155 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003156 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157
3158 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003160 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003161 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003162 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3163 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003164 break;
3165 }
Chris Yef59a2f42020-10-16 12:55:26 -07003166 case EventEntry::Type::SENSOR: {
3167 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3168 break;
3169 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003170 case EventEntry::Type::CONFIGURATION_CHANGED:
3171 case EventEntry::Type::DEVICE_RESET: {
3172 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003173 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003174 break;
3175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
3177
3178 // Remember that we are waiting for this dispatch to complete.
3179 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003180 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182
3183 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003184 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003185 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003186}
3187
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003188/**
3189 * This function is purely for debugging. It helps us understand where the user interaction
3190 * was taking place. For example, if user is touching launcher, we will see a log that user
3191 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3192 * We will see both launcher and wallpaper in that list.
3193 * Once the interaction with a particular set of connections starts, no new logs will be printed
3194 * until the set of interacted connections changes.
3195 *
3196 * The following items are skipped, to reduce the logspam:
3197 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3198 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3199 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3200 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3201 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003202 */
3203void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3204 const std::vector<InputTarget>& targets) {
3205 // Skip ACTION_UP events, and all events other than keys and motions
3206 if (entry.type == EventEntry::Type::KEY) {
3207 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3208 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3209 return;
3210 }
3211 } else if (entry.type == EventEntry::Type::MOTION) {
3212 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3213 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3214 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3215 return;
3216 }
3217 } else {
3218 return; // Not a key or a motion
3219 }
3220
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003221 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003222 std::vector<sp<Connection>> newConnections;
3223 for (const InputTarget& target : targets) {
3224 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3225 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3226 continue; // Skip windows that receive ACTION_OUTSIDE
3227 }
3228
3229 sp<IBinder> token = target.inputChannel->getConnectionToken();
3230 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003231 if (connection == nullptr) {
3232 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003233 }
3234 newConnectionTokens.insert(std::move(token));
3235 newConnections.emplace_back(connection);
3236 }
3237 if (newConnectionTokens == mInteractionConnectionTokens) {
3238 return; // no change
3239 }
3240 mInteractionConnectionTokens = newConnectionTokens;
3241
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003242 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003243 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003244 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003245 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003246 std::string message = "Interaction with: " + targetList;
3247 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003248 message += "<none>";
3249 }
3250 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3251}
3252
chaviwfd6d3512019-03-25 13:23:49 -07003253void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003254 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003255 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003256 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3257 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003258 return;
3259 }
3260
Vishnu Nairc519ff72021-01-21 08:23:08 -08003261 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003262 if (focusedToken == token) {
3263 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003264 return;
3265 }
3266
Prabir Pradhancef936d2021-07-21 16:17:52 +00003267 auto command = [this, token]() REQUIRES(mLock) {
3268 scoped_unlock unlock(mLock);
3269 mPolicy->onPointerDownOutsideFocus(token);
3270 };
3271 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272}
3273
3274void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003275 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003276 if (ATRACE_ENABLED()) {
3277 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003278 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003279 ATRACE_NAME(message.c_str());
3280 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003281 if (DEBUG_DISPATCH_CYCLE) {
3282 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003285 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003286 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003288 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003289 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290
3291 // Publish the event.
3292 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3294 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003295 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3297 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003300 status = connection->inputPublisher
3301 .publishKeyEvent(dispatchEntry->seq,
3302 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3303 keyEntry.source, keyEntry.displayId,
3304 std::move(hmac), dispatchEntry->resolvedAction,
3305 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3306 keyEntry.scanCode, keyEntry.metaState,
3307 keyEntry.repeatCount, keyEntry.downTime,
3308 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
3311
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003312 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003315 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317
chaviw82357092020-01-28 13:13:06 -08003318 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3321 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003322 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003323 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3324 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003325 // Don't apply window scale here since we don't want scale to affect raw
3326 // coordinates. The scale will be sent back to the client and applied
3327 // later when requesting relative coordinates.
3328 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3329 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 }
3331 usingCoords = scaledCoords;
3332 }
3333 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 // We don't want the dispatch target to know.
3335 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003336 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 scaledCoords[i].clear();
3338 }
3339 usingCoords = scaledCoords;
3340 }
3341 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003343 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344
3345 // Publish the motion event.
3346 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003347 .publishMotionEvent(dispatchEntry->seq,
3348 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003349 motionEntry.deviceId, motionEntry.source,
3350 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003351 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003352 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003354 motionEntry.edgeFlags, motionEntry.metaState,
3355 motionEntry.buttonState,
3356 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003357 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003358 motionEntry.xPrecision, motionEntry.yPrecision,
3359 motionEntry.xCursorPosition,
3360 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003361 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003362 motionEntry.downTime, motionEntry.eventTime,
3363 motionEntry.pointerCount,
3364 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 break;
3366 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003367
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003368 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003369 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003370 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003371 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003372 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003373 break;
3374 }
3375
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003376 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3377 const TouchModeEntry& touchModeEntry =
3378 static_cast<const TouchModeEntry&>(eventEntry);
3379 status = connection->inputPublisher
3380 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3381 touchModeEntry.inTouchMode);
3382
3383 break;
3384 }
3385
Prabir Pradhan99987712020-11-10 18:43:05 -08003386 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3387 const auto& captureEntry =
3388 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3389 status = connection->inputPublisher
3390 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003391 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003392 break;
3393 }
3394
arthurhungb89ccb02020-12-30 16:19:01 +08003395 case EventEntry::Type::DRAG: {
3396 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3397 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3398 dragEntry.id, dragEntry.x,
3399 dragEntry.y,
3400 dragEntry.isExiting);
3401 break;
3402 }
3403
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003404 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003405 case EventEntry::Type::DEVICE_RESET:
3406 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003407 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003408 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412
3413 // Check the result.
3414 if (status) {
3415 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003416 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003418 "This is unexpected because the wait queue is empty, so the pipe "
3419 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003420 "event to it, status=%s(%d)",
3421 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3422 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3424 } else {
3425 // Pipe is full and we are waiting for the app to finish process some events
3426 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003427 if (DEBUG_DISPATCH_CYCLE) {
3428 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3429 "waiting for the application to catch up",
3430 connection->getInputChannelName().c_str());
3431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433 } else {
3434 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003435 "status=%s(%d)",
3436 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3437 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3439 }
3440 return;
3441 }
3442
3443 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003444 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3445 connection->outboundQueue.end(),
3446 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003447 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003448 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003449 if (connection->responsive) {
3450 mAnrTracker.insert(dispatchEntry->timeoutTime,
3451 connection->inputChannel->getConnectionToken());
3452 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003453 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 }
3455}
3456
chaviw09c8d2d2020-08-24 15:48:26 -07003457std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3458 size_t size;
3459 switch (event.type) {
3460 case VerifiedInputEvent::Type::KEY: {
3461 size = sizeof(VerifiedKeyEvent);
3462 break;
3463 }
3464 case VerifiedInputEvent::Type::MOTION: {
3465 size = sizeof(VerifiedMotionEvent);
3466 break;
3467 }
3468 }
3469 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3470 return mHmacKeyManager.sign(start, size);
3471}
3472
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003473const std::array<uint8_t, 32> InputDispatcher::getSignature(
3474 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003475 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3476 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003477 // Only sign events up and down events as the purely move events
3478 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003479 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003480 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003481
3482 VerifiedMotionEvent verifiedEvent =
3483 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3484 verifiedEvent.actionMasked = actionMasked;
3485 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3486 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003487}
3488
3489const std::array<uint8_t, 32> InputDispatcher::getSignature(
3490 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3491 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3492 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3493 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003494 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003495}
3496
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003499 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003500 if (DEBUG_DISPATCH_CYCLE) {
3501 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3502 connection->getInputChannelName().c_str(), seq, toString(handled));
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003505 if (connection->status == Connection::Status::BROKEN ||
3506 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 return;
3508 }
3509
3510 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003511 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3512 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3513 };
3514 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515}
3516
3517void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518 const sp<Connection>& connection,
3519 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003520 if (DEBUG_DISPATCH_CYCLE) {
3521 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3522 connection->getInputChannelName().c_str(), toString(notify));
3523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524
3525 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003526 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003527 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003528 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003529 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530
3531 // The connection appears to be unrecoverably broken.
3532 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003533 if (connection->status == Connection::Status::NORMAL) {
3534 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535
3536 if (notify) {
3537 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003538 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3539 connection->getInputChannelName().c_str());
3540
3541 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003542 scoped_unlock unlock(mLock);
3543 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3544 };
3545 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 }
3547 }
3548}
3549
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003550void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3551 while (!queue.empty()) {
3552 DispatchEntry* dispatchEntry = queue.front();
3553 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003554 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 }
3556}
3557
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003558void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003560 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 }
3562 delete dispatchEntry;
3563}
3564
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003565int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3566 std::scoped_lock _l(mLock);
3567 sp<Connection> connection = getConnectionLocked(connectionToken);
3568 if (connection == nullptr) {
3569 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3570 connectionToken.get(), events);
3571 return 0; // remove the callback
3572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003574 bool notify;
3575 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3576 if (!(events & ALOOPER_EVENT_INPUT)) {
3577 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3578 "events=0x%x",
3579 connection->getInputChannelName().c_str(), events);
3580 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 }
3582
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003583 nsecs_t currentTime = now();
3584 bool gotOne = false;
3585 status_t status = OK;
3586 for (;;) {
3587 Result<InputPublisher::ConsumerResponse> result =
3588 connection->inputPublisher.receiveConsumerResponse();
3589 if (!result.ok()) {
3590 status = result.error().code();
3591 break;
3592 }
3593
3594 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3595 const InputPublisher::Finished& finish =
3596 std::get<InputPublisher::Finished>(*result);
3597 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3598 finish.consumeTime);
3599 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003600 if (shouldReportMetricsForConnection(*connection)) {
3601 const InputPublisher::Timeline& timeline =
3602 std::get<InputPublisher::Timeline>(*result);
3603 mLatencyTracker
3604 .trackGraphicsLatency(timeline.inputEventId,
3605 connection->inputChannel->getConnectionToken(),
3606 std::move(timeline.graphicsTimeline));
3607 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003608 }
3609 gotOne = true;
3610 }
3611 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003612 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003613 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 return 1;
3615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003618 notify = status != DEAD_OBJECT || !connection->monitor;
3619 if (notify) {
3620 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3621 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3622 status);
3623 }
3624 } else {
3625 // Monitor channels are never explicitly unregistered.
3626 // We do it automatically when the remote endpoint is closed so don't warn about them.
3627 const bool stillHaveWindowHandle =
3628 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3629 notify = !connection->monitor && stillHaveWindowHandle;
3630 if (notify) {
3631 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3632 connection->getInputChannelName().c_str(), events);
3633 }
3634 }
3635
3636 // Remove the channel.
3637 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3638 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639}
3640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003641void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003643 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003644 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646}
3647
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003648void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003649 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003650 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003651 for (const Monitor& monitor : monitors) {
3652 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003653 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003654 }
3655}
3656
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003658 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003659 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003660 if (connection == nullptr) {
3661 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003663
3664 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665}
3666
3667void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3668 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003669 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 return;
3671 }
3672
3673 nsecs_t currentTime = now();
3674
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003676 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003678 if (cancelationEvents.empty()) {
3679 return;
3680 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003681 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3682 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3683 "with reality: %s, mode=%d.",
3684 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3685 options.mode);
3686 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003687
Arthur Hungb3307ee2021-10-14 10:57:37 +00003688 std::string reason = std::string("reason=").append(options.reason);
3689 android_log_event_list(LOGTAG_INPUT_CANCEL)
3690 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3691
Svet Ganov5d3bc372020-01-26 23:11:07 -08003692 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003693 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003694 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3695 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003696 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003697 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003698 target.globalScaleFactor = windowInfo->globalScaleFactor;
3699 }
3700 target.inputChannel = connection->inputChannel;
3701 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3702
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003703 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003705 switch (cancelationEventEntry->type) {
3706 case EventEntry::Type::KEY: {
3707 logOutboundKeyDetails("cancel - ",
3708 static_cast<const KeyEntry&>(*cancelationEventEntry));
3709 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003711 case EventEntry::Type::MOTION: {
3712 logOutboundMotionDetails("cancel - ",
3713 static_cast<const MotionEntry&>(*cancelationEventEntry));
3714 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003716 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003717 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003718 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3719 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003720 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003721 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003722 break;
3723 }
3724 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003725 case EventEntry::Type::DEVICE_RESET:
3726 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003727 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003728 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003729 break;
3730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 }
3732
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003733 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3734 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003736
3737 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738}
3739
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3741 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003742 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 return;
3744 }
3745
3746 nsecs_t currentTime = now();
3747
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003748 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003749 connection->inputState.synthesizePointerDownEvents(currentTime);
3750
3751 if (downEvents.empty()) {
3752 return;
3753 }
3754
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003755 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003756 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3757 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003758 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003759
3760 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003761 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003762 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3763 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003764 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003765 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003766 target.globalScaleFactor = windowInfo->globalScaleFactor;
3767 }
3768 target.inputChannel = connection->inputChannel;
3769 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3770
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003771 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003772 switch (downEventEntry->type) {
3773 case EventEntry::Type::MOTION: {
3774 logOutboundMotionDetails("down - ",
3775 static_cast<const MotionEntry&>(*downEventEntry));
3776 break;
3777 }
3778
3779 case EventEntry::Type::KEY:
3780 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003781 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003782 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003783 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003784 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003785 case EventEntry::Type::SENSOR:
3786 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003787 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003788 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003789 break;
3790 }
3791 }
3792
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003793 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3794 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003795 }
3796
3797 startDispatchCycleLocked(currentTime, connection);
3798}
3799
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003800std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3801 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 ALOG_ASSERT(pointerIds.value != 0);
3803
3804 uint32_t splitPointerIndexMap[MAX_POINTERS];
3805 PointerProperties splitPointerProperties[MAX_POINTERS];
3806 PointerCoords splitPointerCoords[MAX_POINTERS];
3807
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003808 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 uint32_t splitPointerCount = 0;
3810
3811 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003812 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003814 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 uint32_t pointerId = uint32_t(pointerProperties.id);
3816 if (pointerIds.hasBit(pointerId)) {
3817 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3818 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3819 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003820 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 splitPointerCount += 1;
3822 }
3823 }
3824
3825 if (splitPointerCount != pointerIds.count()) {
3826 // This is bad. We are missing some of the pointers that we expected to deliver.
3827 // Most likely this indicates that we received an ACTION_MOVE events that has
3828 // different pointer ids than we expected based on the previous ACTION_DOWN
3829 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3830 // in this way.
3831 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 "we expected there to be %d pointers. This probably means we received "
3833 "a broken sequence of pointer ids from the input device.",
3834 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003835 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003838 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003840 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3841 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3843 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003844 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 uint32_t pointerId = uint32_t(pointerProperties.id);
3846 if (pointerIds.hasBit(pointerId)) {
3847 if (pointerIds.count() == 1) {
3848 // The first/last pointer went down/up.
3849 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003851 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3852 ? AMOTION_EVENT_ACTION_CANCEL
3853 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 } else {
3855 // A secondary pointer went down/up.
3856 uint32_t splitPointerIndex = 0;
3857 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3858 splitPointerIndex += 1;
3859 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003860 action = maskedAction |
3861 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 }
3863 } else {
3864 // An unrelated pointer changed.
3865 action = AMOTION_EVENT_ACTION_MOVE;
3866 }
3867 }
3868
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003869 int32_t newId = mIdGenerator.nextId();
3870 if (ATRACE_ENABLED()) {
3871 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3872 ") to MotionEvent(id=0x%" PRIx32 ").",
3873 originalMotionEntry.id, newId);
3874 ATRACE_NAME(message.c_str());
3875 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003876 std::unique_ptr<MotionEntry> splitMotionEntry =
3877 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3878 originalMotionEntry.deviceId, originalMotionEntry.source,
3879 originalMotionEntry.displayId,
3880 originalMotionEntry.policyFlags, action,
3881 originalMotionEntry.actionButton,
3882 originalMotionEntry.flags, originalMotionEntry.metaState,
3883 originalMotionEntry.buttonState,
3884 originalMotionEntry.classification,
3885 originalMotionEntry.edgeFlags,
3886 originalMotionEntry.xPrecision,
3887 originalMotionEntry.yPrecision,
3888 originalMotionEntry.xCursorPosition,
3889 originalMotionEntry.yCursorPosition,
3890 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003891 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003893 if (originalMotionEntry.injectionState) {
3894 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 splitMotionEntry->injectionState->refCount += 1;
3896 }
3897
3898 return splitMotionEntry;
3899}
3900
3901void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003902 if (DEBUG_INBOUND_EVENT_DETAILS) {
3903 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905
Antonio Kantekf16f2832021-09-28 04:39:20 +00003906 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003908 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003910 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3911 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3912 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 } // release lock
3914
3915 if (needWake) {
3916 mLooper->wake();
3917 }
3918}
3919
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920/**
3921 * If one of the meta shortcuts is detected, process them here:
3922 * Meta + Backspace -> generate BACK
3923 * Meta + Enter -> generate HOME
3924 * This will potentially overwrite keyCode and metaState.
3925 */
3926void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003927 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003928 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3929 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3930 if (keyCode == AKEYCODE_DEL) {
3931 newKeyCode = AKEYCODE_BACK;
3932 } else if (keyCode == AKEYCODE_ENTER) {
3933 newKeyCode = AKEYCODE_HOME;
3934 }
3935 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003936 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003937 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003938 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003939 keyCode = newKeyCode;
3940 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3941 }
3942 } else if (action == AKEY_EVENT_ACTION_UP) {
3943 // In order to maintain a consistent stream of up and down events, check to see if the key
3944 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3945 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003946 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003947 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003948 auto replacementIt = mReplacedKeys.find(replacement);
3949 if (replacementIt != mReplacedKeys.end()) {
3950 keyCode = replacementIt->second;
3951 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003952 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3953 }
3954 }
3955}
3956
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003958 if (DEBUG_INBOUND_EVENT_DETAILS) {
3959 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3960 "policyFlags=0x%x, action=0x%x, "
3961 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3962 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3963 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3964 args->downTime);
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 if (!validateKeyEvent(args->action)) {
3967 return;
3968 }
3969
3970 uint32_t policyFlags = args->policyFlags;
3971 int32_t flags = args->flags;
3972 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003973 // InputDispatcher tracks and generates key repeats on behalf of
3974 // whatever notifies it, so repeatCount should always be set to 0
3975 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3977 policyFlags |= POLICY_FLAG_VIRTUAL;
3978 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 if (policyFlags & POLICY_FLAG_FUNCTION) {
3981 metaState |= AMETA_FUNCTION_ON;
3982 }
3983
3984 policyFlags |= POLICY_FLAG_TRUSTED;
3985
Michael Wright78f24442014-08-06 15:55:28 -07003986 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003987 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003988
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003990 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003991 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3992 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
Michael Wright2b3c3302018-03-02 17:19:13 +00003994 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003996 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3997 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003998 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
Antonio Kantekf16f2832021-09-28 04:39:20 +00004001 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 { // acquire lock
4003 mLock.lock();
4004
4005 if (shouldSendKeyToInputFilterLocked(args)) {
4006 mLock.unlock();
4007
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004008 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4010 return; // event was consumed by the filter
4011 }
4012
4013 mLock.lock();
4014 }
4015
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004016 std::unique_ptr<KeyEntry> newEntry =
4017 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4018 args->displayId, policyFlags, args->action, flags,
4019 keyCode, args->scanCode, metaState, repeatCount,
4020 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004022 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 mLock.unlock();
4024 } // release lock
4025
4026 if (needWake) {
4027 mLooper->wake();
4028 }
4029}
4030
4031bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4032 return mInputFilterEnabled;
4033}
4034
4035void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004036 if (DEBUG_INBOUND_EVENT_DETAILS) {
4037 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4038 "displayId=%" PRId32 ", policyFlags=0x%x, "
4039 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4040 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4041 "yCursorPosition=%f, downTime=%" PRId64,
4042 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4043 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4044 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4045 args->xCursorPosition, args->yCursorPosition, args->downTime);
4046 for (uint32_t i = 0; i < args->pointerCount; i++) {
4047 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4048 "x=%f, y=%f, pressure=%f, size=%f, "
4049 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4050 "orientation=%f",
4051 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4052 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4053 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4054 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4055 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4056 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4057 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4058 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4059 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4060 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4064 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 return;
4066 }
4067
4068 uint32_t policyFlags = args->policyFlags;
4069 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004070
4071 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004072 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004073 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4074 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Antonio Kantekf16f2832021-09-28 04:39:20 +00004078 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 { // acquire lock
4080 mLock.lock();
4081
4082 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004083 ui::Transform displayTransform;
4084 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4085 displayTransform = it->second.transform;
4086 }
4087
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 mLock.unlock();
4089
4090 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004091 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4092 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004093 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004094 displayTransform, args->xPrecision, args->yPrecision,
4095 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004096 args->downTime, args->eventTime, args->pointerCount,
4097 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098
4099 policyFlags |= POLICY_FLAG_FILTERED;
4100 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4101 return; // event was consumed by the filter
4102 }
4103
4104 mLock.lock();
4105 }
4106
4107 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 std::unique_ptr<MotionEntry> newEntry =
4109 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4110 args->source, args->displayId, policyFlags,
4111 args->action, args->actionButton, args->flags,
4112 args->metaState, args->buttonState,
4113 args->classification, args->edgeFlags,
4114 args->xPrecision, args->yPrecision,
4115 args->xCursorPosition, args->yCursorPosition,
4116 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004117 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004119 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4120 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4121 !mInputFilterEnabled) {
4122 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4123 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4124 }
4125
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004126 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 mLock.unlock();
4128 } // release lock
4129
4130 if (needWake) {
4131 mLooper->wake();
4132 }
4133}
4134
Chris Yef59a2f42020-10-16 12:55:26 -07004135void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004136 if (DEBUG_INBOUND_EVENT_DETAILS) {
4137 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4138 " sensorType=%s",
4139 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004140 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004141 }
Chris Yef59a2f42020-10-16 12:55:26 -07004142
Antonio Kantekf16f2832021-09-28 04:39:20 +00004143 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004144 { // acquire lock
4145 mLock.lock();
4146
4147 // Just enqueue a new sensor event.
4148 std::unique_ptr<SensorEntry> newEntry =
4149 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4150 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4151 args->sensorType, args->accuracy,
4152 args->accuracyChanged, args->values);
4153
4154 needWake = enqueueInboundEventLocked(std::move(newEntry));
4155 mLock.unlock();
4156 } // release lock
4157
4158 if (needWake) {
4159 mLooper->wake();
4160 }
4161}
4162
Chris Yefb552902021-02-03 17:18:37 -08004163void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004164 if (DEBUG_INBOUND_EVENT_DETAILS) {
4165 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4166 args->deviceId, args->isOn);
4167 }
Chris Yefb552902021-02-03 17:18:37 -08004168 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4169}
4170
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004172 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173}
4174
4175void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004176 if (DEBUG_INBOUND_EVENT_DETAILS) {
4177 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4178 "switchMask=0x%08x",
4179 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181
4182 uint32_t policyFlags = args->policyFlags;
4183 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185}
4186
4187void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004188 if (DEBUG_INBOUND_EVENT_DETAILS) {
4189 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4190 args->deviceId);
4191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192
Antonio Kantekf16f2832021-09-28 04:39:20 +00004193 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004195 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 std::unique_ptr<DeviceResetEntry> newEntry =
4198 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4199 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 } // release lock
4201
4202 if (needWake) {
4203 mLooper->wake();
4204 }
4205}
4206
Prabir Pradhan7e186182020-11-10 13:56:45 -08004207void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004208 if (DEBUG_INBOUND_EVENT_DETAILS) {
4209 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004210 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004211 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004212
Antonio Kantekf16f2832021-09-28 04:39:20 +00004213 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004214 { // acquire lock
4215 std::scoped_lock _l(mLock);
4216 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004217 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004218 needWake = enqueueInboundEventLocked(std::move(entry));
4219 } // release lock
4220
4221 if (needWake) {
4222 mLooper->wake();
4223 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004224}
4225
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004226InputEventInjectionResult InputDispatcher::injectInputEvent(
4227 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4228 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004229 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004230 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4231 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4232 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004233 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004234 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004236 policyFlags |= POLICY_FLAG_INJECTED;
4237 if (hasInjectionPermission(injectorPid, injectorUid)) {
4238 policyFlags |= POLICY_FLAG_TRUSTED;
4239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004241 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004242 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4243 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4244 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4245 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4246 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004248 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004249 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004250 }
4251
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004252 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004255 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4256 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004261 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004262 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4263 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4264 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004265 int32_t keyCode = incomingKey.getKeyCode();
4266 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004267 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004269 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004270 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004271 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4272 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4273 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4276 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004277 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278
4279 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4280 android::base::Timer t;
4281 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4282 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4283 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4284 std::to_string(t.duration().count()).c_str());
4285 }
4286 }
4287
4288 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004289 std::unique_ptr<KeyEntry> injectedEntry =
4290 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004291 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004292 incomingKey.getDisplayId(), policyFlags, action,
4293 flags, keyCode, incomingKey.getScanCode(), metaState,
4294 incomingKey.getRepeatCount(),
4295 incomingKey.getDownTime());
4296 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 }
4299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004301 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004302 const int32_t action = motionEvent.getAction();
4303 const bool isPointerEvent =
4304 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4305 // If a pointer event has no displayId specified, inject it to the default display.
4306 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4307 ? ADISPLAY_ID_DEFAULT
4308 : event->getDisplayId();
4309 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004310 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004311 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004312 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004313 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 }
4316
4317 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004319 android::base::Timer t;
4320 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4321 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4322 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4323 std::to_string(t.duration().count()).c_str());
4324 }
4325 }
4326
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004327 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4328 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4329 }
4330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004332 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4333 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004334 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004335 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4336 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004337 displayId, policyFlags, action, actionButton,
4338 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004339 motionEvent.getButtonState(),
4340 motionEvent.getClassification(),
4341 motionEvent.getEdgeFlags(),
4342 motionEvent.getXPrecision(),
4343 motionEvent.getYPrecision(),
4344 motionEvent.getRawXCursorPosition(),
4345 motionEvent.getRawYCursorPosition(),
4346 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004347 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004348 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004350 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 sampleEventTimes += 1;
4352 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004354 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4355 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004356 displayId, policyFlags, action, actionButton,
4357 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004358 motionEvent.getButtonState(),
4359 motionEvent.getClassification(),
4360 motionEvent.getEdgeFlags(),
4361 motionEvent.getXPrecision(),
4362 motionEvent.getYPrecision(),
4363 motionEvent.getRawXCursorPosition(),
4364 motionEvent.getRawYCursorPosition(),
4365 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004366 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004367 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004368 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4369 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004370 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 }
4372 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004375 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004376 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004377 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 }
4379
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004380 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 injectionState->injectionIsAsync = true;
4383 }
4384
4385 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004386 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
4388 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004389 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004390 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004391 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 }
4393
4394 mLock.unlock();
4395
4396 if (needWake) {
4397 mLooper->wake();
4398 }
4399
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004402 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 if (syncMode == InputEventInjectionSync::NONE) {
4405 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 } else {
4407 for (;;) {
4408 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004409 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 break;
4411 }
4412
4413 nsecs_t remainingTimeout = endTime - now();
4414 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004415 if (DEBUG_INJECTION) {
4416 ALOGD("injectInputEvent - Timed out waiting for injection result "
4417 "to become available.");
4418 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 break;
4421 }
4422
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004423 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 }
4425
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004426 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4427 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004429 if (DEBUG_INJECTION) {
4430 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4431 injectionState->pendingForegroundDispatches);
4432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 nsecs_t remainingTimeout = endTime - now();
4434 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004435 if (DEBUG_INJECTION) {
4436 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4437 "dispatches to finish.");
4438 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004439 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 break;
4441 }
4442
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004443 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 }
4445 }
4446 }
4447
4448 injectionState->release();
4449 } // release lock
4450
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004451 if (DEBUG_INJECTION) {
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004452 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4453 injectionResult, injectorPid, injectorUid);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455
4456 return injectionResult;
4457}
4458
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004459std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004460 std::array<uint8_t, 32> calculatedHmac;
4461 std::unique_ptr<VerifiedInputEvent> result;
4462 switch (event.getType()) {
4463 case AINPUT_EVENT_TYPE_KEY: {
4464 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4465 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4466 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004467 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004468 break;
4469 }
4470 case AINPUT_EVENT_TYPE_MOTION: {
4471 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4472 VerifiedMotionEvent verifiedMotionEvent =
4473 verifiedMotionEventFromMotionEvent(motionEvent);
4474 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004475 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004476 break;
4477 }
4478 default: {
4479 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4480 return nullptr;
4481 }
4482 }
4483 if (calculatedHmac == INVALID_HMAC) {
4484 return nullptr;
4485 }
4486 if (calculatedHmac != event.getHmac()) {
4487 return nullptr;
4488 }
4489 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004490}
4491
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004492bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
4493 return injectorUid == 0 ||
4494 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
4495}
4496
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004497void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004499 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004501 if (DEBUG_INJECTION) {
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004502 ALOGD("Setting input event injection result to %d. "
4503 "injectorPid=%d, injectorUid=%d",
4504 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004507 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 // Log the outcome since the injector did not wait for the injection result.
4509 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 ALOGV("Asynchronous input event injection succeeded.");
4512 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004513 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004514 ALOGW("Asynchronous input event injection failed.");
4515 break;
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004516 case InputEventInjectionResult::PERMISSION_DENIED:
4517 ALOGW("Asynchronous input event injection permission denied.");
4518 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004519 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 ALOGW("Asynchronous input event injection timed out.");
4521 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004522 case InputEventInjectionResult::PENDING:
4523 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4524 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 }
4526 }
4527
4528 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004529 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 }
4531}
4532
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004533void InputDispatcher::transformMotionEntryForInjectionLocked(
4534 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004535 // Input injection works in the logical display coordinate space, but the input pipeline works
4536 // display space, so we need to transform the injected events accordingly.
4537 const auto it = mDisplayInfos.find(entry.displayId);
4538 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004539 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004540
4541 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004542 entry.pointerCoords[i] =
4543 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4544 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004545 }
4546}
4547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004548void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4549 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 if (injectionState) {
4551 injectionState->pendingForegroundDispatches += 1;
4552 }
4553}
4554
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004555void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4556 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 if (injectionState) {
4558 injectionState->pendingForegroundDispatches -= 1;
4559
4560 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004561 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 }
4563 }
4564}
4565
chaviw98318de2021-05-19 16:45:23 -05004566const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004567 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004568 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004569 auto it = mWindowHandlesByDisplay.find(displayId);
4570 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004571}
4572
chaviw98318de2021-05-19 16:45:23 -05004573sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004574 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004575 if (windowHandleToken == nullptr) {
4576 return nullptr;
4577 }
4578
Arthur Hungb92218b2018-08-14 12:00:21 +08004579 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004580 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4581 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004582 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004583 return windowHandle;
4584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 }
4586 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004587 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588}
4589
chaviw98318de2021-05-19 16:45:23 -05004590sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4591 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004592 if (windowHandleToken == nullptr) {
4593 return nullptr;
4594 }
4595
chaviw98318de2021-05-19 16:45:23 -05004596 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004597 if (windowHandle->getToken() == windowHandleToken) {
4598 return windowHandle;
4599 }
4600 }
4601 return nullptr;
4602}
4603
chaviw98318de2021-05-19 16:45:23 -05004604sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4605 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004606 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004607 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4608 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004609 if (handle->getId() == windowHandle->getId() &&
4610 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004611 if (windowHandle->getInfo()->displayId != it.first) {
4612 ALOGE("Found window %s in display %" PRId32
4613 ", but it should belong to display %" PRId32,
4614 windowHandle->getName().c_str(), it.first,
4615 windowHandle->getInfo()->displayId);
4616 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004617 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 }
4620 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004621 return nullptr;
4622}
4623
chaviw98318de2021-05-19 16:45:23 -05004624sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004625 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4626 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627}
4628
chaviw98318de2021-05-19 16:45:23 -05004629bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004630 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4631 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004632 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004633 if (connection != nullptr && noInputChannel) {
4634 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4635 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4636 return false;
4637 }
4638
4639 if (connection == nullptr) {
4640 if (!noInputChannel) {
4641 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4642 }
4643 return false;
4644 }
4645 if (!connection->responsive) {
4646 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4647 return false;
4648 }
4649 return true;
4650}
4651
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004652std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4653 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004654 auto connectionIt = mConnectionsByToken.find(token);
4655 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004656 return nullptr;
4657 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004658 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004659}
4660
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004661void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004662 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4663 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004664 // Remove all handles on a display if there are no windows left.
4665 mWindowHandlesByDisplay.erase(displayId);
4666 return;
4667 }
4668
4669 // Since we compare the pointer of input window handles across window updates, we need
4670 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004671 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4672 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4673 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004674 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004675 }
4676
chaviw98318de2021-05-19 16:45:23 -05004677 std::vector<sp<WindowInfoHandle>> newHandles;
4678 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004679 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004680 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004681 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004682 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004683 const bool canReceiveInput =
4684 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4685 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004686 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004687 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004688 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004689 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004690 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004691 }
4692
4693 if (info->displayId != displayId) {
4694 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4695 handle->getName().c_str(), displayId, info->displayId);
4696 continue;
4697 }
4698
Robert Carredd13602020-04-13 17:24:34 -07004699 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4700 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004701 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004702 oldHandle->updateFrom(handle);
4703 newHandles.push_back(oldHandle);
4704 } else {
4705 newHandles.push_back(handle);
4706 }
4707 }
4708
4709 // Insert or replace
4710 mWindowHandlesByDisplay[displayId] = newHandles;
4711}
4712
Arthur Hung72d8dc32020-03-28 00:48:39 +00004713void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004714 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004715 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004716 { // acquire lock
4717 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004718 for (const auto& [displayId, handles] : handlesPerDisplay) {
4719 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004720 }
4721 }
4722 // Wake up poll loop since it may need to make new input dispatching choices.
4723 mLooper->wake();
4724}
4725
Arthur Hungb92218b2018-08-14 12:00:21 +08004726/**
4727 * Called from InputManagerService, update window handle list by displayId that can receive input.
4728 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4729 * If set an empty list, remove all handles from the specific display.
4730 * For focused handle, check if need to change and send a cancel event to previous one.
4731 * For removed handle, check if need to send a cancel event if already in touch.
4732 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004733void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004734 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004735 if (DEBUG_FOCUS) {
4736 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004737 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004738 windowList += iwh->getName() + " ";
4739 }
4740 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742
Prabir Pradhand65552b2021-10-07 11:23:50 -07004743 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004744 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004745 const WindowInfo& info = *window->getInfo();
4746
4747 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004748 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004749 if (noInputWindow && window->getToken() != nullptr) {
4750 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4751 window->getName().c_str());
4752 window->releaseChannel();
4753 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004754
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004755 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004756 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4757 !info.inputConfig.test(
4758 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004759 "%s has feature SPY, but is not a trusted overlay.",
4760 window->getName().c_str());
4761
Prabir Pradhand65552b2021-10-07 11:23:50 -07004762 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004763 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4764 !info.inputConfig.test(
4765 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004766 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4767 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004768 }
4769
Arthur Hung72d8dc32020-03-28 00:48:39 +00004770 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004771 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004773 // Save the old windows' orientation by ID before it gets updated.
4774 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004775 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004776 oldWindowOrientations.emplace(handle->getId(),
4777 handle->getInfo()->transform.getOrientation());
4778 }
4779
chaviw98318de2021-05-19 16:45:23 -05004780 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004781
chaviw98318de2021-05-19 16:45:23 -05004782 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004783 if (mLastHoverWindowHandle &&
4784 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4785 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004786 mLastHoverWindowHandle = nullptr;
4787 }
4788
Vishnu Nairc519ff72021-01-21 08:23:08 -08004789 std::optional<FocusResolver::FocusChanges> changes =
4790 mFocusResolver.setInputWindows(displayId, windowHandles);
4791 if (changes) {
4792 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004795 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4796 mTouchStatesByDisplay.find(displayId);
4797 if (stateIt != mTouchStatesByDisplay.end()) {
4798 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004799 for (size_t i = 0; i < state.windows.size();) {
4800 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004801 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004802 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004803 ALOGD("Touched window was removed: %s in display %" PRId32,
4804 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004806 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004807 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4808 if (touchedInputChannel != nullptr) {
4809 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4810 "touched window was removed");
4811 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004812 // Since we are about to drop the touch, cancel the events for the wallpaper as
4813 // well.
4814 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004815 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4816 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004817 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4818 if (wallpaper != nullptr) {
4819 sp<Connection> wallpaperConnection =
4820 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004821 if (wallpaperConnection != nullptr) {
4822 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4823 options);
4824 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004825 }
4826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004828 state.windows.erase(state.windows.begin() + i);
4829 } else {
4830 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832 }
arthurhungb89ccb02020-12-30 16:19:01 +08004833
arthurhung6d4bed92021-03-17 11:59:33 +08004834 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004835 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004836 if (mDragState &&
4837 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004838 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004839 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004840 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004841 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004842
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004843 // Determine if the orientation of any of the input windows have changed, and cancel all
4844 // pointer events if necessary.
4845 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4846 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4847 if (newWindowHandle != nullptr &&
4848 newWindowHandle->getInfo()->transform.getOrientation() !=
4849 oldWindowOrientations[oldWindowHandle->getId()]) {
4850 std::shared_ptr<InputChannel> inputChannel =
4851 getInputChannelLocked(newWindowHandle->getToken());
4852 if (inputChannel != nullptr) {
4853 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4854 "touched window's orientation changed");
4855 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004856 }
4857 }
4858 }
4859
Arthur Hung72d8dc32020-03-28 00:48:39 +00004860 // Release information for windows that are no longer present.
4861 // This ensures that unused input channels are released promptly.
4862 // Otherwise, they might stick around until the window handle is destroyed
4863 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004864 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004865 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004866 if (DEBUG_FOCUS) {
4867 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004868 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004869 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004870 }
chaviw291d88a2019-02-14 10:33:58 -08004871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872}
4873
4874void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004875 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004876 if (DEBUG_FOCUS) {
4877 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4878 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4879 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004880 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004881 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004882 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883 } // release lock
4884
4885 // Wake up poll loop since it may need to make new input dispatching choices.
4886 mLooper->wake();
4887}
4888
Vishnu Nair599f1412021-06-21 10:39:58 -07004889void InputDispatcher::setFocusedApplicationLocked(
4890 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4891 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4892 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4893
4894 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4895 return; // This application is already focused. No need to wake up or change anything.
4896 }
4897
4898 // Set the new application handle.
4899 if (inputApplicationHandle != nullptr) {
4900 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4901 } else {
4902 mFocusedApplicationHandlesByDisplay.erase(displayId);
4903 }
4904
4905 // No matter what the old focused application was, stop waiting on it because it is
4906 // no longer focused.
4907 resetNoFocusedWindowTimeoutLocked();
4908}
4909
Tiger Huang721e26f2018-07-24 22:26:19 +08004910/**
4911 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4912 * the display not specified.
4913 *
4914 * We track any unreleased events for each window. If a window loses the ability to receive the
4915 * released event, we will send a cancel event to it. So when the focused display is changed, we
4916 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4917 * display. The display-specified events won't be affected.
4918 */
4919void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004920 if (DEBUG_FOCUS) {
4921 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4922 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004923 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004924 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004925
4926 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004927 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004928 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004929 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004930 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004931 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004932 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004933 CancelationOptions
4934 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4935 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004936 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004937 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4938 }
4939 }
4940 mFocusedDisplayId = displayId;
4941
Chris Ye3c2d6f52020-08-09 10:39:48 -07004942 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004943 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004944 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004945
Vishnu Nairad321cd2020-08-20 16:40:21 -07004946 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004947 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004948 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004949 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004950 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004951 }
4952 }
4953 }
4954
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004955 if (DEBUG_FOCUS) {
4956 logDispatchStateLocked();
4957 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004958 } // release lock
4959
4960 // Wake up poll loop since it may need to make new input dispatching choices.
4961 mLooper->wake();
4962}
4963
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004965 if (DEBUG_FOCUS) {
4966 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968
4969 bool changed;
4970 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004971 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
4973 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4974 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 }
4977
4978 if (mDispatchEnabled && !enabled) {
4979 resetAndDropEverythingLocked("dispatcher is being disabled");
4980 }
4981
4982 mDispatchEnabled = enabled;
4983 mDispatchFrozen = frozen;
4984 changed = true;
4985 } else {
4986 changed = false;
4987 }
4988
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004989 if (DEBUG_FOCUS) {
4990 logDispatchStateLocked();
4991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 } // release lock
4993
4994 if (changed) {
4995 // Wake up poll loop since it may need to make new input dispatching choices.
4996 mLooper->wake();
4997 }
4998}
4999
5000void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005001 if (DEBUG_FOCUS) {
5002 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
5005 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005006 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007
5008 if (mInputFilterEnabled == enabled) {
5009 return;
5010 }
5011
5012 mInputFilterEnabled = enabled;
5013 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5014 } // release lock
5015
5016 // Wake up poll loop since there might be work to do to drop everything.
5017 mLooper->wake();
5018}
5019
Antonio Kantekea47acb2021-12-23 12:41:25 -08005020bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
5021 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005022 bool needWake = false;
5023 {
5024 std::scoped_lock lock(mLock);
5025 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005026 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005027 }
5028 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005029 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
5030 "hasPermission=%s)",
5031 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
5032 }
5033 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005034 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5035 !recentWindowsAreOwnedByLocked(pid, uid)) {
5036 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5037 "window nor none of the previously interacted window",
5038 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005039 return false;
5040 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005041 }
5042
5043 // TODO(b/198499018): Store touch mode per display.
5044 mInTouchMode = inTouchMode;
5045
Antonio Kantekf16f2832021-09-28 04:39:20 +00005046 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5047 needWake = enqueueInboundEventLocked(std::move(entry));
5048 } // release lock
5049
5050 if (needWake) {
5051 mLooper->wake();
5052 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005053 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005054}
5055
Antonio Kantek48710e42022-03-24 14:19:30 -07005056bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5057 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5058 if (focusedToken == nullptr) {
5059 return false;
5060 }
5061 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5062 return isWindowOwnedBy(windowHandle, pid, uid);
5063}
5064
5065bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5066 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5067 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5068 const sp<WindowInfoHandle> windowHandle =
5069 getWindowHandleLocked(connectionToken);
5070 return isWindowOwnedBy(windowHandle, pid, uid);
5071 }) != mInteractionConnectionTokens.end();
5072}
5073
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005074void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5075 if (opacity < 0 || opacity > 1) {
5076 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5077 return;
5078 }
5079
5080 std::scoped_lock lock(mLock);
5081 mMaximumObscuringOpacityForTouch = opacity;
5082}
5083
5084void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5085 std::scoped_lock lock(mLock);
5086 mBlockUntrustedTouchesMode = mode;
5087}
5088
Arthur Hungabbb9d82021-09-01 14:52:30 +00005089std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5090 const sp<IBinder>& token) {
5091 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5092 for (TouchedWindow& w : state.windows) {
5093 if (w.windowHandle->getToken() == token) {
5094 return std::make_pair(&state, &w);
5095 }
5096 }
5097 }
5098 return std::make_pair(nullptr, nullptr);
5099}
5100
arthurhungb89ccb02020-12-30 16:19:01 +08005101bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5102 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005103 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005104 if (DEBUG_FOCUS) {
5105 ALOGD("Trivial transfer to same window.");
5106 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005107 return true;
5108 }
5109
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005111 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113 // Find the target touch state and touched window by fromToken.
5114 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5115 if (state == nullptr || touchedWindow == nullptr) {
5116 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 return false;
5118 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005119
5120 const int32_t displayId = state->displayId;
5121 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5122 if (toWindowHandle == nullptr) {
5123 ALOGW("Cannot transfer focus because to window not found.");
5124 return false;
5125 }
5126
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005127 if (DEBUG_FOCUS) {
5128 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005129 touchedWindow->windowHandle->getName().c_str(),
5130 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 }
5132
Arthur Hungabbb9d82021-09-01 14:52:30 +00005133 // Erase old window.
5134 int32_t oldTargetFlags = touchedWindow->targetFlags;
5135 BitSet32 pointerIds = touchedWindow->pointerIds;
5136 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137
Arthur Hungabbb9d82021-09-01 14:52:30 +00005138 // Add new window.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005139 int32_t newTargetFlags =
5140 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5141 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5142 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5143 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005144 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145
Arthur Hungabbb9d82021-09-01 14:52:30 +00005146 // Store the dragging window.
5147 if (isDragDrop) {
Arthur Hung54745652022-04-20 07:17:41 +00005148 if (pointerIds.count() > 1) {
5149 ALOGW("The drag and drop cannot be started when there is more than 1 pointer on the"
5150 " window.");
5151 return false;
5152 }
5153 // If the window didn't not support split or the source is mouse, the pointerIds count
5154 // would be 0, so we have to track the pointer 0.
5155 const int32_t id = pointerIds.count() == 0 ? 0 : pointerIds.firstMarkedBit();
5156 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 }
5158
Arthur Hungabbb9d82021-09-01 14:52:30 +00005159 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005160 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5161 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005162 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005163 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005164 CancelationOptions
5165 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5166 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005168 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 }
5170
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005171 if (DEBUG_FOCUS) {
5172 logDispatchStateLocked();
5173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 } // release lock
5175
5176 // Wake up poll loop since it may need to make new input dispatching choices.
5177 mLooper->wake();
5178 return true;
5179}
5180
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005181/**
5182 * Get the touched foreground window on the given display.
5183 * Return null if there are no windows touched on that display, or if more than one foreground
5184 * window is being touched.
5185 */
5186sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5187 auto stateIt = mTouchStatesByDisplay.find(displayId);
5188 if (stateIt == mTouchStatesByDisplay.end()) {
5189 ALOGI("No touch state on display %" PRId32, displayId);
5190 return nullptr;
5191 }
5192
5193 const TouchState& state = stateIt->second;
5194 sp<WindowInfoHandle> touchedForegroundWindow;
5195 // If multiple foreground windows are touched, return nullptr
5196 for (const TouchedWindow& window : state.windows) {
5197 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5198 if (touchedForegroundWindow != nullptr) {
5199 ALOGI("Two or more foreground windows: %s and %s",
5200 touchedForegroundWindow->getName().c_str(),
5201 window.windowHandle->getName().c_str());
5202 return nullptr;
5203 }
5204 touchedForegroundWindow = window.windowHandle;
5205 }
5206 }
5207 return touchedForegroundWindow;
5208}
5209
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005210// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005211bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005212 sp<IBinder> fromToken;
5213 { // acquire lock
5214 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005215 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005216 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005217 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5218 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005219 return false;
5220 }
5221
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005222 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5223 if (from == nullptr) {
5224 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5225 return false;
5226 }
5227
5228 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005229 } // release lock
5230
5231 return transferTouchFocus(fromToken, destChannelToken);
5232}
5233
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005235 if (DEBUG_FOCUS) {
5236 ALOGD("Resetting and dropping all events (%s).", reason);
5237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238
5239 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5240 synthesizeCancelationEventsForAllConnectionsLocked(options);
5241
5242 resetKeyRepeatLocked();
5243 releasePendingEventLocked();
5244 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005245 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005247 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005248 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005250 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251}
5252
5253void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005254 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 dumpDispatchStateLocked(dump);
5256
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005257 std::istringstream stream(dump);
5258 std::string line;
5259
5260 while (std::getline(stream, line, '\n')) {
5261 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 }
5263}
5264
Prabir Pradhan99987712020-11-10 18:43:05 -08005265std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5266 std::string dump;
5267
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005268 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5269 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005270
5271 std::string windowName = "None";
5272 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005273 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005274 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5275 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5276 : "token has capture without window";
5277 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005278 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005279
5280 return dump;
5281}
5282
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005283void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005284 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5285 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5286 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005287 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288
Tiger Huang721e26f2018-07-24 22:26:19 +08005289 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5290 dump += StringPrintf(INDENT "FocusedApplications:\n");
5291 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5292 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005293 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005294 const std::chrono::duration timeout =
5295 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005297 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005298 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005301 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005303
Vishnu Nairc519ff72021-01-21 08:23:08 -08005304 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005305 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005307 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005309 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5310 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005311 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005312 state.displayId, toString(state.down), toString(state.split),
5313 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005314 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005315 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005316 for (size_t i = 0; i < state.windows.size(); i++) {
5317 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005318 dump += StringPrintf(INDENT4
5319 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5320 i, touchedWindow.windowHandle->getName().c_str(),
5321 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005322 }
5323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005324 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 }
5327 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005328 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 }
5330
arthurhung6d4bed92021-03-17 11:59:33 +08005331 if (mDragState) {
5332 dump += StringPrintf(INDENT "DragState:\n");
5333 mDragState->dump(dump, INDENT2);
5334 }
5335
Arthur Hungb92218b2018-08-14 12:00:21 +08005336 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005337 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5338 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5339 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5340 const auto& displayInfo = it->second;
5341 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5342 displayInfo.logicalHeight);
5343 displayInfo.transform.dump(dump, "transform", INDENT4);
5344 } else {
5345 dump += INDENT2 "No DisplayInfo found!\n";
5346 }
5347
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005348 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005349 dump += INDENT2 "Windows:\n";
5350 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005351 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5352 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005354 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005355 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005356 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005357 "applicationInfo.name=%s, "
5358 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005359 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005360 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005361 windowInfo->displayId,
5362 windowInfo->inputConfig.string().c_str(),
5363 windowInfo->alpha, windowInfo->frameLeft,
5364 windowInfo->frameTop, windowInfo->frameRight,
5365 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005366 windowInfo->applicationInfo.name.c_str(),
5367 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005368 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005369 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005370 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005371 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005372 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005373 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005374 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005375 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005376 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005377 }
5378 } else {
5379 dump += INDENT2 "Windows: <none>\n";
5380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 }
5382 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005383 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005386 if (!mGlobalMonitorsByDisplay.empty()) {
5387 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5388 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005389 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005392 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005395 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396
5397 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005398 if (!mRecentQueue.empty()) {
5399 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005400 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005402 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005403 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 }
5405 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408
5409 // Dump event currently being dispatched.
5410 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005411 dump += INDENT "PendingEvent:\n";
5412 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005413 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005414 dump += StringPrintf(", age=%" PRId64 "ms\n",
5415 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005417 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418 }
5419
5420 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005421 if (!mInboundQueue.empty()) {
5422 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005423 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005424 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005425 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005426 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 }
5428 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005432 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005433 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005434 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5435 const KeyReplacement& replacement = pair.first;
5436 int32_t newKeyCode = pair.second;
5437 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005438 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005439 }
5440 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005441 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005442 }
5443
Prabir Pradhancef936d2021-07-21 16:17:52 +00005444 if (!mCommandQueue.empty()) {
5445 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5446 } else {
5447 dump += INDENT "CommandQueue: <empty>\n";
5448 }
5449
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005450 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005451 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005452 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005453 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005454 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005455 connection->inputChannel->getFd().get(),
5456 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005457 connection->getWindowName().c_str(),
5458 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005459 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005461 if (!connection->outboundQueue.empty()) {
5462 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5463 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005464 dump += dumpQueue(connection->outboundQueue, currentTime);
5465
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005467 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 }
5469
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005470 if (!connection->waitQueue.empty()) {
5471 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5472 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005473 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005475 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477 }
5478 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005479 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 }
5481
5482 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005483 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5484 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005486 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 }
5488
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005489 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005490 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5491 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5492 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005493 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005494 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495}
5496
Michael Wright3dd60e22019-03-27 22:06:44 +00005497void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5498 const size_t numMonitors = monitors.size();
5499 for (size_t i = 0; i < numMonitors; i++) {
5500 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005501 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005502 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5503 dump += "\n";
5504 }
5505}
5506
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005507class LooperEventCallback : public LooperCallback {
5508public:
5509 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5510 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5511
5512private:
5513 std::function<int(int events)> mCallback;
5514};
5515
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005516Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005517 if (DEBUG_CHANNEL_CREATION) {
5518 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005521 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005522 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005523 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005524
5525 if (result) {
5526 return base::Error(result) << "Failed to open input channel pair with name " << name;
5527 }
5528
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005530 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005531 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005532 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005533 sp<Connection> connection =
5534 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005536 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5537 ALOGE("Created a new connection, but the token %p is already known", token.get());
5538 }
5539 mConnectionsByToken.emplace(token, connection);
5540
5541 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5542 this, std::placeholders::_1, token);
5543
5544 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 } // release lock
5546
5547 // Wake the looper because some connections have changed.
5548 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005549 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550}
5551
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005552Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005553 const std::string& name,
5554 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005555 std::shared_ptr<InputChannel> serverChannel;
5556 std::unique_ptr<InputChannel> clientChannel;
5557 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5558 if (result) {
5559 return base::Error(result) << "Failed to open input channel pair with name " << name;
5560 }
5561
Michael Wright3dd60e22019-03-27 22:06:44 +00005562 { // acquire lock
5563 std::scoped_lock _l(mLock);
5564
5565 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005566 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5567 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005568 }
5569
Garfield Tan15601662020-09-22 15:32:38 -07005570 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005571 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005572 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005573
5574 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5575 ALOGE("Created a new connection, but the token %p is already known", token.get());
5576 }
5577 mConnectionsByToken.emplace(token, connection);
5578 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5579 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005580
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005581 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005582
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005583 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005584 }
Garfield Tan15601662020-09-22 15:32:38 -07005585
Michael Wright3dd60e22019-03-27 22:06:44 +00005586 // Wake the looper because some connections have changed.
5587 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005588 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005589}
5590
Garfield Tan15601662020-09-22 15:32:38 -07005591status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005593 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594
Garfield Tan15601662020-09-22 15:32:38 -07005595 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 if (status) {
5597 return status;
5598 }
5599 } // release lock
5600
5601 // Wake the poll loop because removing the connection may have changed the current
5602 // synchronization state.
5603 mLooper->wake();
5604 return OK;
5605}
5606
Garfield Tan15601662020-09-22 15:32:38 -07005607status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5608 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005609 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005610 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005611 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 return BAD_VALUE;
5613 }
5614
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005615 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005616
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005618 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619 }
5620
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005621 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622
5623 nsecs_t currentTime = now();
5624 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5625
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005626 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 return OK;
5628}
5629
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005630void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005631 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5632 auto& [displayId, monitors] = *it;
5633 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5634 return monitor.inputChannel->getConnectionToken() == connectionToken;
5635 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005636
Michael Wright3dd60e22019-03-27 22:06:44 +00005637 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005638 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005639 } else {
5640 ++it;
5641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 }
5643}
5644
Michael Wright3dd60e22019-03-27 22:06:44 +00005645status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005646 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005647
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005648 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5649 if (!requestingChannel) {
5650 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5651 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005652 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005653
5654 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5655 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5656 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5657 " Ignoring.");
5658 return BAD_VALUE;
5659 }
5660
5661 TouchState& state = *statePtr;
5662
5663 // Send cancel events to all the input channels we're stealing from.
5664 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5665 "input channel stole pointer stream");
5666 options.deviceId = state.deviceId;
5667 options.displayId = state.displayId;
5668 std::string canceledWindows;
5669 for (const TouchedWindow& window : state.windows) {
5670 const std::shared_ptr<InputChannel> channel =
5671 getInputChannelLocked(window.windowHandle->getToken());
5672 if (channel != nullptr && channel->getConnectionToken() != token) {
5673 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5674 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5675 canceledWindows += channel->getName();
5676 }
5677 }
5678 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5679 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5680 canceledWindows.c_str());
5681
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005682 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005683 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005684 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005685 return OK;
5686}
5687
Prabir Pradhan99987712020-11-10 18:43:05 -08005688void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5689 { // acquire lock
5690 std::scoped_lock _l(mLock);
5691 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005692 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005693 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5694 windowHandle != nullptr ? windowHandle->getName().c_str()
5695 : "token without window");
5696 }
5697
Vishnu Nairc519ff72021-01-21 08:23:08 -08005698 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005699 if (focusedToken != windowToken) {
5700 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5701 enabled ? "enable" : "disable");
5702 return;
5703 }
5704
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005705 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005706 ALOGW("Ignoring request to %s Pointer Capture: "
5707 "window has %s requested pointer capture.",
5708 enabled ? "enable" : "disable", enabled ? "already" : "not");
5709 return;
5710 }
5711
Christine Franksb768bb42021-11-29 12:11:31 -08005712 if (enabled) {
5713 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5714 mIneligibleDisplaysForPointerCapture.end(),
5715 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5716 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5717 return;
5718 }
5719 }
5720
Prabir Pradhan99987712020-11-10 18:43:05 -08005721 setPointerCaptureLocked(enabled);
5722 } // release lock
5723
5724 // Wake the thread to process command entries.
5725 mLooper->wake();
5726}
5727
Christine Franksb768bb42021-11-29 12:11:31 -08005728void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5729 { // acquire lock
5730 std::scoped_lock _l(mLock);
5731 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5732 if (!isEligible) {
5733 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5734 }
5735 } // release lock
5736}
5737
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005738std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5739 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005740 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005741 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005742 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005743 }
5744 }
5745 }
5746 return std::nullopt;
5747}
5748
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005749sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005750 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005751 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005752 }
5753
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005754 for (const auto& [token, connection] : mConnectionsByToken) {
5755 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005756 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757 }
5758 }
Robert Carr4e670e52018-08-15 13:26:12 -07005759
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005760 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761}
5762
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005763std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5764 sp<Connection> connection = getConnectionLocked(connectionToken);
5765 if (connection == nullptr) {
5766 return "<nullptr>";
5767 }
5768 return connection->getInputChannelName();
5769}
5770
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005771void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005772 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005773 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005774}
5775
Prabir Pradhancef936d2021-07-21 16:17:52 +00005776void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5777 const sp<Connection>& connection, uint32_t seq,
5778 bool handled, nsecs_t consumeTime) {
5779 // Handle post-event policy actions.
5780 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5781 if (dispatchEntryIt == connection->waitQueue.end()) {
5782 return;
5783 }
5784 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5785 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5786 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5787 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5788 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5789 }
5790 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5791 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5792 connection->inputChannel->getConnectionToken(),
5793 dispatchEntry->deliveryTime, consumeTime, finishTime);
5794 }
5795
5796 bool restartEvent;
5797 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5798 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5799 restartEvent =
5800 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5801 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5802 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5803 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5804 handled);
5805 } else {
5806 restartEvent = false;
5807 }
5808
5809 // Dequeue the event and start the next cycle.
5810 // Because the lock might have been released, it is possible that the
5811 // contents of the wait queue to have been drained, so we need to double-check
5812 // a few things.
5813 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5814 if (dispatchEntryIt != connection->waitQueue.end()) {
5815 dispatchEntry = *dispatchEntryIt;
5816 connection->waitQueue.erase(dispatchEntryIt);
5817 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5818 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5819 if (!connection->responsive) {
5820 connection->responsive = isConnectionResponsive(*connection);
5821 if (connection->responsive) {
5822 // The connection was unresponsive, and now it's responsive.
5823 processConnectionResponsiveLocked(*connection);
5824 }
5825 }
5826 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005827 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005828 connection->outboundQueue.push_front(dispatchEntry);
5829 traceOutboundQueueLength(*connection);
5830 } else {
5831 releaseDispatchEntry(dispatchEntry);
5832 }
5833 }
5834
5835 // Start the next dispatch cycle for this connection.
5836 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837}
5838
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5840 const sp<IBinder>& newToken) {
5841 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5842 scoped_unlock unlock(mLock);
5843 mPolicy->notifyFocusChanged(oldToken, newToken);
5844 };
5845 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846}
5847
Prabir Pradhancef936d2021-07-21 16:17:52 +00005848void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5849 auto command = [this, token, x, y]() REQUIRES(mLock) {
5850 scoped_unlock unlock(mLock);
5851 mPolicy->notifyDropWindow(token, x, y);
5852 };
5853 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005854}
5855
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5857 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5858 scoped_unlock unlock(mLock);
5859 mPolicy->notifyUntrustedTouch(obscuringPackage);
5860 };
5861 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005862}
5863
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005864void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5865 if (connection == nullptr) {
5866 LOG_ALWAYS_FATAL("Caller must check for nullness");
5867 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005868 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5869 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005870 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005871 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005872 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005873 return;
5874 }
5875 /**
5876 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5877 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5878 * has changed. This could cause newer entries to time out before the already dispatched
5879 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5880 * processes the events linearly. So providing information about the oldest entry seems to be
5881 * most useful.
5882 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005883 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5885 std::string reason =
5886 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005887 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005888 ns2ms(currentWait),
5889 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005890 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005891 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005892
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5894
5895 // Stop waking up for events on this connection, it is already unresponsive
5896 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005897}
5898
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005899void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5900 std::string reason =
5901 StringPrintf("%s does not have a focused window", application->getName().c_str());
5902 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005903
Prabir Pradhancef936d2021-07-21 16:17:52 +00005904 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5905 scoped_unlock unlock(mLock);
5906 mPolicy->notifyNoFocusedWindowAnr(application);
5907 };
5908 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005909}
5910
chaviw98318de2021-05-19 16:45:23 -05005911void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005912 const std::string& reason) {
5913 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5914 updateLastAnrStateLocked(windowLabel, reason);
5915}
5916
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005917void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5918 const std::string& reason) {
5919 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005920 updateLastAnrStateLocked(windowLabel, reason);
5921}
5922
5923void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5924 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005926 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 struct tm tm;
5928 localtime_r(&t, &tm);
5929 char timestr[64];
5930 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005931 mLastAnrState.clear();
5932 mLastAnrState += INDENT "ANR:\n";
5933 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005934 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5935 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005936 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937}
5938
Prabir Pradhancef936d2021-07-21 16:17:52 +00005939void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5940 KeyEntry& entry) {
5941 const KeyEvent event = createKeyEvent(entry);
5942 nsecs_t delay = 0;
5943 { // release lock
5944 scoped_unlock unlock(mLock);
5945 android::base::Timer t;
5946 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5947 entry.policyFlags);
5948 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5949 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5950 std::to_string(t.duration().count()).c_str());
5951 }
5952 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953
5954 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005955 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005956 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005959 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5960 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962}
5963
Prabir Pradhancef936d2021-07-21 16:17:52 +00005964void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005965 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005966 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005967 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005968 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005969 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005970 };
5971 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005972}
5973
Prabir Pradhanedd96402022-02-15 01:46:16 -08005974void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5975 std::optional<int32_t> pid) {
5976 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005978 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005979 };
5980 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005981}
5982
5983/**
5984 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5985 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5986 * command entry to the command queue.
5987 */
5988void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5989 std::string reason) {
5990 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005991 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005992 if (connection.monitor) {
5993 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5994 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005995 pid = findMonitorPidByTokenLocked(connectionToken);
5996 } else {
5997 // The connection is a window
5998 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5999 reason.c_str());
6000 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6001 if (handle != nullptr) {
6002 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006003 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006004 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006005 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006006}
6007
6008/**
6009 * Tell the policy that a connection has become responsive so that it can stop ANR.
6010 */
6011void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6012 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006013 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006014 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 pid = findMonitorPidByTokenLocked(connectionToken);
6016 } else {
6017 // The connection is a window
6018 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6019 if (handle != nullptr) {
6020 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006021 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006022 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006023 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024}
6025
Prabir Pradhancef936d2021-07-21 16:17:52 +00006026bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006027 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006028 KeyEntry& keyEntry, bool handled) {
6029 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006030 if (!handled) {
6031 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006033 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034 return false;
6035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006037 // Get the fallback key state.
6038 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006039 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 connection->inputState.removeFallbackKey(originalKeyCode);
6043 }
6044
6045 if (handled || !dispatchEntry->hasForegroundTarget()) {
6046 // If the application handles the original key for which we previously
6047 // generated a fallback or if the window is not a foreground window,
6048 // then cancel the associated fallback key, if any.
6049 if (fallbackKeyCode != -1) {
6050 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006051 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6052 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6053 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6054 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6055 keyEntry.policyFlags);
6056 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006057 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006058 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059
6060 mLock.unlock();
6061
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006062 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006063 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064
6065 mLock.lock();
6066
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067 // Cancel the fallback key.
6068 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070 "application handled the original non-fallback key "
6071 "or is no longer a foreground target, "
6072 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 options.keyCode = fallbackKeyCode;
6074 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006076 connection->inputState.removeFallbackKey(originalKeyCode);
6077 }
6078 } else {
6079 // If the application did not handle a non-fallback key, first check
6080 // that we are in a good state to perform unhandled key event processing
6081 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006082 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006084 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6085 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6086 "since this is not an initial down. "
6087 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6088 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6089 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 return false;
6091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006093 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006094 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6095 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6096 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6097 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6098 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006099 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006100
6101 mLock.unlock();
6102
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006103 bool fallback =
6104 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106
6107 mLock.lock();
6108
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006109 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006110 connection->inputState.removeFallbackKey(originalKeyCode);
6111 return false;
6112 }
6113
6114 // Latch the fallback keycode for this key on an initial down.
6115 // The fallback keycode cannot change at any other point in the lifecycle.
6116 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118 fallbackKeyCode = event.getKeyCode();
6119 } else {
6120 fallbackKeyCode = AKEYCODE_UNKNOWN;
6121 }
6122 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6123 }
6124
6125 ALOG_ASSERT(fallbackKeyCode != -1);
6126
6127 // Cancel the fallback key if the policy decides not to send it anymore.
6128 // We will continue to dispatch the key to the policy but we will no
6129 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006130 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6131 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006132 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6133 if (fallback) {
6134 ALOGD("Unhandled key event: Policy requested to send key %d"
6135 "as a fallback for %d, but on the DOWN it had requested "
6136 "to send %d instead. Fallback canceled.",
6137 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6138 } else {
6139 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6140 "but on the DOWN it had requested to send %d. "
6141 "Fallback canceled.",
6142 originalKeyCode, fallbackKeyCode);
6143 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006144 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006145
6146 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6147 "canceling fallback, policy no longer desires it");
6148 options.keyCode = fallbackKeyCode;
6149 synthesizeCancelationEventsForConnectionLocked(connection, options);
6150
6151 fallback = false;
6152 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006153 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006154 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006155 }
6156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006157
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006158 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6159 {
6160 std::string msg;
6161 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6162 connection->inputState.getFallbackKeys();
6163 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6164 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6165 }
6166 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6167 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006168 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006169 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006170
6171 if (fallback) {
6172 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006173 keyEntry.eventTime = event.getEventTime();
6174 keyEntry.deviceId = event.getDeviceId();
6175 keyEntry.source = event.getSource();
6176 keyEntry.displayId = event.getDisplayId();
6177 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6178 keyEntry.keyCode = fallbackKeyCode;
6179 keyEntry.scanCode = event.getScanCode();
6180 keyEntry.metaState = event.getMetaState();
6181 keyEntry.repeatCount = event.getRepeatCount();
6182 keyEntry.downTime = event.getDownTime();
6183 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006184
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006185 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6186 ALOGD("Unhandled key event: Dispatching fallback key. "
6187 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6188 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6189 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190 return true; // restart the event
6191 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006192 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6193 ALOGD("Unhandled key event: No fallback key.");
6194 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006195
6196 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006197 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198 }
6199 }
6200 return false;
6201}
6202
Prabir Pradhancef936d2021-07-21 16:17:52 +00006203bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006204 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006205 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206 return false;
6207}
6208
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209void InputDispatcher::traceInboundQueueLengthLocked() {
6210 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006211 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006212 }
6213}
6214
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006215void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 if (ATRACE_ENABLED()) {
6217 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006218 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6219 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 }
6221}
6222
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006223void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224 if (ATRACE_ENABLED()) {
6225 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006226 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6227 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 }
6229}
6230
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006231void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006232 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006234 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 dumpDispatchStateLocked(dump);
6236
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006237 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006238 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006239 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 }
6241}
6242
6243void InputDispatcher::monitor() {
6244 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006245 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006247 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248}
6249
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006250/**
6251 * Wake up the dispatcher and wait until it processes all events and commands.
6252 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6253 * this method can be safely called from any thread, as long as you've ensured that
6254 * the work you are interested in completing has already been queued.
6255 */
6256bool InputDispatcher::waitForIdle() {
6257 /**
6258 * Timeout should represent the longest possible time that a device might spend processing
6259 * events and commands.
6260 */
6261 constexpr std::chrono::duration TIMEOUT = 100ms;
6262 std::unique_lock lock(mLock);
6263 mLooper->wake();
6264 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6265 return result == std::cv_status::no_timeout;
6266}
6267
Vishnu Naire798b472020-07-23 13:52:21 -07006268/**
6269 * Sets focus to the window identified by the token. This must be called
6270 * after updating any input window handles.
6271 *
6272 * Params:
6273 * request.token - input channel token used to identify the window that should gain focus.
6274 * request.focusedToken - the token that the caller expects currently to be focused. If the
6275 * specified token does not match the currently focused window, this request will be dropped.
6276 * If the specified focused token matches the currently focused window, the call will succeed.
6277 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6278 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6279 * when requesting the focus change. This determines which request gets
6280 * precedence if there is a focus change request from another source such as pointer down.
6281 */
Vishnu Nair958da932020-08-21 17:12:37 -07006282void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6283 { // acquire lock
6284 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006285 std::optional<FocusResolver::FocusChanges> changes =
6286 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6287 if (changes) {
6288 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006289 }
6290 } // release lock
6291 // Wake up poll loop since it may need to make new input dispatching choices.
6292 mLooper->wake();
6293}
6294
Vishnu Nairc519ff72021-01-21 08:23:08 -08006295void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6296 if (changes.oldFocus) {
6297 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006298 if (focusedInputChannel) {
6299 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6300 "focus left window");
6301 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006302 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006303 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006304 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006305 if (changes.newFocus) {
6306 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006307 }
6308
Prabir Pradhan99987712020-11-10 18:43:05 -08006309 // If a window has pointer capture, then it must have focus. We need to ensure that this
6310 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6311 // If the window loses focus before it loses pointer capture, then the window can be in a state
6312 // where it has pointer capture but not focus, violating the contract. Therefore we must
6313 // dispatch the pointer capture event before the focus event. Since focus events are added to
6314 // the front of the queue (above), we add the pointer capture event to the front of the queue
6315 // after the focus events are added. This ensures the pointer capture event ends up at the
6316 // front.
6317 disablePointerCaptureForcedLocked();
6318
Vishnu Nairc519ff72021-01-21 08:23:08 -08006319 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006320 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006321 }
6322}
Vishnu Nair958da932020-08-21 17:12:37 -07006323
Prabir Pradhan99987712020-11-10 18:43:05 -08006324void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006325 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006326 return;
6327 }
6328
6329 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6330
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006331 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006332 setPointerCaptureLocked(false);
6333 }
6334
6335 if (!mWindowTokenWithPointerCapture) {
6336 // No need to send capture changes because no window has capture.
6337 return;
6338 }
6339
6340 if (mPendingEvent != nullptr) {
6341 // Move the pending event to the front of the queue. This will give the chance
6342 // for the pending event to be dropped if it is a captured event.
6343 mInboundQueue.push_front(mPendingEvent);
6344 mPendingEvent = nullptr;
6345 }
6346
6347 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006348 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006349 mInboundQueue.push_front(std::move(entry));
6350}
6351
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006352void InputDispatcher::setPointerCaptureLocked(bool enable) {
6353 mCurrentPointerCaptureRequest.enable = enable;
6354 mCurrentPointerCaptureRequest.seq++;
6355 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006356 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006357 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006358 };
6359 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006360}
6361
Vishnu Nair599f1412021-06-21 10:39:58 -07006362void InputDispatcher::displayRemoved(int32_t displayId) {
6363 { // acquire lock
6364 std::scoped_lock _l(mLock);
6365 // Set an empty list to remove all handles from the specific display.
6366 setInputWindowsLocked(/* window handles */ {}, displayId);
6367 setFocusedApplicationLocked(displayId, nullptr);
6368 // Call focus resolver to clean up stale requests. This must be called after input windows
6369 // have been removed for the removed display.
6370 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006371 // Reset pointer capture eligibility, regardless of previous state.
6372 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006373 } // release lock
6374
6375 // Wake up poll loop since it may need to make new input dispatching choices.
6376 mLooper->wake();
6377}
6378
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006379void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6380 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006381 // The listener sends the windows as a flattened array. Separate the windows by display for
6382 // more convenient parsing.
6383 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006384 for (const auto& info : windowInfos) {
6385 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6386 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6387 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006388
6389 { // acquire lock
6390 std::scoped_lock _l(mLock);
6391 mDisplayInfos.clear();
6392 for (const auto& displayInfo : displayInfos) {
6393 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6394 }
6395
6396 for (const auto& [displayId, handles] : handlesPerDisplay) {
6397 setInputWindowsLocked(handles, displayId);
6398 }
6399 }
6400 // Wake up poll loop since it may need to make new input dispatching choices.
6401 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006402}
6403
Vishnu Nair062a8672021-09-03 16:07:44 -07006404bool InputDispatcher::shouldDropInput(
6405 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006406 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6407 (windowHandle->getInfo()->inputConfig.test(
6408 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006409 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006410 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6411 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006412 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006413 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006414 windowHandle->getInfo()->displayId);
6415 return true;
6416 }
6417 return false;
6418}
6419
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006420void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6421 const std::vector<gui::WindowInfo>& windowInfos,
6422 const std::vector<DisplayInfo>& displayInfos) {
6423 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6424}
6425
Arthur Hungdfd528e2021-12-08 13:23:04 +00006426void InputDispatcher::cancelCurrentTouch() {
6427 {
6428 std::scoped_lock _l(mLock);
6429 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6430 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6431 "cancel current touch");
6432 synthesizeCancelationEventsForAllConnectionsLocked(options);
6433
6434 mTouchStatesByDisplay.clear();
6435 mLastHoverWindowHandle.clear();
6436 }
6437 // Wake up poll loop since there might be work to do.
6438 mLooper->wake();
6439}
6440
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006441void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6442 std::scoped_lock _l(mLock);
6443 mMonitorDispatchingTimeout = timeout;
6444}
6445
Garfield Tane84e6f92019-08-29 17:28:41 -07006446} // namespace android::inputdispatcher