blob: b5a3825fc351288541d28a1aa9bbe395d49a3e72 [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 Pradhan8a2b1a42022-04-11 17:23:34 +0000581// Checks targeted injection using the window's owner's uid.
582// Returns an empty string if an entry can be sent to the given window, or an error message if the
583// entry is a targeted injection whose uid target doesn't match the window owner.
584std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
585 const EventEntry& entry) {
586 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
587 // The event was not injected, or the injected event does not target a window.
588 return {};
589 }
590 const int32_t uid = *entry.injectionState->targetUid;
591 if (window == nullptr) {
592 return StringPrintf("No valid window target for injection into uid %d.", uid);
593 }
594 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
595 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
596 "owned by uid %d.",
597 uid, window->getName().c_str(), window->getInfo()->ownerUid);
598 }
599 return {};
600}
601
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000602} // namespace
603
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604// --- InputDispatcher ---
605
Garfield Tan00f511d2019-06-12 16:55:40 -0700606InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800607 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
608
609InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
610 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700611 : mPolicy(policy),
612 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700613 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800614 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700615 mAppSwitchSawKeyDown(false),
616 mAppSwitchDueTime(LONG_LONG_MAX),
617 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800618 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700619 mDispatchEnabled(false),
620 mDispatchFrozen(false),
621 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800622 // mInTouchMode will be initialized by the WindowManager to the default device config.
623 // To avoid leaking stack in case that call never comes, and for tests,
624 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000625 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100626 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000627 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800628 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800629 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000630 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800631 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800633 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700635 mWindowInfoListener = new DispatcherWindowListener(*this);
636 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
637
Yi Kong9b14ac62018-07-17 13:48:38 -0700638 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639
640 policy->getDispatcherConfiguration(&mConfig);
641}
642
643InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000644 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645
Prabir Pradhancef936d2021-07-21 16:17:52 +0000646 resetKeyRepeatLocked();
647 releasePendingEventLocked();
648 drainInboundQueueLocked();
649 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000651 while (!mConnectionsByToken.empty()) {
652 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000653 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
654 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 }
656}
657
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700658status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700659 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700660 return ALREADY_EXISTS;
661 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700662 mThread = std::make_unique<InputThread>(
663 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
664 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700665}
666
667status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700668 if (mThread && mThread->isCallingThread()) {
669 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700670 return INVALID_OPERATION;
671 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700672 mThread.reset();
673 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700674}
675
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676void InputDispatcher::dispatchOnce() {
677 nsecs_t nextWakeupTime = LONG_LONG_MAX;
678 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800679 std::scoped_lock _l(mLock);
680 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681
682 // Run a dispatch loop if there are no pending commands.
683 // The dispatch loop might enqueue commands to run afterwards.
684 if (!haveCommandsLocked()) {
685 dispatchOnceInnerLocked(&nextWakeupTime);
686 }
687
688 // Run all pending commands if there are any.
689 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000690 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 nextWakeupTime = LONG_LONG_MIN;
692 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800693
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 // If we are still waiting for ack on some events,
695 // we might have to wake up earlier to check if an app is anr'ing.
696 const nsecs_t nextAnrCheck = processAnrsLocked();
697 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
698
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800699 // We are about to enter an infinitely long sleep, because we have no commands or
700 // pending or queued events
701 if (nextWakeupTime == LONG_LONG_MAX) {
702 mDispatcherEnteredIdle.notify_all();
703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 } // release lock
705
706 // Wait for callback or timeout or wake. (make sure we round up, not down)
707 nsecs_t currentTime = now();
708 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
709 mLooper->pollOnce(timeoutMillis);
710}
711
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500713 * Raise ANR if there is no focused window.
714 * Before the ANR is raised, do a final state check:
715 * 1. The currently focused application must be the same one we are waiting for.
716 * 2. Ensure we still don't have a focused window.
717 */
718void InputDispatcher::processNoFocusedWindowAnrLocked() {
719 // Check if the application that we are waiting for is still focused.
720 std::shared_ptr<InputApplicationHandle> focusedApplication =
721 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
722 if (focusedApplication == nullptr ||
723 focusedApplication->getApplicationToken() !=
724 mAwaitedFocusedApplication->getApplicationToken()) {
725 // Unexpected because we should have reset the ANR timer when focused application changed
726 ALOGE("Waited for a focused window, but focused application has already changed to %s",
727 focusedApplication->getName().c_str());
728 return; // The focused application has changed.
729 }
730
chaviw98318de2021-05-19 16:45:23 -0500731 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500732 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
733 if (focusedWindowHandle != nullptr) {
734 return; // We now have a focused window. No need for ANR.
735 }
736 onAnrLocked(mAwaitedFocusedApplication);
737}
738
739/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700740 * Check if any of the connections' wait queues have events that are too old.
741 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
742 * Return the time at which we should wake up next.
743 */
744nsecs_t InputDispatcher::processAnrsLocked() {
745 const nsecs_t currentTime = now();
746 nsecs_t nextAnrCheck = LONG_LONG_MAX;
747 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
748 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
749 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500750 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700751 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500752 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700753 return LONG_LONG_MIN;
754 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500755 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700756 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
757 }
758 }
759
760 // Check if any connection ANRs are due
761 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
762 if (currentTime < nextAnrCheck) { // most likely scenario
763 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
764 }
765
766 // If we reached here, we have an unresponsive connection.
767 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
768 if (connection == nullptr) {
769 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
770 return nextAnrCheck;
771 }
772 connection->responsive = false;
773 // Stop waking up for this unresponsive connection
774 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000775 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700776 return LONG_LONG_MIN;
777}
778
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800779std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
780 const sp<Connection>& connection) {
781 if (connection->monitor) {
782 return mMonitorDispatchingTimeout;
783 }
784 const sp<WindowInfoHandle> window =
785 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700786 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500787 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700788 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500789 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700790}
791
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
793 nsecs_t currentTime = now();
794
Jeff Browndc5992e2014-04-11 01:27:26 -0700795 // Reset the key repeat timer whenever normal dispatch is suspended while the
796 // device is in a non-interactive state. This is to ensure that we abort a key
797 // repeat if the device is just coming out of sleep.
798 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 resetKeyRepeatLocked();
800 }
801
802 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
803 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100804 if (DEBUG_FOCUS) {
805 ALOGD("Dispatch frozen. Waiting some more.");
806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 return;
808 }
809
810 // Optimize latency of app switches.
811 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
812 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
813 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
814 if (mAppSwitchDueTime < *nextWakeupTime) {
815 *nextWakeupTime = mAppSwitchDueTime;
816 }
817
818 // Ready to start a new event.
819 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700821 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 if (isAppSwitchDue) {
823 // The inbound queue is empty so the app switch key we were waiting
824 // for will never arrive. Stop waiting for it.
825 resetPendingAppSwitchLocked(false);
826 isAppSwitchDue = false;
827 }
828
829 // Synthesize a key repeat if appropriate.
830 if (mKeyRepeatState.lastKeyEntry) {
831 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
832 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
833 } else {
834 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
835 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
836 }
837 }
838 }
839
840 // Nothing to do if there is no pending event.
841 if (!mPendingEvent) {
842 return;
843 }
844 } else {
845 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700846 mPendingEvent = mInboundQueue.front();
847 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 traceInboundQueueLengthLocked();
849 }
850
851 // Poke user activity for this event.
852 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700853 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 }
856
857 // Now we have an event to dispatch.
858 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700859 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700863 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 }
867
868 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700869 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
871
872 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700873 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 const ConfigurationChangedEntry& typedEntry =
875 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 break;
879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700881 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 const DeviceResetEntry& typedEntry =
883 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 break;
887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100889 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700890 std::shared_ptr<FocusEntry> typedEntry =
891 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100892 dispatchFocusLocked(currentTime, typedEntry);
893 done = true;
894 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
895 break;
896 }
897
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700898 case EventEntry::Type::TOUCH_MODE_CHANGED: {
899 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
900 dispatchTouchModeChangeLocked(currentTime, typedEntry);
901 done = true;
902 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
903 break;
904 }
905
Prabir Pradhan99987712020-11-10 18:43:05 -0800906 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
907 const auto typedEntry =
908 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
909 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
910 done = true;
911 break;
912 }
913
arthurhungb89ccb02020-12-30 16:19:01 +0800914 case EventEntry::Type::DRAG: {
915 std::shared_ptr<DragEntry> typedEntry =
916 std::static_pointer_cast<DragEntry>(mPendingEvent);
917 dispatchDragLocked(currentTime, typedEntry);
918 done = true;
919 break;
920 }
921
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700922 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700923 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700925 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 resetPendingAppSwitchLocked(true);
927 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700928 } else if (dropReason == DropReason::NOT_DROPPED) {
929 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 }
931 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700932 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700933 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700935 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
936 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700938 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 break;
940 }
941
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700942 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943 std::shared_ptr<MotionEntry> motionEntry =
944 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700945 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
946 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700948 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700949 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700951 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
952 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700954 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
Chris Yef59a2f42020-10-16 12:55:26 -0700957
958 case EventEntry::Type::SENSOR: {
959 std::shared_ptr<SensorEntry> sensorEntry =
960 std::static_pointer_cast<SensorEntry>(mPendingEvent);
961 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
962 dropReason = DropReason::APP_SWITCH;
963 }
964 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
965 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
966 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
967 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
968 dropReason = DropReason::STALE;
969 }
970 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
971 done = true;
972 break;
973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 }
975
976 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700977 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700978 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
Michael Wright3a981722015-06-10 15:26:13 +0100980 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981
982 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 }
985}
986
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800987bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
988 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
989}
990
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700991/**
992 * Return true if the events preceding this incoming motion event should be dropped
993 * Return false otherwise (the default behaviour)
994 */
995bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700996 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700997 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700998
999 // Optimize case where the current application is unresponsive and the user
1000 // decides to touch a window in a different application.
1001 // If the application takes too long to catch up then we drop all events preceding
1002 // the touch into the other window.
1003 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001004 int32_t displayId = motionEntry.displayId;
1005 int32_t x = static_cast<int32_t>(
1006 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1007 int32_t y = static_cast<int32_t>(
1008 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -07001009
1010 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05001011 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07001012 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001013 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001014 touchedWindowHandle->getApplicationToken() !=
1015 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001016 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001017 ALOGI("Pruning input queue because user touched a different application while waiting "
1018 "for %s",
1019 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001020 return true;
1021 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001022
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001023 // Alternatively, maybe there's a spy window that could handle this event.
1024 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1025 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1026 for (const auto& windowHandle : touchedSpies) {
1027 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001028 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001029 // This spy window could take more input. Drop all events preceding this
1030 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001031 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001032 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 mAwaitedFocusedApplication->getName().c_str());
1034 return true;
1035 }
1036 }
1037 }
1038
1039 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1040 // yet been processed by some connections, the dispatcher will wait for these motion
1041 // events to be processed before dispatching the key event. This is because these motion events
1042 // may cause a new window to be launched, which the user might expect to receive focus.
1043 // To prevent waiting forever for such events, just send the key to the currently focused window
1044 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1045 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1046 "just send the pending key event to the focused window.");
1047 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001048 }
1049 return false;
1050}
1051
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001052bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001053 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001054 mInboundQueue.push_back(std::move(newEntry));
1055 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 traceInboundQueueLengthLocked();
1057
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001058 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001059 case EventEntry::Type::KEY: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001060 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1061 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 // Optimize app switch latency.
1063 // If the application takes too long to catch up then we drop all events preceding
1064 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001065 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001066 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001067 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001069 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001071 if (DEBUG_APP_SWITCH) {
1072 ALOGD("App switch is pending!");
1073 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001074 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 mAppSwitchSawKeyDown = false;
1076 needWake = true;
1077 }
1078 }
1079 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001080
1081 // If a new up event comes in, and the pending event with same key code has been asked
1082 // to try again later because of the policy. We have to reset the intercept key wake up
1083 // time for it may have been handled in the policy and could be dropped.
1084 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1085 mPendingEvent->type == EventEntry::Type::KEY) {
1086 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1087 if (pendingKey.keyCode == keyEntry.keyCode &&
1088 pendingKey.interceptKeyResult ==
1089 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1090 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1091 pendingKey.interceptKeyWakeupTime = 0;
1092 needWake = true;
1093 }
1094 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001095 break;
1096 }
1097
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001098 case EventEntry::Type::MOTION: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001099 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1100 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001101 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1102 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001103 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001107 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001108 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1109 break;
1110 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001111 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001112 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001113 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001114 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001115 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1116 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001117 // nothing to do
1118 break;
1119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
1121
1122 return needWake;
1123}
1124
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001125void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001126 // Do not store sensor event in recent queue to avoid flooding the queue.
1127 if (entry->type != EventEntry::Type::SENSOR) {
1128 mRecentQueue.push_back(entry);
1129 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001130 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001131 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
1133}
1134
chaviw98318de2021-05-19 16:45:23 -05001135sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1136 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001137 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001138 bool addOutsideTargets,
1139 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001140 if (addOutsideTargets && touchState == nullptr) {
1141 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001144 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001145 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001146 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001147 continue;
1148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001150 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001151 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001152 return windowHandle;
1153 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001154
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001155 if (addOutsideTargets &&
1156 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001157 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1158 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 }
1160 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001161 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162}
1163
Prabir Pradhand65552b2021-10-07 11:23:50 -07001164std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1165 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001166 // Traverse windows from front to back and gather the touched spy windows.
1167 std::vector<sp<WindowInfoHandle>> spyWindows;
1168 const auto& windowHandles = getWindowHandlesLocked(displayId);
1169 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1170 const WindowInfo& info = *windowHandle->getInfo();
1171
Prabir Pradhand65552b2021-10-07 11:23:50 -07001172 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001173 continue;
1174 }
1175 if (!info.isSpy()) {
1176 // The first touched non-spy window was found, so return the spy windows touched so far.
1177 return spyWindows;
1178 }
1179 spyWindows.push_back(windowHandle);
1180 }
1181 return spyWindows;
1182}
1183
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001184void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 const char* reason;
1186 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001188 if (DEBUG_INBOUND_EVENT_DETAILS) {
1189 ALOGD("Dropped event because policy consumed it.");
1190 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001191 reason = "inbound event was dropped because the policy consumed it";
1192 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001193 case DropReason::DISABLED:
1194 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 ALOGI("Dropped event because input dispatch is disabled.");
1196 }
1197 reason = "inbound event was dropped because input dispatch is disabled";
1198 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001199 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001200 ALOGI("Dropped event because of pending overdue app switch.");
1201 reason = "inbound event was dropped because of pending overdue app switch";
1202 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001203 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 ALOGI("Dropped event because the current application is not responding and the user "
1205 "has started interacting with a different application.");
1206 reason = "inbound event was dropped because the current application is not responding "
1207 "and the user has started interacting with a different application";
1208 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001209 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 ALOGI("Dropped event because it is stale.");
1211 reason = "inbound event was dropped because it is stale";
1212 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001213 case DropReason::NO_POINTER_CAPTURE:
1214 ALOGI("Dropped event because there is no window with Pointer Capture.");
1215 reason = "inbound event was dropped because there is no window with Pointer Capture";
1216 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001217 case DropReason::NOT_DROPPED: {
1218 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 }
1222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001223 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001224 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1226 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001229 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001230 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1231 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1233 synthesizeCancelationEventsForAllConnectionsLocked(options);
1234 } else {
1235 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1236 synthesizeCancelationEventsForAllConnectionsLocked(options);
1237 }
1238 break;
1239 }
Chris Yef59a2f42020-10-16 12:55:26 -07001240 case EventEntry::Type::SENSOR: {
1241 break;
1242 }
arthurhungb89ccb02020-12-30 16:19:01 +08001243 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1244 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001245 break;
1246 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001247 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001248 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001249 case EventEntry::Type::CONFIGURATION_CHANGED:
1250 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001251 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001252 break;
1253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255}
1256
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001257static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1259 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260}
1261
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1263 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1264 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1265 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266}
1267
1268bool InputDispatcher::isAppSwitchPendingLocked() {
1269 return mAppSwitchDueTime != LONG_LONG_MAX;
1270}
1271
1272void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1273 mAppSwitchDueTime = LONG_LONG_MAX;
1274
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001275 if (DEBUG_APP_SWITCH) {
1276 if (handled) {
1277 ALOGD("App switch has arrived.");
1278 } else {
1279 ALOGD("App switch was abandoned.");
1280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282}
1283
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001285 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286}
1287
Prabir Pradhancef936d2021-07-21 16:17:52 +00001288bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001289 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 return false;
1291 }
1292
1293 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001294 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001295 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001296 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1297 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001298 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 return true;
1300}
1301
Prabir Pradhancef936d2021-07-21 16:17:52 +00001302void InputDispatcher::postCommandLocked(Command&& command) {
1303 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304}
1305
1306void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001307 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001309 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 releaseInboundEventLocked(entry);
1311 }
1312 traceInboundQueueLengthLocked();
1313}
1314
1315void InputDispatcher::releasePendingEventLocked() {
1316 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001318 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320}
1321
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001322void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001324 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001325 if (DEBUG_DISPATCH_CYCLE) {
1326 ALOGD("Injected inbound event was dropped.");
1327 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001328 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 }
1330 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001331 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
1333 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334}
1335
1336void InputDispatcher::resetKeyRepeatLocked() {
1337 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340}
1341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001342std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1343 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344
Michael Wright2e732952014-09-24 13:26:59 -07001345 uint32_t policyFlags = entry->policyFlags &
1346 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001348 std::shared_ptr<KeyEntry> newEntry =
1349 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1350 entry->source, entry->displayId, policyFlags, entry->action,
1351 entry->flags, entry->keyCode, entry->scanCode,
1352 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354 newEntry->syntheticRepeat = true;
1355 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001357 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358}
1359
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001362 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1363 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365
1366 // Reset key repeating in case a keyboard device was added or removed or something.
1367 resetKeyRepeatLocked();
1368
1369 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001370 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1371 scoped_unlock unlock(mLock);
1372 mPolicy->notifyConfigurationChanged(eventTime);
1373 };
1374 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 return true;
1376}
1377
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001378bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1379 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001380 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1381 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1382 entry.deviceId);
1383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384
liushenxiang42232912021-05-21 20:24:09 +08001385 // Reset key repeating in case a keyboard device was disabled or enabled.
1386 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1387 resetKeyRepeatLocked();
1388 }
1389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001390 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001391 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 synthesizeCancelationEventsForAllConnectionsLocked(options);
1393 return true;
1394}
1395
Vishnu Nairad321cd2020-08-20 16:40:21 -07001396void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001397 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001398 if (mPendingEvent != nullptr) {
1399 // Move the pending event to the front of the queue. This will give the chance
1400 // for the pending event to get dispatched to the newly focused window
1401 mInboundQueue.push_front(mPendingEvent);
1402 mPendingEvent = nullptr;
1403 }
1404
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001405 std::unique_ptr<FocusEntry> focusEntry =
1406 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1407 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001408
1409 // This event should go to the front of the queue, but behind all other focus events
1410 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001411 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001412 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001413 [](const std::shared_ptr<EventEntry>& event) {
1414 return event->type == EventEntry::Type::FOCUS;
1415 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001416
1417 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001419}
1420
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001421void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001422 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001423 if (channel == nullptr) {
1424 return; // Window has gone away
1425 }
1426 InputTarget target;
1427 target.inputChannel = channel;
1428 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1429 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001430 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1431 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001432 std::string reason = std::string("reason=").append(entry->reason);
1433 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001434 dispatchEventLocked(currentTime, entry, {target});
1435}
1436
Prabir Pradhan99987712020-11-10 18:43:05 -08001437void InputDispatcher::dispatchPointerCaptureChangedLocked(
1438 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1439 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001440 dropReason = DropReason::NOT_DROPPED;
1441
Prabir Pradhan99987712020-11-10 18:43:05 -08001442 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001443 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001444
1445 if (entry->pointerCaptureRequest.enable) {
1446 // Enable Pointer Capture.
1447 if (haveWindowWithPointerCapture &&
1448 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001449 // This can happen if pointer capture is disabled and re-enabled before we notify the
1450 // app of the state change, so there is no need to notify the app.
1451 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1452 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001453 }
1454 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001455 // This can happen if a window requests capture and immediately releases capture.
1456 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001457 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001458 return;
1459 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001460 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1461 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1462 return;
1463 }
1464
Vishnu Nairc519ff72021-01-21 08:23:08 -08001465 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001466 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1467 mWindowTokenWithPointerCapture = token;
1468 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001469 // Disable Pointer Capture.
1470 // We do not check if the sequence number matches for requests to disable Pointer Capture
1471 // for two reasons:
1472 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1473 // to disable capture with the same sequence number: one generated by
1474 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1475 // Capture being disabled in InputReader.
1476 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1477 // actual Pointer Capture state that affects events being generated by input devices is
1478 // in InputReader.
1479 if (!haveWindowWithPointerCapture) {
1480 // Pointer capture was already forcefully disabled because of focus change.
1481 dropReason = DropReason::NOT_DROPPED;
1482 return;
1483 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001484 token = mWindowTokenWithPointerCapture;
1485 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001486 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001487 setPointerCaptureLocked(false);
1488 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001489 }
1490
1491 auto channel = getInputChannelLocked(token);
1492 if (channel == nullptr) {
1493 // Window has gone away, clean up Pointer Capture state.
1494 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001495 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001496 setPointerCaptureLocked(false);
1497 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001498 return;
1499 }
1500 InputTarget target;
1501 target.inputChannel = channel;
1502 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1503 entry->dispatchInProgress = true;
1504 dispatchEventLocked(currentTime, entry, {target});
1505
1506 dropReason = DropReason::NOT_DROPPED;
1507}
1508
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001509void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1510 const std::shared_ptr<TouchModeEntry>& entry) {
1511 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1512 getWindowHandlesLocked(mFocusedDisplayId);
1513 if (windowHandles.empty()) {
1514 return;
1515 }
1516 const std::vector<InputTarget> inputTargets =
1517 getInputTargetsFromWindowHandlesLocked(windowHandles);
1518 if (inputTargets.empty()) {
1519 return;
1520 }
1521 entry->dispatchInProgress = true;
1522 dispatchEventLocked(currentTime, entry, inputTargets);
1523}
1524
1525std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1526 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1527 std::vector<InputTarget> inputTargets;
1528 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1529 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1530 const sp<IBinder>& token = handle->getToken();
1531 if (token == nullptr) {
1532 continue;
1533 }
1534 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1535 if (channel == nullptr) {
1536 continue; // Window has gone away
1537 }
1538 InputTarget target;
1539 target.inputChannel = channel;
1540 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1541 inputTargets.push_back(target);
1542 }
1543 return inputTargets;
1544}
1545
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001546bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001549 if (!entry->dispatchInProgress) {
1550 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1551 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1552 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1553 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001554 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 // We have seen two identical key downs in a row which indicates that the device
1556 // driver is automatically generating key repeats itself. We take note of the
1557 // repeat here, but we disable our own next key repeat timer since it is clear that
1558 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001559 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1560 // Make sure we don't get key down from a different device. If a different
1561 // device Id has same key pressed down, the new device Id will replace the
1562 // current one to hold the key repeat with repeat count reset.
1563 // In the future when got a KEY_UP on the device id, drop it and do not
1564 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1566 resetKeyRepeatLocked();
1567 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1568 } else {
1569 // Not a repeat. Save key down state in case we do see a repeat later.
1570 resetKeyRepeatLocked();
1571 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1572 }
1573 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001574 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1575 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001576 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001577 if (DEBUG_INBOUND_EVENT_DETAILS) {
1578 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1579 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 resetKeyRepeatLocked();
1582 }
1583
1584 if (entry->repeatCount == 1) {
1585 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1586 } else {
1587 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1588 }
1589
1590 entry->dispatchInProgress = true;
1591
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001592 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594
1595 // Handle case where the policy asked us to try again later last time.
1596 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1597 if (currentTime < entry->interceptKeyWakeupTime) {
1598 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1599 *nextWakeupTime = entry->interceptKeyWakeupTime;
1600 }
1601 return false; // wait until next wakeup
1602 }
1603 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1604 entry->interceptKeyWakeupTime = 0;
1605 }
1606
1607 // Give the policy a chance to intercept the key.
1608 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1609 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001610 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001611 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001612
1613 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1614 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1615 };
1616 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 return false; // wait for the command to run
1618 } else {
1619 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1620 }
1621 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001622 if (*dropReason == DropReason::NOT_DROPPED) {
1623 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 }
1625 }
1626
1627 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001628 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001629 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001630 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1631 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001632 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 return true;
1634 }
1635
1636 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001637 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001638 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001639 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 return false;
1642 }
1643
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001644 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 return true;
1647 }
1648
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001649 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 // Dispatch the key.
1653 dispatchEventLocked(currentTime, entry, inputTargets);
1654 return true;
1655}
1656
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001658 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1659 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1660 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1661 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1662 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1663 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1664 entry.metaState, entry.repeatCount, entry.downTime);
1665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666}
1667
Prabir Pradhancef936d2021-07-21 16:17:52 +00001668void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1669 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001670 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001671 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1672 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1673 "source=0x%x, sensorType=%s",
1674 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001675 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001676 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001677 auto command = [this, entry]() REQUIRES(mLock) {
1678 scoped_unlock unlock(mLock);
1679
1680 if (entry->accuracyChanged) {
1681 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1682 }
1683 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1684 entry->hwTimestamp, entry->values);
1685 };
1686 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001687}
1688
1689bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001690 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1691 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001692 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001693 }
Chris Yef59a2f42020-10-16 12:55:26 -07001694 { // acquire lock
1695 std::scoped_lock _l(mLock);
1696
1697 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1698 std::shared_ptr<EventEntry> entry = *it;
1699 if (entry->type == EventEntry::Type::SENSOR) {
1700 it = mInboundQueue.erase(it);
1701 releaseInboundEventLocked(entry);
1702 }
1703 }
1704 }
1705 return true;
1706}
1707
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001708bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001710 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 entry->dispatchInProgress = true;
1714
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001715 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717
1718 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001719 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001720 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001721 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1722 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 return true;
1724 }
1725
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001726 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727
1728 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001729 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730
1731 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001732 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 if (isPointerEvent) {
1734 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001735 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001737 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 } else {
1739 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001741 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001743 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 return false;
1745 }
1746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001747 setInjectionResult(*entry, injectionResult);
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001748 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001749 return true;
1750 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001751 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001752 CancelationOptions::Mode mode(isPointerEvent
1753 ? CancelationOptions::CANCEL_POINTER_EVENTS
1754 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1755 CancelationOptions options(mode, "input event injection failed");
1756 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 return true;
1758 }
1759
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001760 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001761 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762
1763 // Dispatch the motion.
1764 if (conflictingPointerActions) {
1765 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001766 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 synthesizeCancelationEventsForAllConnectionsLocked(options);
1768 }
1769 dispatchEventLocked(currentTime, entry, inputTargets);
1770 return true;
1771}
1772
chaviw98318de2021-05-19 16:45:23 -05001773void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001774 bool isExiting, const int32_t rawX,
1775 const int32_t rawY) {
1776 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001777 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001778 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1779 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001780
1781 enqueueInboundEventLocked(std::move(dragEntry));
1782}
1783
1784void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1785 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1786 if (channel == nullptr) {
1787 return; // Window has gone away
1788 }
1789 InputTarget target;
1790 target.inputChannel = channel;
1791 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1792 entry->dispatchInProgress = true;
1793 dispatchEventLocked(currentTime, entry, {target});
1794}
1795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001797 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1798 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1799 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001800 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001801 "metaState=0x%x, buttonState=0x%x,"
1802 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1803 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001804 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1805 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1806 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001808 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1809 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1810 "x=%f, y=%f, pressure=%f, size=%f, "
1811 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1812 "orientation=%f",
1813 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1814 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1815 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1816 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1817 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1818 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1819 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1820 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1821 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1822 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825}
1826
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001827void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1828 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001829 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001830 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001831 if (DEBUG_DISPATCH_CYCLE) {
1832 ALOGD("dispatchEventToCurrentInputTargets");
1833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001835 updateInteractionTokensLocked(*eventEntry, inputTargets);
1836
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1838
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001839 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001841 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001842 sp<Connection> connection =
1843 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001844 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001845 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001847 if (DEBUG_FOCUS) {
1848 ALOGD("Dropping event delivery to target with channel '%s' because it "
1849 "is no longer registered with the input dispatcher.",
1850 inputTarget.inputChannel->getName().c_str());
1851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 }
1853 }
1854}
1855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001856void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1857 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1858 // If the policy decides to close the app, we will get a channel removal event via
1859 // unregisterInputChannel, and will clean up the connection that way. We are already not
1860 // sending new pointers to the connection when it blocked, but focused events will continue to
1861 // pile up.
1862 ALOGW("Canceling events for %s because it is unresponsive",
1863 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001864 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001865 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1866 "application not responding");
1867 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
1869}
1870
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001871void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001872 if (DEBUG_FOCUS) {
1873 ALOGD("Resetting ANR timeouts.");
1874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875
1876 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001877 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001878 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879}
1880
Tiger Huang721e26f2018-07-24 22:26:19 +08001881/**
1882 * Get the display id that the given event should go to. If this event specifies a valid display id,
1883 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1884 * Focused display is the display that the user most recently interacted with.
1885 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001886int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001887 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001888 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001889 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001890 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1891 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001892 break;
1893 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001894 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001895 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1896 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001897 break;
1898 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001899 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001900 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001901 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001902 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001903 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001904 case EventEntry::Type::SENSOR:
1905 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001906 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001907 return ADISPLAY_ID_NONE;
1908 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001909 }
1910 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1911}
1912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1914 const char* focusedWindowName) {
1915 if (mAnrTracker.empty()) {
1916 // already processed all events that we waited for
1917 mKeyIsWaitingForEventsTimeout = std::nullopt;
1918 return false;
1919 }
1920
1921 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1922 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001923 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001924 mKeyIsWaitingForEventsTimeout = currentTime +
1925 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1926 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 return true;
1928 }
1929
1930 // We still have pending events, and already started the timer
1931 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1932 return true; // Still waiting
1933 }
1934
1935 // Waited too long, and some connection still hasn't processed all motions
1936 // Just send the key to the focused window
1937 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1938 focusedWindowName);
1939 mKeyIsWaitingForEventsTimeout = std::nullopt;
1940 return false;
1941}
1942
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1944 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1945 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001946 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947
Tiger Huang721e26f2018-07-24 22:26:19 +08001948 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001949 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001950 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001951 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1952
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 // If there is no currently focused window and no focused application
1954 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1956 ALOGI("Dropping %s event because there is no focused window or focused application in "
1957 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001958 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
1961
Vishnu Nair062a8672021-09-03 16:07:44 -07001962 // Drop key events if requested by input feature
1963 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1964 return InputEventInjectionResult::FAILED;
1965 }
1966
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1968 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1969 // start interacting with another application via touch (app switch). This code can be removed
1970 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1971 // an app is expected to have a focused window.
1972 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1973 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1974 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001975 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1976 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1977 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001978 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001979 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001980 ALOGW("Waiting because no window has focus but %s may eventually add a "
1981 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001982 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001983 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001984 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1986 // Already raised ANR. Drop the event
1987 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001988 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001990 } else {
1991 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001992 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001993 }
1994 }
1995
1996 // we have a valid, non-null focused window
1997 resetNoFocusedWindowTimeoutLocked();
1998
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001999 // Verify targeted injection.
2000 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2001 ALOGW("Dropping injected event: %s", (*err).c_str());
2002 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 }
2004
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002005 if (focusedWindowHandle->getInfo()->inputConfig.test(
2006 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002008 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002009 }
2010
2011 // If the event is a key event, then we must wait for all previous events to
2012 // complete before delivering it because previous events may have the
2013 // side-effect of transferring focus to a different window and we want to
2014 // ensure that the following keys are sent to the new window.
2015 //
2016 // Suppose the user touches a button in a window then immediately presses "A".
2017 // If the button causes a pop-up window to appear then we want to ensure that
2018 // the "A" key is delivered to the new pop-up window. This is because users
2019 // often anticipate pending UI changes when typing on a keyboard.
2020 // To obtain this behavior, we must serialize key events with respect to all
2021 // prior input events.
2022 if (entry.type == EventEntry::Type::KEY) {
2023 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2024 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002025 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 }
2028
2029 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08002030 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002031 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
2032 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033
2034 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036}
2037
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038/**
2039 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2040 * that are currently unresponsive.
2041 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002042std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2043 const std::vector<Monitor>& monitors) const {
2044 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002045 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002046 [this](const Monitor& monitor) REQUIRES(mLock) {
2047 sp<Connection> connection =
2048 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 if (connection == nullptr) {
2050 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002051 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 return false;
2053 }
2054 if (!connection->responsive) {
2055 ALOGW("Unresponsive monitor %s will not get the new gesture",
2056 connection->inputChannel->getName().c_str());
2057 return false;
2058 }
2059 return true;
2060 });
2061 return responsiveMonitors;
2062}
2063
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002064InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2065 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2066 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002067 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 // For security reasons, we defer updating the touch state until we are sure that
2070 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002071 const int32_t displayId = entry.displayId;
2072 const int32_t action = entry.action;
2073 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
2075 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002077 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2078 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002080 // Copy current touch state into tempTouchState.
2081 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2082 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002083 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002084 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002085 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2086 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002087 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002088 }
2089
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002090 bool isSplit = tempTouchState.split;
2091 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2092 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2093 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002094
2095 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2096 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2097 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2098 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2099 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002100 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 bool wrongDevice = false;
2102 if (newGesture) {
2103 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002104 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002105 ALOGI("Dropping event because a pointer for a different device is already down "
2106 "in display %" PRId32,
2107 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002108 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002109 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 switchedDevice = false;
2111 wrongDevice = true;
2112 goto Failed;
2113 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002114 tempTouchState.reset();
2115 tempTouchState.down = down;
2116 tempTouchState.deviceId = entry.deviceId;
2117 tempTouchState.source = entry.source;
2118 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002120 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002121 ALOGI("Dropping move event because a pointer for a different device is already active "
2122 "in display %" PRId32,
2123 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002124 // TODO: test multiple simultaneous input streams.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002125 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002126 switchedDevice = false;
2127 wrongDevice = true;
2128 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130
2131 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2132 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2133
Garfield Tan00f511d2019-06-12 16:55:40 -07002134 int32_t x;
2135 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002136 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002137 // Always dispatch mouse events to cursor position.
2138 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002139 x = int32_t(entry.xCursorPosition);
2140 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002141 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002142 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2143 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002144 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002145 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002146 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002147 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002148 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002149
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002151 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002152 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2153 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002156 }
2157
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002158 // Verify targeted injection.
2159 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2160 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2161 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2162 newTouchedWindowHandle = nullptr;
2163 goto Failed;
2164 }
2165
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002167 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002168 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2169 // New window supports splitting, but we should never split mouse events.
2170 isSplit = !isFromMouse;
2171 } else if (isSplit) {
2172 // New window does not support splitting but we have already split events.
2173 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 newTouchedWindowHandle = nullptr;
2175 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002176 } else {
2177 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002178 // be delivered to a new window which supports split touch. Pointers from a mouse device
2179 // should never be split.
2180 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181 }
2182
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002184 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002185 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2186 newHoverWindowHandle = nullptr;
2187 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002188 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002189 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002190 }
2191
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002192 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002193 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002194 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002195 // Process the foreground window first so that it is the first to receive the event.
2196 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002197 }
2198
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002199 if (newTouchedWindows.empty()) {
2200 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2201 x, y, displayId);
2202 injectionResult = InputEventInjectionResult::FAILED;
2203 goto Failed;
2204 }
2205
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002206 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2207 const WindowInfo& info = *windowHandle->getInfo();
2208
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002209 // Skip spy window targets that are not valid for targeted injection.
2210 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2211 continue;
2212 }
2213
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002214 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002215 ALOGI("Not sending touch event to %s because it is paused",
2216 windowHandle->getName().c_str());
2217 continue;
2218 }
2219
2220 // Ensure the window has a connection and the connection is responsive
2221 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2222 if (!isResponsive) {
2223 ALOGW("Not sending touch gesture to %s because it is not responsive",
2224 windowHandle->getName().c_str());
2225 continue;
2226 }
2227
2228 // Drop events that can't be trusted due to occlusion
2229 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2230 TouchOcclusionInfo occlusionInfo =
2231 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2232 if (!isTouchTrustedLocked(occlusionInfo)) {
2233 if (DEBUG_TOUCH_OCCLUSION) {
2234 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2235 for (const auto& log : occlusionInfo.debugInfo) {
2236 ALOGD("%s", log.c_str());
2237 }
2238 }
2239 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2240 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2241 ALOGW("Dropping untrusted touch event due to %s/%d",
2242 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2243 continue;
2244 }
2245 }
2246 }
2247
2248 // Drop touch events if requested by input feature
2249 if (shouldDropInput(entry, windowHandle)) {
2250 continue;
2251 }
2252
2253 // Set target flags.
2254 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2255
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002256 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2257 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002258 targetFlags |= InputTarget::FLAG_FOREGROUND;
2259 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260
2261 if (isSplit) {
2262 targetFlags |= InputTarget::FLAG_SPLIT;
2263 }
2264 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2265 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2266 } else if (isWindowObscuredLocked(windowHandle)) {
2267 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2268 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002269
2270 // Update the temporary touch state.
2271 BitSet32 pointerIds;
2272 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002273 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002274 pointerIds.markBit(pointerId);
2275 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002276
2277 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 } else {
2280 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2281
2282 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002284 if (DEBUG_FOCUS) {
2285 ALOGD("Dropping event because the pointer is not down or we previously "
2286 "dropped the pointer down event in display %" PRId32,
2287 displayId);
2288 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002289 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 goto Failed;
2291 }
2292
arthurhung6d4bed92021-03-17 11:59:33 +08002293 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002294
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002296 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002297 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002298 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2299 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
Prabir Pradhand65552b2021-10-07 11:23:50 -07002301 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002302 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002304 newTouchedWindowHandle =
2305 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002306
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002307 // Verify targeted injection.
2308 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2309 ALOGW("Dropping injected event: %s", (*err).c_str());
2310 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2311 newTouchedWindowHandle = nullptr;
2312 goto Failed;
2313 }
2314
Vishnu Nair062a8672021-09-03 16:07:44 -07002315 // Drop touch events if requested by input feature
2316 if (newTouchedWindowHandle != nullptr &&
2317 shouldDropInput(entry, newTouchedWindowHandle)) {
2318 newTouchedWindowHandle = nullptr;
2319 }
2320
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002321 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2322 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002323 if (DEBUG_FOCUS) {
2324 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2325 oldTouchedWindowHandle->getName().c_str(),
2326 newTouchedWindowHandle->getName().c_str(), displayId);
2327 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002329 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2330 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2331 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
2333 // Make a slippery entrance into the new window.
2334 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002335 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
2337
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002338 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2339 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2340 targetFlags |= InputTarget::FLAG_FOREGROUND;
2341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 if (isSplit) {
2343 targetFlags |= InputTarget::FLAG_SPLIT;
2344 }
2345 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2346 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002347 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2348 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 }
2350
2351 BitSet32 pointerIds;
2352 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002353 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002355 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357 }
2358 }
2359
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002360 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002362 // Let the previous window know that the hover sequence is over, unless we already did
2363 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002364 if (mLastHoverWindowHandle != nullptr &&
2365 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2366 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002367 if (DEBUG_HOVER) {
2368 ALOGD("Sending hover exit event to window %s.",
2369 mLastHoverWindowHandle->getName().c_str());
2370 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002371 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2372 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374
Garfield Tandf26e862020-07-01 20:18:19 -07002375 // Let the new window know that the hover sequence is starting, unless we already did it
2376 // when dispatching it as is to newTouchedWindowHandle.
2377 if (newHoverWindowHandle != nullptr &&
2378 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2379 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002380 if (DEBUG_HOVER) {
2381 ALOGD("Sending hover enter event to window %s.",
2382 newHoverWindowHandle->getName().c_str());
2383 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002384 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2385 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2386 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
2388 }
2389
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002390 // Ensure that we have at least one foreground window or at least one window that cannot be a
2391 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2392 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2393 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002394 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2395 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002396 return !canReceiveForegroundTouches(
2397 *touchedWindow.windowHandle->getInfo()) ||
2398 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002399 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002400 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2401 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002402 injectionResult = InputEventInjectionResult::FAILED;
2403 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002406 // Ensure that all touched windows are valid for injection.
2407 if (entry.injectionState != nullptr) {
2408 std::string errs;
2409 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2410 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2411 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2412 // dispatched to any uid, since the coords will be zeroed out later.
2413 continue;
2414 }
2415 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2416 if (err) errs += "\n - " + *err;
2417 }
2418 if (!errs.empty()) {
2419 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2420 "%d:%s",
2421 *entry.injectionState->targetUid, errs.c_str());
2422 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2423 goto Failed;
2424 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002425 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002426
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 // Check whether windows listening for outside touches are owned by the same UID. If it is
2428 // set the policy flag that we will not reveal coordinate information to this window.
2429 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002430 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002431 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002432 if (foregroundWindowHandle) {
2433 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002434 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002435 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002436 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2437 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2438 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002439 InputTarget::FLAG_ZERO_COORDS,
2440 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
2443 }
2444 }
2445 }
2446
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 // If this is the first pointer going down and the touched window has a wallpaper
2448 // then also add the touched wallpaper windows so they are locked in for the duration
2449 // of the touch gesture.
2450 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2451 // engine only supports touch events. We would need to add a mechanism similar
2452 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2453 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002454 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002455 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002456 if (foregroundWindowHandle &&
2457 foregroundWindowHandle->getInfo()->inputConfig.test(
2458 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002459 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002460 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002461 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2462 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002464 windowHandle->getInfo()->inputConfig.test(
2465 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002466 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 .addOrUpdateWindow(windowHandle,
2468 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2469 InputTarget::
2470 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2471 InputTarget::FLAG_DISPATCH_AS_IS,
2472 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 }
2474 }
2475 }
2476 }
2477
2478 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002479 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002481 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
2485
2486 // Drop the outside or hover touch windows since we will not care about them
2487 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002488 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489
2490Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002492 if (!wrongDevice) {
2493 if (switchedDevice) {
2494 if (DEBUG_FOCUS) {
2495 ALOGD("Conflicting pointer actions: Switched to a different device.");
2496 }
2497 *outConflictingPointerActions = true;
2498 }
2499
2500 if (isHoverAction) {
2501 // Started hovering, therefore no longer down.
2502 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002503 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002504 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2505 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 *outConflictingPointerActions = true;
2508 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002509 tempTouchState.reset();
2510 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2511 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2512 tempTouchState.deviceId = entry.deviceId;
2513 tempTouchState.source = entry.source;
2514 tempTouchState.displayId = displayId;
2515 }
2516 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2517 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2518 // All pointers up or canceled.
2519 tempTouchState.reset();
2520 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2521 // First pointer went down.
2522 if (oldState && oldState->down) {
2523 if (DEBUG_FOCUS) {
2524 ALOGD("Conflicting pointer actions: Down received while already down.");
2525 }
2526 *outConflictingPointerActions = true;
2527 }
2528 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2529 // One pointer went up.
2530 if (isSplit) {
2531 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2532 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002534 for (size_t i = 0; i < tempTouchState.windows.size();) {
2535 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2536 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2537 touchedWindow.pointerIds.clearBit(pointerId);
2538 if (touchedWindow.pointerIds.isEmpty()) {
2539 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2540 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002543 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002545 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002546 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002547
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002548 // Save changes unless the action was scroll in which case the temporary touch
2549 // state was only valid for this one action.
2550 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2551 if (tempTouchState.displayId >= 0) {
2552 mTouchStatesByDisplay[displayId] = tempTouchState;
2553 } else {
2554 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002558 // Update hover state.
2559 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 }
2561
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 return injectionResult;
2563}
2564
arthurhung6d4bed92021-03-17 11:59:33 +08002565void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002566 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2567 // have an explicit reason to support it.
2568 constexpr bool isStylus = false;
2569
chaviw98318de2021-05-19 16:45:23 -05002570 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002571 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002572 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002573 if (dropWindow) {
2574 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002575 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002576 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002577 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002578 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002579 }
2580 mDragState.reset();
2581}
2582
2583void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung54745652022-04-20 07:17:41 +00002584 if (!mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002585 return;
2586 }
2587
arthurhung6d4bed92021-03-17 11:59:33 +08002588 if (!mDragState->isStartDrag) {
2589 mDragState->isStartDrag = true;
2590 mDragState->isStylusButtonDownAtStart =
2591 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2592 }
2593
Arthur Hung54745652022-04-20 07:17:41 +00002594 // Find the pointer index by id.
2595 int32_t pointerIndex = 0;
2596 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2597 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2598 if (pointerProperties.id == mDragState->pointerId) {
2599 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002600 }
Arthur Hung54745652022-04-20 07:17:41 +00002601 }
arthurhung6d4bed92021-03-17 11:59:33 +08002602
Arthur Hung54745652022-04-20 07:17:41 +00002603 if (uint32_t(pointerIndex) == entry.pointerCount) {
2604 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002605 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002606 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002607 return;
2608 }
2609
2610 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2611 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2612 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2613
2614 switch (maskedAction) {
2615 case AMOTION_EVENT_ACTION_MOVE: {
2616 // Handle the special case : stylus button no longer pressed.
2617 bool isStylusButtonDown =
2618 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2619 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2620 finishDragAndDrop(entry.displayId, x, y);
2621 return;
2622 }
2623
2624 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2625 // until we have an explicit reason to support it.
2626 constexpr bool isStylus = false;
2627
2628 const sp<WindowInfoHandle> hoverWindowHandle =
2629 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2630 isStylus, false /*addOutsideTargets*/,
2631 true /*ignoreDragWindow*/);
2632 // enqueue drag exit if needed.
2633 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2634 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2635 if (mDragState->dragHoverWindowHandle != nullptr) {
2636 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2637 y);
2638 }
2639 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2640 }
2641 // enqueue drag location if needed.
2642 if (hoverWindowHandle != nullptr) {
2643 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2644 }
2645 break;
2646 }
2647
2648 case AMOTION_EVENT_ACTION_POINTER_UP:
2649 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2650 break;
2651 }
2652 // The drag pointer is up.
2653 [[fallthrough]];
2654 case AMOTION_EVENT_ACTION_UP:
2655 finishDragAndDrop(entry.displayId, x, y);
2656 break;
2657 case AMOTION_EVENT_ACTION_CANCEL: {
2658 ALOGD("Receiving cancel when drag and drop.");
2659 sendDropWindowCommandLocked(nullptr, 0, 0);
2660 mDragState.reset();
2661 break;
2662 }
arthurhungb89ccb02020-12-30 16:19:01 +08002663 }
2664}
2665
chaviw98318de2021-05-19 16:45:23 -05002666void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002667 int32_t targetFlags, BitSet32 pointerIds,
2668 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002669 std::vector<InputTarget>::iterator it =
2670 std::find_if(inputTargets.begin(), inputTargets.end(),
2671 [&windowHandle](const InputTarget& inputTarget) {
2672 return inputTarget.inputChannel->getConnectionToken() ==
2673 windowHandle->getToken();
2674 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002675
chaviw98318de2021-05-19 16:45:23 -05002676 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002677
2678 if (it == inputTargets.end()) {
2679 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002680 std::shared_ptr<InputChannel> inputChannel =
2681 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002682 if (inputChannel == nullptr) {
2683 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2684 return;
2685 }
2686 inputTarget.inputChannel = inputChannel;
2687 inputTarget.flags = targetFlags;
2688 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002689 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2690 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002691 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002692 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002693 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002694 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002695 inputTargets.push_back(inputTarget);
2696 it = inputTargets.end() - 1;
2697 }
2698
2699 ALOG_ASSERT(it->flags == targetFlags);
2700 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2701
chaviw1ff3d1e2020-07-01 15:53:47 -07002702 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703}
2704
Michael Wright3dd60e22019-03-27 22:06:44 +00002705void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002706 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002707 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2708 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002709
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002710 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2711 InputTarget target;
2712 target.inputChannel = monitor.inputChannel;
2713 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2714 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2715 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002716 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002717 target.setDefaultPointerTransform(target.displayTransform);
2718 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 }
2720}
2721
Robert Carrc9bf1d32020-04-13 17:21:08 -07002722/**
2723 * Indicate whether one window handle should be considered as obscuring
2724 * another window handle. We only check a few preconditions. Actually
2725 * checking the bounds is left to the caller.
2726 */
chaviw98318de2021-05-19 16:45:23 -05002727static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2728 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002729 // Compare by token so cloned layers aren't counted
2730 if (haveSameToken(windowHandle, otherHandle)) {
2731 return false;
2732 }
2733 auto info = windowHandle->getInfo();
2734 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002735 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002736 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002737 } else if (otherInfo->alpha == 0 &&
2738 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002739 // Those act as if they were invisible, so we don't need to flag them.
2740 // We do want to potentially flag touchable windows even if they have 0
2741 // opacity, since they can consume touches and alter the effects of the
2742 // user interaction (eg. apps that rely on
2743 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2744 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2745 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002746 } else if (info->ownerUid == otherInfo->ownerUid) {
2747 // If ownerUid is the same we don't generate occlusion events as there
2748 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002749 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002750 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002751 return false;
2752 } else if (otherInfo->displayId != info->displayId) {
2753 return false;
2754 }
2755 return true;
2756}
2757
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002758/**
2759 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2760 * untrusted, one should check:
2761 *
2762 * 1. If result.hasBlockingOcclusion is true.
2763 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2764 * BLOCK_UNTRUSTED.
2765 *
2766 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2767 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2768 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2769 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2770 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2771 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2772 *
2773 * If neither of those is true, then it means the touch can be allowed.
2774 */
2775InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002776 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2777 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002778 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002779 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002780 TouchOcclusionInfo info;
2781 info.hasBlockingOcclusion = false;
2782 info.obscuringOpacity = 0;
2783 info.obscuringUid = -1;
2784 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002785 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002786 if (windowHandle == otherHandle) {
2787 break; // All future windows are below us. Exit early.
2788 }
chaviw98318de2021-05-19 16:45:23 -05002789 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002790 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2791 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002792 if (DEBUG_TOUCH_OCCLUSION) {
2793 info.debugInfo.push_back(
2794 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2795 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002796 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2797 // we perform the checks below to see if the touch can be propagated or not based on the
2798 // window's touch occlusion mode
2799 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2800 info.hasBlockingOcclusion = true;
2801 info.obscuringUid = otherInfo->ownerUid;
2802 info.obscuringPackage = otherInfo->packageName;
2803 break;
2804 }
2805 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2806 uint32_t uid = otherInfo->ownerUid;
2807 float opacity =
2808 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2809 // Given windows A and B:
2810 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2811 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2812 opacityByUid[uid] = opacity;
2813 if (opacity > info.obscuringOpacity) {
2814 info.obscuringOpacity = opacity;
2815 info.obscuringUid = uid;
2816 info.obscuringPackage = otherInfo->packageName;
2817 }
2818 }
2819 }
2820 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002821 if (DEBUG_TOUCH_OCCLUSION) {
2822 info.debugInfo.push_back(
2823 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2824 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002825 return info;
2826}
2827
chaviw98318de2021-05-19 16:45:23 -05002828std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002829 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002830 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2831 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2832 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2833 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002834 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2835 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2836 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2837 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2838 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002839 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002840 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002841}
2842
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002843bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2844 if (occlusionInfo.hasBlockingOcclusion) {
2845 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2846 occlusionInfo.obscuringUid);
2847 return false;
2848 }
2849 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2850 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2851 "%.2f, maximum allowed = %.2f)",
2852 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2853 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2854 return false;
2855 }
2856 return true;
2857}
2858
chaviw98318de2021-05-19 16:45:23 -05002859bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002862 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2863 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002864 if (windowHandle == otherHandle) {
2865 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
chaviw98318de2021-05-19 16:45:23 -05002867 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002868 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002869 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 return true;
2871 }
2872 }
2873 return false;
2874}
2875
chaviw98318de2021-05-19 16:45:23 -05002876bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002877 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002878 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2879 const WindowInfo* windowInfo = windowHandle->getInfo();
2880 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002881 if (windowHandle == otherHandle) {
2882 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002883 }
chaviw98318de2021-05-19 16:45:23 -05002884 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002885 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002886 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002887 return true;
2888 }
2889 }
2890 return false;
2891}
2892
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002893std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002894 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002895 if (applicationHandle != nullptr) {
2896 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002897 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 } else {
2899 return applicationHandle->getName();
2900 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002901 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002902 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002904 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 }
2906}
2907
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002908void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002909 if (!isUserActivityEvent(eventEntry)) {
2910 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002911 return;
2912 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002913 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002914 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002915 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002916 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002917 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002918 if (DEBUG_DISPATCH_CYCLE) {
2919 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 return;
2922 }
2923 }
2924
2925 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002927 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002928 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2929 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 return;
2931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 eventType = USER_ACTIVITY_EVENT_TOUCH;
2935 }
2936 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002938 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002939 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2940 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 return;
2942 }
2943 eventType = USER_ACTIVITY_EVENT_BUTTON;
2944 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002946 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002947 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002948 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002949 break;
2950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 }
2952
Prabir Pradhancef936d2021-07-21 16:17:52 +00002953 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2954 REQUIRES(mLock) {
2955 scoped_unlock unlock(mLock);
2956 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2957 };
2958 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959}
2960
2961void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002963 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002964 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002965 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002967 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002968 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002969 ATRACE_NAME(message.c_str());
2970 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002971 if (DEBUG_DISPATCH_CYCLE) {
2972 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2973 "globalScaleFactor=%f, pointerIds=0x%x %s",
2974 connection->getInputChannelName().c_str(), inputTarget.flags,
2975 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2976 inputTarget.getPointerInfoString().c_str());
2977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978
2979 // Skip this event if the connection status is not normal.
2980 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002981 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002982 if (DEBUG_DISPATCH_CYCLE) {
2983 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002984 connection->getInputChannelName().c_str(),
2985 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987 return;
2988 }
2989
2990 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2992 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2993 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002994 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002996 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002997 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002998 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002999 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 if (!splitMotionEntry) {
3001 return; // split event was dropped
3002 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003003 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3004 std::string reason = std::string("reason=pointer cancel on split window");
3005 android_log_event_list(LOGTAG_INPUT_CANCEL)
3006 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3007 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003008 if (DEBUG_FOCUS) {
3009 ALOGD("channel '%s' ~ Split motion event.",
3010 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003011 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003012 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003013 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3014 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 return;
3016 }
3017 }
3018
3019 // Not splitting. Enqueue dispatch entries for the event as is.
3020 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3021}
3022
3023void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003025 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003026 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003027 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003029 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003030 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003031 ATRACE_NAME(message.c_str());
3032 }
3033
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003034 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035
3036 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003037 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003039 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003041 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003043 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003045 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003047 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049
3050 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003051 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 startDispatchCycleLocked(currentTime, connection);
3053 }
3054}
3055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003056void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003057 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003058 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003059 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003060 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3062 connection->getInputChannelName().c_str(),
3063 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003064 ATRACE_NAME(message.c_str());
3065 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003066 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 if (!(inputTargetFlags & dispatchMode)) {
3068 return;
3069 }
3070 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3071
3072 // This is a new event.
3073 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003074 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003075 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003077 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3078 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003079 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003081 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003082 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003083 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003084 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003085 dispatchEntry->resolvedAction = keyEntry.action;
3086 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3089 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003090 if (DEBUG_DISPATCH_CYCLE) {
3091 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3092 "event",
3093 connection->getInputChannelName().c_str());
3094 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 return; // skip the inconsistent event
3096 }
3097 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003100 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003101 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003102 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3103 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3104 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3105 static_cast<int32_t>(IdGenerator::Source::OTHER);
3106 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3108 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3109 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3110 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3111 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3112 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3113 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3114 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3115 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3116 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3117 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003119 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 }
3121 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3123 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003124 if (DEBUG_DISPATCH_CYCLE) {
3125 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3126 "enter event",
3127 connection->getInputChannelName().c_str());
3128 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003129 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3130 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003131 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3136 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3137 }
3138 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3139 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3143 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003144 if (DEBUG_DISPATCH_CYCLE) {
3145 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3146 "event",
3147 connection->getInputChannelName().c_str());
3148 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 return; // skip the inconsistent event
3150 }
3151
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003152 dispatchEntry->resolvedEventId =
3153 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3154 ? mIdGenerator.nextId()
3155 : motionEntry.id;
3156 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3157 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3158 ") to MotionEvent(id=0x%" PRIx32 ").",
3159 motionEntry.id, dispatchEntry->resolvedEventId);
3160 ATRACE_NAME(message.c_str());
3161 }
3162
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003163 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3164 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3165 // Skip reporting pointer down outside focus to the policy.
3166 break;
3167 }
3168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003169 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003170 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171
3172 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003174 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003175 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003176 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3177 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003178 break;
3179 }
Chris Yef59a2f42020-10-16 12:55:26 -07003180 case EventEntry::Type::SENSOR: {
3181 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3182 break;
3183 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003184 case EventEntry::Type::CONFIGURATION_CHANGED:
3185 case EventEntry::Type::DEVICE_RESET: {
3186 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003187 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003188 break;
3189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 }
3191
3192 // Remember that we are waiting for this dispatch to complete.
3193 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003194 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 }
3196
3197 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003198 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003199 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003200}
3201
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003202/**
3203 * This function is purely for debugging. It helps us understand where the user interaction
3204 * was taking place. For example, if user is touching launcher, we will see a log that user
3205 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3206 * We will see both launcher and wallpaper in that list.
3207 * Once the interaction with a particular set of connections starts, no new logs will be printed
3208 * until the set of interacted connections changes.
3209 *
3210 * The following items are skipped, to reduce the logspam:
3211 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3212 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3213 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3214 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3215 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003216 */
3217void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3218 const std::vector<InputTarget>& targets) {
3219 // Skip ACTION_UP events, and all events other than keys and motions
3220 if (entry.type == EventEntry::Type::KEY) {
3221 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3222 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3223 return;
3224 }
3225 } else if (entry.type == EventEntry::Type::MOTION) {
3226 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3227 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3228 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3229 return;
3230 }
3231 } else {
3232 return; // Not a key or a motion
3233 }
3234
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003235 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003236 std::vector<sp<Connection>> newConnections;
3237 for (const InputTarget& target : targets) {
3238 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3239 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3240 continue; // Skip windows that receive ACTION_OUTSIDE
3241 }
3242
3243 sp<IBinder> token = target.inputChannel->getConnectionToken();
3244 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003245 if (connection == nullptr) {
3246 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003247 }
3248 newConnectionTokens.insert(std::move(token));
3249 newConnections.emplace_back(connection);
3250 }
3251 if (newConnectionTokens == mInteractionConnectionTokens) {
3252 return; // no change
3253 }
3254 mInteractionConnectionTokens = newConnectionTokens;
3255
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003256 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003257 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003258 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003259 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003260 std::string message = "Interaction with: " + targetList;
3261 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003262 message += "<none>";
3263 }
3264 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3265}
3266
chaviwfd6d3512019-03-25 13:23:49 -07003267void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003268 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003269 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003270 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3271 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003272 return;
3273 }
3274
Vishnu Nairc519ff72021-01-21 08:23:08 -08003275 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003276 if (focusedToken == token) {
3277 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003278 return;
3279 }
3280
Prabir Pradhancef936d2021-07-21 16:17:52 +00003281 auto command = [this, token]() REQUIRES(mLock) {
3282 scoped_unlock unlock(mLock);
3283 mPolicy->onPointerDownOutsideFocus(token);
3284 };
3285 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286}
3287
3288void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003290 if (ATRACE_ENABLED()) {
3291 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003293 ATRACE_NAME(message.c_str());
3294 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003295 if (DEBUG_DISPATCH_CYCLE) {
3296 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003299 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003300 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003302 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003303 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304
3305 // Publish the event.
3306 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3308 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003309 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003310 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3311 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 status = connection->inputPublisher
3315 .publishKeyEvent(dispatchEntry->seq,
3316 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3317 keyEntry.source, keyEntry.displayId,
3318 std::move(hmac), dispatchEntry->resolvedAction,
3319 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3320 keyEntry.scanCode, keyEntry.metaState,
3321 keyEntry.repeatCount, keyEntry.downTime,
3322 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
3325
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003326 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003327 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003330 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331
chaviw82357092020-01-28 13:13:06 -08003332 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3335 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003336 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003337 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3338 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003339 // Don't apply window scale here since we don't want scale to affect raw
3340 // coordinates. The scale will be sent back to the client and applied
3341 // later when requesting relative coordinates.
3342 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3343 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 }
3345 usingCoords = scaledCoords;
3346 }
3347 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003348 // We don't want the dispatch target to know.
3349 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003350 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 scaledCoords[i].clear();
3352 }
3353 usingCoords = scaledCoords;
3354 }
3355 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003357 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358
3359 // Publish the motion event.
3360 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003361 .publishMotionEvent(dispatchEntry->seq,
3362 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003363 motionEntry.deviceId, motionEntry.source,
3364 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003365 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003366 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003368 motionEntry.edgeFlags, motionEntry.metaState,
3369 motionEntry.buttonState,
3370 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003371 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003372 motionEntry.xPrecision, motionEntry.yPrecision,
3373 motionEntry.xCursorPosition,
3374 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003375 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003376 motionEntry.downTime, motionEntry.eventTime,
3377 motionEntry.pointerCount,
3378 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 break;
3380 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003381
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003382 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003383 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003384 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003385 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003386 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003387 break;
3388 }
3389
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003390 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3391 const TouchModeEntry& touchModeEntry =
3392 static_cast<const TouchModeEntry&>(eventEntry);
3393 status = connection->inputPublisher
3394 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3395 touchModeEntry.inTouchMode);
3396
3397 break;
3398 }
3399
Prabir Pradhan99987712020-11-10 18:43:05 -08003400 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3401 const auto& captureEntry =
3402 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3403 status = connection->inputPublisher
3404 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003405 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003406 break;
3407 }
3408
arthurhungb89ccb02020-12-30 16:19:01 +08003409 case EventEntry::Type::DRAG: {
3410 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3411 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3412 dragEntry.id, dragEntry.x,
3413 dragEntry.y,
3414 dragEntry.isExiting);
3415 break;
3416 }
3417
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003418 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003419 case EventEntry::Type::DEVICE_RESET:
3420 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003421 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003422 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426
3427 // Check the result.
3428 if (status) {
3429 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003430 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003432 "This is unexpected because the wait queue is empty, so the pipe "
3433 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003434 "event to it, status=%s(%d)",
3435 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3436 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3438 } else {
3439 // Pipe is full and we are waiting for the app to finish process some events
3440 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003441 if (DEBUG_DISPATCH_CYCLE) {
3442 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3443 "waiting for the application to catch up",
3444 connection->getInputChannelName().c_str());
3445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 }
3447 } else {
3448 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003449 "status=%s(%d)",
3450 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3451 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3453 }
3454 return;
3455 }
3456
3457 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003458 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3459 connection->outboundQueue.end(),
3460 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003461 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003462 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003463 if (connection->responsive) {
3464 mAnrTracker.insert(dispatchEntry->timeoutTime,
3465 connection->inputChannel->getConnectionToken());
3466 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003467 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
3469}
3470
chaviw09c8d2d2020-08-24 15:48:26 -07003471std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3472 size_t size;
3473 switch (event.type) {
3474 case VerifiedInputEvent::Type::KEY: {
3475 size = sizeof(VerifiedKeyEvent);
3476 break;
3477 }
3478 case VerifiedInputEvent::Type::MOTION: {
3479 size = sizeof(VerifiedMotionEvent);
3480 break;
3481 }
3482 }
3483 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3484 return mHmacKeyManager.sign(start, size);
3485}
3486
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003487const std::array<uint8_t, 32> InputDispatcher::getSignature(
3488 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003489 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3490 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003491 // Only sign events up and down events as the purely move events
3492 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003493 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003494 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003495
3496 VerifiedMotionEvent verifiedEvent =
3497 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3498 verifiedEvent.actionMasked = actionMasked;
3499 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3500 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003501}
3502
3503const std::array<uint8_t, 32> InputDispatcher::getSignature(
3504 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3505 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3506 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3507 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003508 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003509}
3510
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003513 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003514 if (DEBUG_DISPATCH_CYCLE) {
3515 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3516 connection->getInputChannelName().c_str(), seq, toString(handled));
3517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003519 if (connection->status == Connection::Status::BROKEN ||
3520 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 return;
3522 }
3523
3524 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003525 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3526 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3527 };
3528 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529}
3530
3531void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003532 const sp<Connection>& connection,
3533 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003534 if (DEBUG_DISPATCH_CYCLE) {
3535 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3536 connection->getInputChannelName().c_str(), toString(notify));
3537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538
3539 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003540 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003541 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003542 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003543 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544
3545 // The connection appears to be unrecoverably broken.
3546 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003547 if (connection->status == Connection::Status::NORMAL) {
3548 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549
3550 if (notify) {
3551 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003552 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3553 connection->getInputChannelName().c_str());
3554
3555 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003556 scoped_unlock unlock(mLock);
3557 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3558 };
3559 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561 }
3562}
3563
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003564void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3565 while (!queue.empty()) {
3566 DispatchEntry* dispatchEntry = queue.front();
3567 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003568 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 }
3570}
3571
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003572void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003574 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576 delete dispatchEntry;
3577}
3578
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003579int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3580 std::scoped_lock _l(mLock);
3581 sp<Connection> connection = getConnectionLocked(connectionToken);
3582 if (connection == nullptr) {
3583 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3584 connectionToken.get(), events);
3585 return 0; // remove the callback
3586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003588 bool notify;
3589 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3590 if (!(events & ALOOPER_EVENT_INPUT)) {
3591 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3592 "events=0x%x",
3593 connection->getInputChannelName().c_str(), events);
3594 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003597 nsecs_t currentTime = now();
3598 bool gotOne = false;
3599 status_t status = OK;
3600 for (;;) {
3601 Result<InputPublisher::ConsumerResponse> result =
3602 connection->inputPublisher.receiveConsumerResponse();
3603 if (!result.ok()) {
3604 status = result.error().code();
3605 break;
3606 }
3607
3608 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3609 const InputPublisher::Finished& finish =
3610 std::get<InputPublisher::Finished>(*result);
3611 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3612 finish.consumeTime);
3613 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003614 if (shouldReportMetricsForConnection(*connection)) {
3615 const InputPublisher::Timeline& timeline =
3616 std::get<InputPublisher::Timeline>(*result);
3617 mLatencyTracker
3618 .trackGraphicsLatency(timeline.inputEventId,
3619 connection->inputChannel->getConnectionToken(),
3620 std::move(timeline.graphicsTimeline));
3621 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003622 }
3623 gotOne = true;
3624 }
3625 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003626 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003627 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 return 1;
3629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 }
3631
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003632 notify = status != DEAD_OBJECT || !connection->monitor;
3633 if (notify) {
3634 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3635 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3636 status);
3637 }
3638 } else {
3639 // Monitor channels are never explicitly unregistered.
3640 // We do it automatically when the remote endpoint is closed so don't warn about them.
3641 const bool stillHaveWindowHandle =
3642 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3643 notify = !connection->monitor && stillHaveWindowHandle;
3644 if (notify) {
3645 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3646 connection->getInputChannelName().c_str(), events);
3647 }
3648 }
3649
3650 // Remove the channel.
3651 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3652 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653}
3654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003655void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003657 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003658 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
3660}
3661
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003662void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003663 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003664 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003665 for (const Monitor& monitor : monitors) {
3666 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003667 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003668 }
3669}
3670
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003672 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003673 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003674 if (connection == nullptr) {
3675 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003677
3678 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679}
3680
3681void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3682 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003683 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 return;
3685 }
3686
3687 nsecs_t currentTime = now();
3688
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003689 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003690 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003692 if (cancelationEvents.empty()) {
3693 return;
3694 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003695 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3696 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3697 "with reality: %s, mode=%d.",
3698 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3699 options.mode);
3700 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003701
Arthur Hungb3307ee2021-10-14 10:57:37 +00003702 std::string reason = std::string("reason=").append(options.reason);
3703 android_log_event_list(LOGTAG_INPUT_CANCEL)
3704 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3705
Svet Ganov5d3bc372020-01-26 23:11:07 -08003706 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003707 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003708 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3709 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003710 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003711 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712 target.globalScaleFactor = windowInfo->globalScaleFactor;
3713 }
3714 target.inputChannel = connection->inputChannel;
3715 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3716
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003717 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003718 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003719 switch (cancelationEventEntry->type) {
3720 case EventEntry::Type::KEY: {
3721 logOutboundKeyDetails("cancel - ",
3722 static_cast<const KeyEntry&>(*cancelationEventEntry));
3723 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003725 case EventEntry::Type::MOTION: {
3726 logOutboundMotionDetails("cancel - ",
3727 static_cast<const MotionEntry&>(*cancelationEventEntry));
3728 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003730 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003731 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003732 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3733 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003734 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003735 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003736 break;
3737 }
3738 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003739 case EventEntry::Type::DEVICE_RESET:
3740 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003741 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003742 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003743 break;
3744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 }
3746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3748 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003750
3751 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752}
3753
Svet Ganov5d3bc372020-01-26 23:11:07 -08003754void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3755 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003756 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 return;
3758 }
3759
3760 nsecs_t currentTime = now();
3761
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003762 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003763 connection->inputState.synthesizePointerDownEvents(currentTime);
3764
3765 if (downEvents.empty()) {
3766 return;
3767 }
3768
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003769 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003770 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3771 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003772 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003773
3774 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003775 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003776 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3777 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003778 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003779 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003780 target.globalScaleFactor = windowInfo->globalScaleFactor;
3781 }
3782 target.inputChannel = connection->inputChannel;
3783 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003786 switch (downEventEntry->type) {
3787 case EventEntry::Type::MOTION: {
3788 logOutboundMotionDetails("down - ",
3789 static_cast<const MotionEntry&>(*downEventEntry));
3790 break;
3791 }
3792
3793 case EventEntry::Type::KEY:
3794 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003795 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003796 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003797 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003798 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003799 case EventEntry::Type::SENSOR:
3800 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003801 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003802 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003803 break;
3804 }
3805 }
3806
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003807 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3808 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003809 }
3810
3811 startDispatchCycleLocked(currentTime, connection);
3812}
3813
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003814std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3815 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 ALOG_ASSERT(pointerIds.value != 0);
3817
3818 uint32_t splitPointerIndexMap[MAX_POINTERS];
3819 PointerProperties splitPointerProperties[MAX_POINTERS];
3820 PointerCoords splitPointerCoords[MAX_POINTERS];
3821
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003822 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 uint32_t splitPointerCount = 0;
3824
3825 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003828 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 uint32_t pointerId = uint32_t(pointerProperties.id);
3830 if (pointerIds.hasBit(pointerId)) {
3831 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3832 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3833 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003834 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 splitPointerCount += 1;
3836 }
3837 }
3838
3839 if (splitPointerCount != pointerIds.count()) {
3840 // This is bad. We are missing some of the pointers that we expected to deliver.
3841 // Most likely this indicates that we received an ACTION_MOVE events that has
3842 // different pointer ids than we expected based on the previous ACTION_DOWN
3843 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3844 // in this way.
3845 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003846 "we expected there to be %d pointers. This probably means we received "
3847 "a broken sequence of pointer ids from the input device.",
3848 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003849 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003852 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3855 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3857 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003858 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 uint32_t pointerId = uint32_t(pointerProperties.id);
3860 if (pointerIds.hasBit(pointerId)) {
3861 if (pointerIds.count() == 1) {
3862 // The first/last pointer went down/up.
3863 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003864 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003865 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3866 ? AMOTION_EVENT_ACTION_CANCEL
3867 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 } else {
3869 // A secondary pointer went down/up.
3870 uint32_t splitPointerIndex = 0;
3871 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3872 splitPointerIndex += 1;
3873 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003874 action = maskedAction |
3875 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
3877 } else {
3878 // An unrelated pointer changed.
3879 action = AMOTION_EVENT_ACTION_MOVE;
3880 }
3881 }
3882
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003883 int32_t newId = mIdGenerator.nextId();
3884 if (ATRACE_ENABLED()) {
3885 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3886 ") to MotionEvent(id=0x%" PRIx32 ").",
3887 originalMotionEntry.id, newId);
3888 ATRACE_NAME(message.c_str());
3889 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003890 std::unique_ptr<MotionEntry> splitMotionEntry =
3891 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3892 originalMotionEntry.deviceId, originalMotionEntry.source,
3893 originalMotionEntry.displayId,
3894 originalMotionEntry.policyFlags, action,
3895 originalMotionEntry.actionButton,
3896 originalMotionEntry.flags, originalMotionEntry.metaState,
3897 originalMotionEntry.buttonState,
3898 originalMotionEntry.classification,
3899 originalMotionEntry.edgeFlags,
3900 originalMotionEntry.xPrecision,
3901 originalMotionEntry.yPrecision,
3902 originalMotionEntry.xCursorPosition,
3903 originalMotionEntry.yCursorPosition,
3904 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003905 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003907 if (originalMotionEntry.injectionState) {
3908 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 splitMotionEntry->injectionState->refCount += 1;
3910 }
3911
3912 return splitMotionEntry;
3913}
3914
3915void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003916 if (DEBUG_INBOUND_EVENT_DETAILS) {
3917 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919
Antonio Kantekf16f2832021-09-28 04:39:20 +00003920 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003922 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003924 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3925 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3926 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 } // release lock
3928
3929 if (needWake) {
3930 mLooper->wake();
3931 }
3932}
3933
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003934/**
3935 * If one of the meta shortcuts is detected, process them here:
3936 * Meta + Backspace -> generate BACK
3937 * Meta + Enter -> generate HOME
3938 * This will potentially overwrite keyCode and metaState.
3939 */
3940void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003942 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3943 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3944 if (keyCode == AKEYCODE_DEL) {
3945 newKeyCode = AKEYCODE_BACK;
3946 } else if (keyCode == AKEYCODE_ENTER) {
3947 newKeyCode = AKEYCODE_HOME;
3948 }
3949 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003950 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003951 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003952 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003953 keyCode = newKeyCode;
3954 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3955 }
3956 } else if (action == AKEY_EVENT_ACTION_UP) {
3957 // In order to maintain a consistent stream of up and down events, check to see if the key
3958 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3959 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003960 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003961 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003962 auto replacementIt = mReplacedKeys.find(replacement);
3963 if (replacementIt != mReplacedKeys.end()) {
3964 keyCode = replacementIt->second;
3965 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003966 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3967 }
3968 }
3969}
3970
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003972 if (DEBUG_INBOUND_EVENT_DETAILS) {
3973 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3974 "policyFlags=0x%x, action=0x%x, "
3975 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3976 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3977 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3978 args->downTime);
3979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 if (!validateKeyEvent(args->action)) {
3981 return;
3982 }
3983
3984 uint32_t policyFlags = args->policyFlags;
3985 int32_t flags = args->flags;
3986 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003987 // InputDispatcher tracks and generates key repeats on behalf of
3988 // whatever notifies it, so repeatCount should always be set to 0
3989 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3991 policyFlags |= POLICY_FLAG_VIRTUAL;
3992 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 if (policyFlags & POLICY_FLAG_FUNCTION) {
3995 metaState |= AMETA_FUNCTION_ON;
3996 }
3997
3998 policyFlags |= POLICY_FLAG_TRUSTED;
3999
Michael Wright78f24442014-08-06 15:55:28 -07004000 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004001 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004002
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004004 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004005 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4006 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
Michael Wright2b3c3302018-03-02 17:19:13 +00004008 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004010 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4011 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004012 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
Antonio Kantekf16f2832021-09-28 04:39:20 +00004015 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 { // acquire lock
4017 mLock.lock();
4018
4019 if (shouldSendKeyToInputFilterLocked(args)) {
4020 mLock.unlock();
4021
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004022 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4024 return; // event was consumed by the filter
4025 }
4026
4027 mLock.lock();
4028 }
4029
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004030 std::unique_ptr<KeyEntry> newEntry =
4031 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4032 args->displayId, policyFlags, args->action, flags,
4033 keyCode, args->scanCode, metaState, repeatCount,
4034 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 mLock.unlock();
4038 } // release lock
4039
4040 if (needWake) {
4041 mLooper->wake();
4042 }
4043}
4044
4045bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4046 return mInputFilterEnabled;
4047}
4048
4049void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004050 if (DEBUG_INBOUND_EVENT_DETAILS) {
4051 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4052 "displayId=%" PRId32 ", policyFlags=0x%x, "
4053 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4054 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4055 "yCursorPosition=%f, downTime=%" PRId64,
4056 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4057 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4058 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4059 args->xCursorPosition, args->yCursorPosition, args->downTime);
4060 for (uint32_t i = 0; i < args->pointerCount; i++) {
4061 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4062 "x=%f, y=%f, pressure=%f, size=%f, "
4063 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4064 "orientation=%f",
4065 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4066 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4067 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4068 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4069 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4070 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4071 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4072 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4073 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4074 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4078 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 return;
4080 }
4081
4082 uint32_t policyFlags = args->policyFlags;
4083 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004084
4085 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004086 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004087 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4088 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Antonio Kantekf16f2832021-09-28 04:39:20 +00004092 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 { // acquire lock
4094 mLock.lock();
4095
4096 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004097 ui::Transform displayTransform;
4098 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4099 displayTransform = it->second.transform;
4100 }
4101
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 mLock.unlock();
4103
4104 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004105 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4106 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004107 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004108 displayTransform, args->xPrecision, args->yPrecision,
4109 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004110 args->downTime, args->eventTime, args->pointerCount,
4111 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112
4113 policyFlags |= POLICY_FLAG_FILTERED;
4114 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4115 return; // event was consumed by the filter
4116 }
4117
4118 mLock.lock();
4119 }
4120
4121 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004122 std::unique_ptr<MotionEntry> newEntry =
4123 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4124 args->source, args->displayId, policyFlags,
4125 args->action, args->actionButton, args->flags,
4126 args->metaState, args->buttonState,
4127 args->classification, args->edgeFlags,
4128 args->xPrecision, args->yPrecision,
4129 args->xCursorPosition, args->yCursorPosition,
4130 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004131 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004133 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4134 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4135 !mInputFilterEnabled) {
4136 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4137 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4138 }
4139
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004140 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 mLock.unlock();
4142 } // release lock
4143
4144 if (needWake) {
4145 mLooper->wake();
4146 }
4147}
4148
Chris Yef59a2f42020-10-16 12:55:26 -07004149void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004150 if (DEBUG_INBOUND_EVENT_DETAILS) {
4151 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4152 " sensorType=%s",
4153 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004154 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004155 }
Chris Yef59a2f42020-10-16 12:55:26 -07004156
Antonio Kantekf16f2832021-09-28 04:39:20 +00004157 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004158 { // acquire lock
4159 mLock.lock();
4160
4161 // Just enqueue a new sensor event.
4162 std::unique_ptr<SensorEntry> newEntry =
4163 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4164 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4165 args->sensorType, args->accuracy,
4166 args->accuracyChanged, args->values);
4167
4168 needWake = enqueueInboundEventLocked(std::move(newEntry));
4169 mLock.unlock();
4170 } // release lock
4171
4172 if (needWake) {
4173 mLooper->wake();
4174 }
4175}
4176
Chris Yefb552902021-02-03 17:18:37 -08004177void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004178 if (DEBUG_INBOUND_EVENT_DETAILS) {
4179 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4180 args->deviceId, args->isOn);
4181 }
Chris Yefb552902021-02-03 17:18:37 -08004182 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4183}
4184
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004186 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187}
4188
4189void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004190 if (DEBUG_INBOUND_EVENT_DETAILS) {
4191 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4192 "switchMask=0x%08x",
4193 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195
4196 uint32_t policyFlags = args->policyFlags;
4197 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004198 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199}
4200
4201void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004202 if (DEBUG_INBOUND_EVENT_DETAILS) {
4203 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4204 args->deviceId);
4205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
Antonio Kantekf16f2832021-09-28 04:39:20 +00004207 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004209 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004211 std::unique_ptr<DeviceResetEntry> newEntry =
4212 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4213 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 } // release lock
4215
4216 if (needWake) {
4217 mLooper->wake();
4218 }
4219}
4220
Prabir Pradhan7e186182020-11-10 13:56:45 -08004221void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004222 if (DEBUG_INBOUND_EVENT_DETAILS) {
4223 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004224 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004225 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004226
Antonio Kantekf16f2832021-09-28 04:39:20 +00004227 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004228 { // acquire lock
4229 std::scoped_lock _l(mLock);
4230 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004231 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004232 needWake = enqueueInboundEventLocked(std::move(entry));
4233 } // release lock
4234
4235 if (needWake) {
4236 mLooper->wake();
4237 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004238}
4239
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004240InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4241 std::optional<int32_t> targetUid,
4242 InputEventInjectionSync syncMode,
4243 std::chrono::milliseconds timeout,
4244 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004245 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004246 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4247 "policyFlags=0x%08x",
4248 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4249 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004250 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004251 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004253 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004255 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004256 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4257 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4258 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4259 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4260 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004261 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004262 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004263 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004264 }
4265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004266 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004269 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4270 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004272 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004275 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004276 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4277 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4278 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004279 int32_t keyCode = incomingKey.getKeyCode();
4280 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004281 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004283 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004285 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4286 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4287 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4290 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004291 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292
4293 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4294 android::base::Timer t;
4295 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4296 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4297 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4298 std::to_string(t.duration().count()).c_str());
4299 }
4300 }
4301
4302 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004303 std::unique_ptr<KeyEntry> injectedEntry =
4304 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004305 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004306 incomingKey.getDisplayId(), policyFlags, action,
4307 flags, keyCode, incomingKey.getScanCode(), metaState,
4308 incomingKey.getRepeatCount(),
4309 incomingKey.getDownTime());
4310 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 }
4313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004315 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004316 const int32_t action = motionEvent.getAction();
4317 const bool isPointerEvent =
4318 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4319 // If a pointer event has no displayId specified, inject it to the default display.
4320 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4321 ? ADISPLAY_ID_DEFAULT
4322 : event->getDisplayId();
4323 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004324 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004325 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004326 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004328 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 }
4330
4331 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004332 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004333 android::base::Timer t;
4334 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4335 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4336 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4337 std::to_string(t.duration().count()).c_str());
4338 }
4339 }
4340
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004341 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4342 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4343 }
4344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004345 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004346 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4347 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004349 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4350 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004351 displayId, policyFlags, action, actionButton,
4352 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004353 motionEvent.getButtonState(),
4354 motionEvent.getClassification(),
4355 motionEvent.getEdgeFlags(),
4356 motionEvent.getXPrecision(),
4357 motionEvent.getYPrecision(),
4358 motionEvent.getRawXCursorPosition(),
4359 motionEvent.getRawYCursorPosition(),
4360 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004361 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004362 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004363 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004364 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004365 sampleEventTimes += 1;
4366 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004367 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004368 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4369 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004370 displayId, policyFlags, action, actionButton,
4371 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004372 motionEvent.getButtonState(),
4373 motionEvent.getClassification(),
4374 motionEvent.getEdgeFlags(),
4375 motionEvent.getXPrecision(),
4376 motionEvent.getYPrecision(),
4377 motionEvent.getRawXCursorPosition(),
4378 motionEvent.getRawYCursorPosition(),
4379 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004380 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004381 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004382 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4383 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004384 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 }
4386 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004390 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 }
4393
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004394 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 injectionState->injectionIsAsync = true;
4397 }
4398
4399 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004400 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
4402 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004403 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004404 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004405 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 }
4407
4408 mLock.unlock();
4409
4410 if (needWake) {
4411 mLooper->wake();
4412 }
4413
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004414 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004416 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004418 if (syncMode == InputEventInjectionSync::NONE) {
4419 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 } else {
4421 for (;;) {
4422 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004423 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 break;
4425 }
4426
4427 nsecs_t remainingTimeout = endTime - now();
4428 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004429 if (DEBUG_INJECTION) {
4430 ALOGD("injectInputEvent - Timed out waiting for injection result "
4431 "to become available.");
4432 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004433 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 break;
4435 }
4436
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004437 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 }
4439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004440 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4441 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 if (DEBUG_INJECTION) {
4444 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4445 injectionState->pendingForegroundDispatches);
4446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 nsecs_t remainingTimeout = endTime - now();
4448 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004449 if (DEBUG_INJECTION) {
4450 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4451 "dispatches to finish.");
4452 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004453 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 break;
4455 }
4456
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004457 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 }
4459 }
4460 }
4461
4462 injectionState->release();
4463 } // release lock
4464
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004465 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004466 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468
4469 return injectionResult;
4470}
4471
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004472std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004473 std::array<uint8_t, 32> calculatedHmac;
4474 std::unique_ptr<VerifiedInputEvent> result;
4475 switch (event.getType()) {
4476 case AINPUT_EVENT_TYPE_KEY: {
4477 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4478 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4479 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004480 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004481 break;
4482 }
4483 case AINPUT_EVENT_TYPE_MOTION: {
4484 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4485 VerifiedMotionEvent verifiedMotionEvent =
4486 verifiedMotionEventFromMotionEvent(motionEvent);
4487 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004488 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004489 break;
4490 }
4491 default: {
4492 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4493 return nullptr;
4494 }
4495 }
4496 if (calculatedHmac == INVALID_HMAC) {
4497 return nullptr;
4498 }
4499 if (calculatedHmac != event.getHmac()) {
4500 return nullptr;
4501 }
4502 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004503}
4504
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004505void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004506 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004507 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004509 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004510 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004513 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 // Log the outcome since the injector did not wait for the injection result.
4515 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004516 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004517 ALOGV("Asynchronous input event injection succeeded.");
4518 break;
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004519 case InputEventInjectionResult::TARGET_MISMATCH:
4520 ALOGV("Asynchronous input event injection target mismatch.");
4521 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004522 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 ALOGW("Asynchronous input event injection failed.");
4524 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004525 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 ALOGW("Asynchronous input event injection timed out.");
4527 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004528 case InputEventInjectionResult::PENDING:
4529 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4530 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 }
4532 }
4533
4534 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004535 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 }
4537}
4538
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004539void InputDispatcher::transformMotionEntryForInjectionLocked(
4540 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004541 // Input injection works in the logical display coordinate space, but the input pipeline works
4542 // display space, so we need to transform the injected events accordingly.
4543 const auto it = mDisplayInfos.find(entry.displayId);
4544 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004545 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004546
4547 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004548 entry.pointerCoords[i] =
4549 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4550 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004551 }
4552}
4553
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004554void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4555 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 if (injectionState) {
4557 injectionState->pendingForegroundDispatches += 1;
4558 }
4559}
4560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004561void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4562 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 if (injectionState) {
4564 injectionState->pendingForegroundDispatches -= 1;
4565
4566 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004567 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569 }
4570}
4571
chaviw98318de2021-05-19 16:45:23 -05004572const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004573 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004574 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004575 auto it = mWindowHandlesByDisplay.find(displayId);
4576 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004577}
4578
chaviw98318de2021-05-19 16:45:23 -05004579sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004580 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004581 if (windowHandleToken == nullptr) {
4582 return nullptr;
4583 }
4584
Arthur Hungb92218b2018-08-14 12:00:21 +08004585 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004586 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4587 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004588 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004589 return windowHandle;
4590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 }
4592 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004593 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594}
4595
chaviw98318de2021-05-19 16:45:23 -05004596sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4597 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004598 if (windowHandleToken == nullptr) {
4599 return nullptr;
4600 }
4601
chaviw98318de2021-05-19 16:45:23 -05004602 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004603 if (windowHandle->getToken() == windowHandleToken) {
4604 return windowHandle;
4605 }
4606 }
4607 return nullptr;
4608}
4609
chaviw98318de2021-05-19 16:45:23 -05004610sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4611 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004612 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004613 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4614 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004615 if (handle->getId() == windowHandle->getId() &&
4616 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004617 if (windowHandle->getInfo()->displayId != it.first) {
4618 ALOGE("Found window %s in display %" PRId32
4619 ", but it should belong to display %" PRId32,
4620 windowHandle->getName().c_str(), it.first,
4621 windowHandle->getInfo()->displayId);
4622 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004623 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 }
4626 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004627 return nullptr;
4628}
4629
chaviw98318de2021-05-19 16:45:23 -05004630sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004631 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4632 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633}
4634
chaviw98318de2021-05-19 16:45:23 -05004635bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004636 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4637 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004638 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004639 if (connection != nullptr && noInputChannel) {
4640 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4641 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4642 return false;
4643 }
4644
4645 if (connection == nullptr) {
4646 if (!noInputChannel) {
4647 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4648 }
4649 return false;
4650 }
4651 if (!connection->responsive) {
4652 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4653 return false;
4654 }
4655 return true;
4656}
4657
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004658std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4659 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004660 auto connectionIt = mConnectionsByToken.find(token);
4661 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004662 return nullptr;
4663 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004664 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004665}
4666
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004667void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004668 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4669 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004670 // Remove all handles on a display if there are no windows left.
4671 mWindowHandlesByDisplay.erase(displayId);
4672 return;
4673 }
4674
4675 // Since we compare the pointer of input window handles across window updates, we need
4676 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004677 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4678 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4679 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004680 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004681 }
4682
chaviw98318de2021-05-19 16:45:23 -05004683 std::vector<sp<WindowInfoHandle>> newHandles;
4684 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004685 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004686 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004687 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004688 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004689 const bool canReceiveInput =
4690 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4691 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004692 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004693 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004694 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004695 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004696 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004697 }
4698
4699 if (info->displayId != displayId) {
4700 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4701 handle->getName().c_str(), displayId, info->displayId);
4702 continue;
4703 }
4704
Robert Carredd13602020-04-13 17:24:34 -07004705 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4706 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004707 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004708 oldHandle->updateFrom(handle);
4709 newHandles.push_back(oldHandle);
4710 } else {
4711 newHandles.push_back(handle);
4712 }
4713 }
4714
4715 // Insert or replace
4716 mWindowHandlesByDisplay[displayId] = newHandles;
4717}
4718
Arthur Hung72d8dc32020-03-28 00:48:39 +00004719void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004720 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004721 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004722 { // acquire lock
4723 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004724 for (const auto& [displayId, handles] : handlesPerDisplay) {
4725 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004726 }
4727 }
4728 // Wake up poll loop since it may need to make new input dispatching choices.
4729 mLooper->wake();
4730}
4731
Arthur Hungb92218b2018-08-14 12:00:21 +08004732/**
4733 * Called from InputManagerService, update window handle list by displayId that can receive input.
4734 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4735 * If set an empty list, remove all handles from the specific display.
4736 * For focused handle, check if need to change and send a cancel event to previous one.
4737 * For removed handle, check if need to send a cancel event if already in touch.
4738 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004739void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004740 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004741 if (DEBUG_FOCUS) {
4742 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004743 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004744 windowList += iwh->getName() + " ";
4745 }
4746 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748
Prabir Pradhand65552b2021-10-07 11:23:50 -07004749 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004750 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004751 const WindowInfo& info = *window->getInfo();
4752
4753 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004754 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004755 if (noInputWindow && window->getToken() != nullptr) {
4756 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4757 window->getName().c_str());
4758 window->releaseChannel();
4759 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004760
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004761 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004762 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4763 !info.inputConfig.test(
4764 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004765 "%s has feature SPY, but is not a trusted overlay.",
4766 window->getName().c_str());
4767
Prabir Pradhand65552b2021-10-07 11:23:50 -07004768 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004769 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4770 !info.inputConfig.test(
4771 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004772 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4773 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004774 }
4775
Arthur Hung72d8dc32020-03-28 00:48:39 +00004776 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004777 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004779 // Save the old windows' orientation by ID before it gets updated.
4780 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004781 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004782 oldWindowOrientations.emplace(handle->getId(),
4783 handle->getInfo()->transform.getOrientation());
4784 }
4785
chaviw98318de2021-05-19 16:45:23 -05004786 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004787
chaviw98318de2021-05-19 16:45:23 -05004788 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004789 if (mLastHoverWindowHandle &&
4790 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4791 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004792 mLastHoverWindowHandle = nullptr;
4793 }
4794
Vishnu Nairc519ff72021-01-21 08:23:08 -08004795 std::optional<FocusResolver::FocusChanges> changes =
4796 mFocusResolver.setInputWindows(displayId, windowHandles);
4797 if (changes) {
4798 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004801 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4802 mTouchStatesByDisplay.find(displayId);
4803 if (stateIt != mTouchStatesByDisplay.end()) {
4804 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004805 for (size_t i = 0; i < state.windows.size();) {
4806 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004807 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004808 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 ALOGD("Touched window was removed: %s in display %" PRId32,
4810 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004811 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004812 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004813 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4814 if (touchedInputChannel != nullptr) {
4815 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4816 "touched window was removed");
4817 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004818 // Since we are about to drop the touch, cancel the events for the wallpaper as
4819 // well.
4820 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004821 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4822 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004823 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4824 if (wallpaper != nullptr) {
4825 sp<Connection> wallpaperConnection =
4826 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004827 if (wallpaperConnection != nullptr) {
4828 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4829 options);
4830 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004831 }
4832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004834 state.windows.erase(state.windows.begin() + i);
4835 } else {
4836 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 }
4838 }
arthurhungb89ccb02020-12-30 16:19:01 +08004839
arthurhung6d4bed92021-03-17 11:59:33 +08004840 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004841 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004842 if (mDragState &&
4843 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004844 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004845 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004846 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004847 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004848
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004849 // Determine if the orientation of any of the input windows have changed, and cancel all
4850 // pointer events if necessary.
4851 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4852 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4853 if (newWindowHandle != nullptr &&
4854 newWindowHandle->getInfo()->transform.getOrientation() !=
4855 oldWindowOrientations[oldWindowHandle->getId()]) {
4856 std::shared_ptr<InputChannel> inputChannel =
4857 getInputChannelLocked(newWindowHandle->getToken());
4858 if (inputChannel != nullptr) {
4859 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4860 "touched window's orientation changed");
4861 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004862 }
4863 }
4864 }
4865
Arthur Hung72d8dc32020-03-28 00:48:39 +00004866 // Release information for windows that are no longer present.
4867 // This ensures that unused input channels are released promptly.
4868 // Otherwise, they might stick around until the window handle is destroyed
4869 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004870 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004871 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004872 if (DEBUG_FOCUS) {
4873 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004874 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004875 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004876 }
chaviw291d88a2019-02-14 10:33:58 -08004877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878}
4879
4880void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004881 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004882 if (DEBUG_FOCUS) {
4883 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4884 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4885 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004886 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004887 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004888 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 } // release lock
4890
4891 // Wake up poll loop since it may need to make new input dispatching choices.
4892 mLooper->wake();
4893}
4894
Vishnu Nair599f1412021-06-21 10:39:58 -07004895void InputDispatcher::setFocusedApplicationLocked(
4896 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4897 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4898 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4899
4900 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4901 return; // This application is already focused. No need to wake up or change anything.
4902 }
4903
4904 // Set the new application handle.
4905 if (inputApplicationHandle != nullptr) {
4906 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4907 } else {
4908 mFocusedApplicationHandlesByDisplay.erase(displayId);
4909 }
4910
4911 // No matter what the old focused application was, stop waiting on it because it is
4912 // no longer focused.
4913 resetNoFocusedWindowTimeoutLocked();
4914}
4915
Tiger Huang721e26f2018-07-24 22:26:19 +08004916/**
4917 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4918 * the display not specified.
4919 *
4920 * We track any unreleased events for each window. If a window loses the ability to receive the
4921 * released event, we will send a cancel event to it. So when the focused display is changed, we
4922 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4923 * display. The display-specified events won't be affected.
4924 */
4925void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004926 if (DEBUG_FOCUS) {
4927 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4928 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004929 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004930 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004931
4932 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004933 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004934 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004935 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004936 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004937 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004938 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004939 CancelationOptions
4940 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4941 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004942 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004943 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4944 }
4945 }
4946 mFocusedDisplayId = displayId;
4947
Chris Ye3c2d6f52020-08-09 10:39:48 -07004948 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004949 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004950 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004951
Vishnu Nairad321cd2020-08-20 16:40:21 -07004952 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004953 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004954 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004955 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004956 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004957 }
4958 }
4959 }
4960
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004961 if (DEBUG_FOCUS) {
4962 logDispatchStateLocked();
4963 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 } // release lock
4965
4966 // Wake up poll loop since it may need to make new input dispatching choices.
4967 mLooper->wake();
4968}
4969
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004971 if (DEBUG_FOCUS) {
4972 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974
4975 bool changed;
4976 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004977 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978
4979 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4980 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 }
4983
4984 if (mDispatchEnabled && !enabled) {
4985 resetAndDropEverythingLocked("dispatcher is being disabled");
4986 }
4987
4988 mDispatchEnabled = enabled;
4989 mDispatchFrozen = frozen;
4990 changed = true;
4991 } else {
4992 changed = false;
4993 }
4994
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004995 if (DEBUG_FOCUS) {
4996 logDispatchStateLocked();
4997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 } // release lock
4999
5000 if (changed) {
5001 // Wake up poll loop since it may need to make new input dispatching choices.
5002 mLooper->wake();
5003 }
5004}
5005
5006void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005007 if (DEBUG_FOCUS) {
5008 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010
5011 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005012 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013
5014 if (mInputFilterEnabled == enabled) {
5015 return;
5016 }
5017
5018 mInputFilterEnabled = enabled;
5019 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5020 } // release lock
5021
5022 // Wake up poll loop since there might be work to do to drop everything.
5023 mLooper->wake();
5024}
5025
Antonio Kantekea47acb2021-12-23 12:41:25 -08005026bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
5027 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005028 bool needWake = false;
5029 {
5030 std::scoped_lock lock(mLock);
5031 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005032 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005033 }
5034 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005035 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
5036 "hasPermission=%s)",
5037 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
5038 }
5039 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005040 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5041 !recentWindowsAreOwnedByLocked(pid, uid)) {
5042 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5043 "window nor none of the previously interacted window",
5044 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005045 return false;
5046 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005047 }
5048
5049 // TODO(b/198499018): Store touch mode per display.
5050 mInTouchMode = inTouchMode;
5051
Antonio Kantekf16f2832021-09-28 04:39:20 +00005052 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5053 needWake = enqueueInboundEventLocked(std::move(entry));
5054 } // release lock
5055
5056 if (needWake) {
5057 mLooper->wake();
5058 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005059 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005060}
5061
Antonio Kantek48710e42022-03-24 14:19:30 -07005062bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5063 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5064 if (focusedToken == nullptr) {
5065 return false;
5066 }
5067 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5068 return isWindowOwnedBy(windowHandle, pid, uid);
5069}
5070
5071bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5072 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5073 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5074 const sp<WindowInfoHandle> windowHandle =
5075 getWindowHandleLocked(connectionToken);
5076 return isWindowOwnedBy(windowHandle, pid, uid);
5077 }) != mInteractionConnectionTokens.end();
5078}
5079
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005080void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5081 if (opacity < 0 || opacity > 1) {
5082 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5083 return;
5084 }
5085
5086 std::scoped_lock lock(mLock);
5087 mMaximumObscuringOpacityForTouch = opacity;
5088}
5089
5090void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5091 std::scoped_lock lock(mLock);
5092 mBlockUntrustedTouchesMode = mode;
5093}
5094
Arthur Hungabbb9d82021-09-01 14:52:30 +00005095std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5096 const sp<IBinder>& token) {
5097 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5098 for (TouchedWindow& w : state.windows) {
5099 if (w.windowHandle->getToken() == token) {
5100 return std::make_pair(&state, &w);
5101 }
5102 }
5103 }
5104 return std::make_pair(nullptr, nullptr);
5105}
5106
arthurhungb89ccb02020-12-30 16:19:01 +08005107bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5108 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005109 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005110 if (DEBUG_FOCUS) {
5111 ALOGD("Trivial transfer to same window.");
5112 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005113 return true;
5114 }
5115
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005117 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118
Arthur Hungabbb9d82021-09-01 14:52:30 +00005119 // Find the target touch state and touched window by fromToken.
5120 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5121 if (state == nullptr || touchedWindow == nullptr) {
5122 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 return false;
5124 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005125
5126 const int32_t displayId = state->displayId;
5127 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5128 if (toWindowHandle == nullptr) {
5129 ALOGW("Cannot transfer focus because to window not found.");
5130 return false;
5131 }
5132
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005133 if (DEBUG_FOCUS) {
5134 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005135 touchedWindow->windowHandle->getName().c_str(),
5136 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
5138
Arthur Hungabbb9d82021-09-01 14:52:30 +00005139 // Erase old window.
5140 int32_t oldTargetFlags = touchedWindow->targetFlags;
5141 BitSet32 pointerIds = touchedWindow->pointerIds;
5142 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143
Arthur Hungabbb9d82021-09-01 14:52:30 +00005144 // Add new window.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005145 int32_t newTargetFlags =
5146 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5147 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5148 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5149 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005150 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 // Store the dragging window.
5153 if (isDragDrop) {
Arthur Hung54745652022-04-20 07:17:41 +00005154 if (pointerIds.count() > 1) {
5155 ALOGW("The drag and drop cannot be started when there is more than 1 pointer on the"
5156 " window.");
5157 return false;
5158 }
5159 // If the window didn't not support split or the source is mouse, the pointerIds count
5160 // would be 0, so we have to track the pointer 0.
5161 const int32_t id = pointerIds.count() == 0 ? 0 : pointerIds.firstMarkedBit();
5162 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 }
5164
Arthur Hungabbb9d82021-09-01 14:52:30 +00005165 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005166 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5167 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005168 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005169 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005170 CancelationOptions
5171 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5172 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005174 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 }
5176
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005177 if (DEBUG_FOCUS) {
5178 logDispatchStateLocked();
5179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 } // release lock
5181
5182 // Wake up poll loop since it may need to make new input dispatching choices.
5183 mLooper->wake();
5184 return true;
5185}
5186
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005187/**
5188 * Get the touched foreground window on the given display.
5189 * Return null if there are no windows touched on that display, or if more than one foreground
5190 * window is being touched.
5191 */
5192sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5193 auto stateIt = mTouchStatesByDisplay.find(displayId);
5194 if (stateIt == mTouchStatesByDisplay.end()) {
5195 ALOGI("No touch state on display %" PRId32, displayId);
5196 return nullptr;
5197 }
5198
5199 const TouchState& state = stateIt->second;
5200 sp<WindowInfoHandle> touchedForegroundWindow;
5201 // If multiple foreground windows are touched, return nullptr
5202 for (const TouchedWindow& window : state.windows) {
5203 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5204 if (touchedForegroundWindow != nullptr) {
5205 ALOGI("Two or more foreground windows: %s and %s",
5206 touchedForegroundWindow->getName().c_str(),
5207 window.windowHandle->getName().c_str());
5208 return nullptr;
5209 }
5210 touchedForegroundWindow = window.windowHandle;
5211 }
5212 }
5213 return touchedForegroundWindow;
5214}
5215
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005216// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005217bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005218 sp<IBinder> fromToken;
5219 { // acquire lock
5220 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005221 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005222 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005223 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5224 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005225 return false;
5226 }
5227
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005228 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5229 if (from == nullptr) {
5230 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5231 return false;
5232 }
5233
5234 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005235 } // release lock
5236
5237 return transferTouchFocus(fromToken, destChannelToken);
5238}
5239
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005241 if (DEBUG_FOCUS) {
5242 ALOGD("Resetting and dropping all events (%s).", reason);
5243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244
5245 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5246 synthesizeCancelationEventsForAllConnectionsLocked(options);
5247
5248 resetKeyRepeatLocked();
5249 releasePendingEventLocked();
5250 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005251 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005253 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005254 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005256 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257}
5258
5259void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005260 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 dumpDispatchStateLocked(dump);
5262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005263 std::istringstream stream(dump);
5264 std::string line;
5265
5266 while (std::getline(stream, line, '\n')) {
5267 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 }
5269}
5270
Prabir Pradhan99987712020-11-10 18:43:05 -08005271std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5272 std::string dump;
5273
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005274 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5275 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005276
5277 std::string windowName = "None";
5278 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005279 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005280 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5281 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5282 : "token has capture without window";
5283 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005284 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005285
5286 return dump;
5287}
5288
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005290 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5291 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5292 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005293 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294
Tiger Huang721e26f2018-07-24 22:26:19 +08005295 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5296 dump += StringPrintf(INDENT "FocusedApplications:\n");
5297 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5298 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005299 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005300 const std::chrono::duration timeout =
5301 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005302 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005303 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005304 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005307 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005309
Vishnu Nairc519ff72021-01-21 08:23:08 -08005310 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005311 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005313 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005314 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005315 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5316 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005317 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005318 state.displayId, toString(state.down), toString(state.split),
5319 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005320 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005321 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005322 for (size_t i = 0; i < state.windows.size(); i++) {
5323 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005324 dump += StringPrintf(INDENT4
5325 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5326 i, touchedWindow.windowHandle->getName().c_str(),
5327 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005328 }
5329 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005330 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 }
5333 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 }
5336
arthurhung6d4bed92021-03-17 11:59:33 +08005337 if (mDragState) {
5338 dump += StringPrintf(INDENT "DragState:\n");
5339 mDragState->dump(dump, INDENT2);
5340 }
5341
Arthur Hungb92218b2018-08-14 12:00:21 +08005342 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005343 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5344 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5345 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5346 const auto& displayInfo = it->second;
5347 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5348 displayInfo.logicalHeight);
5349 displayInfo.transform.dump(dump, "transform", INDENT4);
5350 } else {
5351 dump += INDENT2 "No DisplayInfo found!\n";
5352 }
5353
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005354 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005355 dump += INDENT2 "Windows:\n";
5356 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005357 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5358 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005360 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005361 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005362 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005363 "applicationInfo.name=%s, "
5364 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005365 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005366 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005367 windowInfo->displayId,
5368 windowInfo->inputConfig.string().c_str(),
5369 windowInfo->alpha, windowInfo->frameLeft,
5370 windowInfo->frameTop, windowInfo->frameRight,
5371 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005372 windowInfo->applicationInfo.name.c_str(),
5373 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005374 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005375 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005376 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005377 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005378 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005379 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005380 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005381 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005382 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005383 }
5384 } else {
5385 dump += INDENT2 "Windows: <none>\n";
5386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 }
5388 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005389 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 }
5391
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005392 if (!mGlobalMonitorsByDisplay.empty()) {
5393 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5394 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005395 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005398 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 }
5400
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005401 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402
5403 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005404 if (!mRecentQueue.empty()) {
5405 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005406 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005407 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005408 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005409 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 }
5411 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005412 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414
5415 // Dump event currently being dispatched.
5416 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005417 dump += INDENT "PendingEvent:\n";
5418 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005419 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005420 dump += StringPrintf(", age=%" PRId64 "ms\n",
5421 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 }
5425
5426 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005427 if (!mInboundQueue.empty()) {
5428 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005429 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005430 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005431 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005432 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 }
5434 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005435 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 }
5437
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005438 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005439 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005440 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5441 const KeyReplacement& replacement = pair.first;
5442 int32_t newKeyCode = pair.second;
5443 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005444 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005445 }
5446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005447 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005448 }
5449
Prabir Pradhancef936d2021-07-21 16:17:52 +00005450 if (!mCommandQueue.empty()) {
5451 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5452 } else {
5453 dump += INDENT "CommandQueue: <empty>\n";
5454 }
5455
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005456 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005457 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005458 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005459 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005460 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005461 connection->inputChannel->getFd().get(),
5462 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005463 connection->getWindowName().c_str(),
5464 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005465 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005467 if (!connection->outboundQueue.empty()) {
5468 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5469 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005470 dump += dumpQueue(connection->outboundQueue, currentTime);
5471
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005473 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 }
5475
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005476 if (!connection->waitQueue.empty()) {
5477 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5478 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005479 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483 }
5484 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005485 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 }
5487
5488 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005489 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5490 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005492 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 }
5494
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005495 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005496 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5497 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5498 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005499 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005500 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501}
5502
Michael Wright3dd60e22019-03-27 22:06:44 +00005503void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5504 const size_t numMonitors = monitors.size();
5505 for (size_t i = 0; i < numMonitors; i++) {
5506 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005507 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005508 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5509 dump += "\n";
5510 }
5511}
5512
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005513class LooperEventCallback : public LooperCallback {
5514public:
5515 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5516 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5517
5518private:
5519 std::function<int(int events)> mCallback;
5520};
5521
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005522Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005523 if (DEBUG_CHANNEL_CREATION) {
5524 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005527 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005528 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005529 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005530
5531 if (result) {
5532 return base::Error(result) << "Failed to open input channel pair with name " << name;
5533 }
5534
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005536 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005537 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005538 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005539 sp<Connection> connection =
5540 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5543 ALOGE("Created a new connection, but the token %p is already known", token.get());
5544 }
5545 mConnectionsByToken.emplace(token, connection);
5546
5547 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5548 this, std::placeholders::_1, token);
5549
5550 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 } // release lock
5552
5553 // Wake the looper because some connections have changed.
5554 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005555 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556}
5557
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005558Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005559 const std::string& name,
5560 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005561 std::shared_ptr<InputChannel> serverChannel;
5562 std::unique_ptr<InputChannel> clientChannel;
5563 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5564 if (result) {
5565 return base::Error(result) << "Failed to open input channel pair with name " << name;
5566 }
5567
Michael Wright3dd60e22019-03-27 22:06:44 +00005568 { // acquire lock
5569 std::scoped_lock _l(mLock);
5570
5571 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005572 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5573 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005574 }
5575
Garfield Tan15601662020-09-22 15:32:38 -07005576 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005577 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005578 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005579
5580 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5581 ALOGE("Created a new connection, but the token %p is already known", token.get());
5582 }
5583 mConnectionsByToken.emplace(token, connection);
5584 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5585 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005586
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005587 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005588
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005589 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005590 }
Garfield Tan15601662020-09-22 15:32:38 -07005591
Michael Wright3dd60e22019-03-27 22:06:44 +00005592 // Wake the looper because some connections have changed.
5593 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005594 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005595}
5596
Garfield Tan15601662020-09-22 15:32:38 -07005597status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005599 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600
Garfield Tan15601662020-09-22 15:32:38 -07005601 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 if (status) {
5603 return status;
5604 }
5605 } // release lock
5606
5607 // Wake the poll loop because removing the connection may have changed the current
5608 // synchronization state.
5609 mLooper->wake();
5610 return OK;
5611}
5612
Garfield Tan15601662020-09-22 15:32:38 -07005613status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5614 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005615 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005616 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005617 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 return BAD_VALUE;
5619 }
5620
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005621 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005622
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005624 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 }
5626
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005627 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628
5629 nsecs_t currentTime = now();
5630 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5631
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005632 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 return OK;
5634}
5635
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005636void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005637 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5638 auto& [displayId, monitors] = *it;
5639 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5640 return monitor.inputChannel->getConnectionToken() == connectionToken;
5641 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005642
Michael Wright3dd60e22019-03-27 22:06:44 +00005643 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005644 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005645 } else {
5646 ++it;
5647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 }
5649}
5650
Michael Wright3dd60e22019-03-27 22:06:44 +00005651status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005652 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005653
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005654 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5655 if (!requestingChannel) {
5656 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5657 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005658 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005659
5660 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5661 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5662 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5663 " Ignoring.");
5664 return BAD_VALUE;
5665 }
5666
5667 TouchState& state = *statePtr;
5668
5669 // Send cancel events to all the input channels we're stealing from.
5670 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5671 "input channel stole pointer stream");
5672 options.deviceId = state.deviceId;
5673 options.displayId = state.displayId;
5674 std::string canceledWindows;
5675 for (const TouchedWindow& window : state.windows) {
5676 const std::shared_ptr<InputChannel> channel =
5677 getInputChannelLocked(window.windowHandle->getToken());
5678 if (channel != nullptr && channel->getConnectionToken() != token) {
5679 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5680 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5681 canceledWindows += channel->getName();
5682 }
5683 }
5684 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5685 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5686 canceledWindows.c_str());
5687
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005688 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005689 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005690 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005691 return OK;
5692}
5693
Prabir Pradhan99987712020-11-10 18:43:05 -08005694void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5695 { // acquire lock
5696 std::scoped_lock _l(mLock);
5697 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005698 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005699 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5700 windowHandle != nullptr ? windowHandle->getName().c_str()
5701 : "token without window");
5702 }
5703
Vishnu Nairc519ff72021-01-21 08:23:08 -08005704 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005705 if (focusedToken != windowToken) {
5706 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5707 enabled ? "enable" : "disable");
5708 return;
5709 }
5710
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005711 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005712 ALOGW("Ignoring request to %s Pointer Capture: "
5713 "window has %s requested pointer capture.",
5714 enabled ? "enable" : "disable", enabled ? "already" : "not");
5715 return;
5716 }
5717
Christine Franksb768bb42021-11-29 12:11:31 -08005718 if (enabled) {
5719 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5720 mIneligibleDisplaysForPointerCapture.end(),
5721 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5722 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5723 return;
5724 }
5725 }
5726
Prabir Pradhan99987712020-11-10 18:43:05 -08005727 setPointerCaptureLocked(enabled);
5728 } // release lock
5729
5730 // Wake the thread to process command entries.
5731 mLooper->wake();
5732}
5733
Christine Franksb768bb42021-11-29 12:11:31 -08005734void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5735 { // acquire lock
5736 std::scoped_lock _l(mLock);
5737 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5738 if (!isEligible) {
5739 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5740 }
5741 } // release lock
5742}
5743
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005744std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5745 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005746 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005747 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005748 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005749 }
5750 }
5751 }
5752 return std::nullopt;
5753}
5754
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005755sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005756 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005757 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005758 }
5759
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005760 for (const auto& [token, connection] : mConnectionsByToken) {
5761 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005762 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763 }
5764 }
Robert Carr4e670e52018-08-15 13:26:12 -07005765
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005766 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767}
5768
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005769std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5770 sp<Connection> connection = getConnectionLocked(connectionToken);
5771 if (connection == nullptr) {
5772 return "<nullptr>";
5773 }
5774 return connection->getInputChannelName();
5775}
5776
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005777void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005778 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005779 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005780}
5781
Prabir Pradhancef936d2021-07-21 16:17:52 +00005782void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5783 const sp<Connection>& connection, uint32_t seq,
5784 bool handled, nsecs_t consumeTime) {
5785 // Handle post-event policy actions.
5786 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5787 if (dispatchEntryIt == connection->waitQueue.end()) {
5788 return;
5789 }
5790 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5791 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5792 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5793 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5794 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5795 }
5796 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5797 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5798 connection->inputChannel->getConnectionToken(),
5799 dispatchEntry->deliveryTime, consumeTime, finishTime);
5800 }
5801
5802 bool restartEvent;
5803 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5804 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5805 restartEvent =
5806 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5807 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5808 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5809 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5810 handled);
5811 } else {
5812 restartEvent = false;
5813 }
5814
5815 // Dequeue the event and start the next cycle.
5816 // Because the lock might have been released, it is possible that the
5817 // contents of the wait queue to have been drained, so we need to double-check
5818 // a few things.
5819 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5820 if (dispatchEntryIt != connection->waitQueue.end()) {
5821 dispatchEntry = *dispatchEntryIt;
5822 connection->waitQueue.erase(dispatchEntryIt);
5823 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5824 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5825 if (!connection->responsive) {
5826 connection->responsive = isConnectionResponsive(*connection);
5827 if (connection->responsive) {
5828 // The connection was unresponsive, and now it's responsive.
5829 processConnectionResponsiveLocked(*connection);
5830 }
5831 }
5832 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005833 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005834 connection->outboundQueue.push_front(dispatchEntry);
5835 traceOutboundQueueLength(*connection);
5836 } else {
5837 releaseDispatchEntry(dispatchEntry);
5838 }
5839 }
5840
5841 // Start the next dispatch cycle for this connection.
5842 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843}
5844
Prabir Pradhancef936d2021-07-21 16:17:52 +00005845void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5846 const sp<IBinder>& newToken) {
5847 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5848 scoped_unlock unlock(mLock);
5849 mPolicy->notifyFocusChanged(oldToken, newToken);
5850 };
5851 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852}
5853
Prabir Pradhancef936d2021-07-21 16:17:52 +00005854void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5855 auto command = [this, token, x, y]() REQUIRES(mLock) {
5856 scoped_unlock unlock(mLock);
5857 mPolicy->notifyDropWindow(token, x, y);
5858 };
5859 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005860}
5861
Prabir Pradhancef936d2021-07-21 16:17:52 +00005862void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5863 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5864 scoped_unlock unlock(mLock);
5865 mPolicy->notifyUntrustedTouch(obscuringPackage);
5866 };
5867 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005868}
5869
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005870void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5871 if (connection == nullptr) {
5872 LOG_ALWAYS_FATAL("Caller must check for nullness");
5873 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005874 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5875 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005876 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005877 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005878 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005879 return;
5880 }
5881 /**
5882 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5883 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5884 * has changed. This could cause newer entries to time out before the already dispatched
5885 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5886 * processes the events linearly. So providing information about the oldest entry seems to be
5887 * most useful.
5888 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005889 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5891 std::string reason =
5892 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005894 ns2ms(currentWait),
5895 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005896 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005897 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5900
5901 // Stop waking up for events on this connection, it is already unresponsive
5902 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005903}
5904
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005905void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5906 std::string reason =
5907 StringPrintf("%s does not have a focused window", application->getName().c_str());
5908 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005909
Prabir Pradhancef936d2021-07-21 16:17:52 +00005910 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5911 scoped_unlock unlock(mLock);
5912 mPolicy->notifyNoFocusedWindowAnr(application);
5913 };
5914 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005915}
5916
chaviw98318de2021-05-19 16:45:23 -05005917void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005918 const std::string& reason) {
5919 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5920 updateLastAnrStateLocked(windowLabel, reason);
5921}
5922
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005923void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5924 const std::string& reason) {
5925 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005926 updateLastAnrStateLocked(windowLabel, reason);
5927}
5928
5929void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5930 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005932 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 struct tm tm;
5934 localtime_r(&t, &tm);
5935 char timestr[64];
5936 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005937 mLastAnrState.clear();
5938 mLastAnrState += INDENT "ANR:\n";
5939 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005940 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5941 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005942 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943}
5944
Prabir Pradhancef936d2021-07-21 16:17:52 +00005945void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5946 KeyEntry& entry) {
5947 const KeyEvent event = createKeyEvent(entry);
5948 nsecs_t delay = 0;
5949 { // release lock
5950 scoped_unlock unlock(mLock);
5951 android::base::Timer t;
5952 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5953 entry.policyFlags);
5954 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5955 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5956 std::to_string(t.duration().count()).c_str());
5957 }
5958 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
5960 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005961 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005962 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005963 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005965 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5966 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968}
5969
Prabir Pradhancef936d2021-07-21 16:17:52 +00005970void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005971 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005972 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005973 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005974 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005975 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005976 };
5977 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005978}
5979
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5981 std::optional<int32_t> pid) {
5982 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005983 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005984 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005985 };
5986 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005987}
5988
5989/**
5990 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5991 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5992 * command entry to the command queue.
5993 */
5994void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5995 std::string reason) {
5996 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005997 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005998 if (connection.monitor) {
5999 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6000 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001 pid = findMonitorPidByTokenLocked(connectionToken);
6002 } else {
6003 // The connection is a window
6004 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6005 reason.c_str());
6006 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6007 if (handle != nullptr) {
6008 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006009 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006010 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006011 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006012}
6013
6014/**
6015 * Tell the policy that a connection has become responsive so that it can stop ANR.
6016 */
6017void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6018 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006019 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006020 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006021 pid = findMonitorPidByTokenLocked(connectionToken);
6022 } else {
6023 // The connection is a window
6024 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6025 if (handle != nullptr) {
6026 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006029 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006030}
6031
Prabir Pradhancef936d2021-07-21 16:17:52 +00006032bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006033 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006034 KeyEntry& keyEntry, bool handled) {
6035 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006036 if (!handled) {
6037 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006039 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 return false;
6041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043 // Get the fallback key state.
6044 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006045 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006046 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006047 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006048 connection->inputState.removeFallbackKey(originalKeyCode);
6049 }
6050
6051 if (handled || !dispatchEntry->hasForegroundTarget()) {
6052 // If the application handles the original key for which we previously
6053 // generated a fallback or if the window is not a foreground window,
6054 // then cancel the associated fallback key, if any.
6055 if (fallbackKeyCode != -1) {
6056 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006057 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6058 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6059 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6060 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6061 keyEntry.policyFlags);
6062 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006063 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006064 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065
6066 mLock.unlock();
6067
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006068 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006069 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070
6071 mLock.lock();
6072
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006073 // Cancel the fallback key.
6074 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006076 "application handled the original non-fallback key "
6077 "or is no longer a foreground target, "
6078 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 options.keyCode = fallbackKeyCode;
6080 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006082 connection->inputState.removeFallbackKey(originalKeyCode);
6083 }
6084 } else {
6085 // If the application did not handle a non-fallback key, first check
6086 // that we are in a good state to perform unhandled key event processing
6087 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006088 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006089 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006090 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6091 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6092 "since this is not an initial down. "
6093 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6094 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6095 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096 return false;
6097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006099 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006100 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6101 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6102 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6103 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6104 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106
6107 mLock.unlock();
6108
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006109 bool fallback =
6110 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006111 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112
6113 mLock.lock();
6114
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006115 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116 connection->inputState.removeFallbackKey(originalKeyCode);
6117 return false;
6118 }
6119
6120 // Latch the fallback keycode for this key on an initial down.
6121 // The fallback keycode cannot change at any other point in the lifecycle.
6122 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006124 fallbackKeyCode = event.getKeyCode();
6125 } else {
6126 fallbackKeyCode = AKEYCODE_UNKNOWN;
6127 }
6128 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6129 }
6130
6131 ALOG_ASSERT(fallbackKeyCode != -1);
6132
6133 // Cancel the fallback key if the policy decides not to send it anymore.
6134 // We will continue to dispatch the key to the policy but we will no
6135 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006136 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6137 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006138 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6139 if (fallback) {
6140 ALOGD("Unhandled key event: Policy requested to send key %d"
6141 "as a fallback for %d, but on the DOWN it had requested "
6142 "to send %d instead. Fallback canceled.",
6143 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6144 } else {
6145 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6146 "but on the DOWN it had requested to send %d. "
6147 "Fallback canceled.",
6148 originalKeyCode, fallbackKeyCode);
6149 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006150 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006151
6152 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6153 "canceling fallback, policy no longer desires it");
6154 options.keyCode = fallbackKeyCode;
6155 synthesizeCancelationEventsForConnectionLocked(connection, options);
6156
6157 fallback = false;
6158 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006159 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006160 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006161 }
6162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006164 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6165 {
6166 std::string msg;
6167 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6168 connection->inputState.getFallbackKeys();
6169 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6170 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6171 }
6172 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6173 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006174 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006175 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006176
6177 if (fallback) {
6178 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006179 keyEntry.eventTime = event.getEventTime();
6180 keyEntry.deviceId = event.getDeviceId();
6181 keyEntry.source = event.getSource();
6182 keyEntry.displayId = event.getDisplayId();
6183 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6184 keyEntry.keyCode = fallbackKeyCode;
6185 keyEntry.scanCode = event.getScanCode();
6186 keyEntry.metaState = event.getMetaState();
6187 keyEntry.repeatCount = event.getRepeatCount();
6188 keyEntry.downTime = event.getDownTime();
6189 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006191 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6192 ALOGD("Unhandled key event: Dispatching fallback key. "
6193 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6194 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6195 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006196 return true; // restart the event
6197 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006198 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6199 ALOGD("Unhandled key event: No fallback key.");
6200 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006201
6202 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006203 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006204 }
6205 }
6206 return false;
6207}
6208
Prabir Pradhancef936d2021-07-21 16:17:52 +00006209bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006210 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006211 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006212 return false;
6213}
6214
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215void InputDispatcher::traceInboundQueueLengthLocked() {
6216 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006217 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 }
6219}
6220
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006221void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 if (ATRACE_ENABLED()) {
6223 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006224 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6225 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 }
6227}
6228
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006229void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 if (ATRACE_ENABLED()) {
6231 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006232 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6233 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 }
6235}
6236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006237void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006238 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006240 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241 dumpDispatchStateLocked(dump);
6242
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006243 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006244 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006245 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 }
6247}
6248
6249void InputDispatcher::monitor() {
6250 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006251 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006253 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254}
6255
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006256/**
6257 * Wake up the dispatcher and wait until it processes all events and commands.
6258 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6259 * this method can be safely called from any thread, as long as you've ensured that
6260 * the work you are interested in completing has already been queued.
6261 */
6262bool InputDispatcher::waitForIdle() {
6263 /**
6264 * Timeout should represent the longest possible time that a device might spend processing
6265 * events and commands.
6266 */
6267 constexpr std::chrono::duration TIMEOUT = 100ms;
6268 std::unique_lock lock(mLock);
6269 mLooper->wake();
6270 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6271 return result == std::cv_status::no_timeout;
6272}
6273
Vishnu Naire798b472020-07-23 13:52:21 -07006274/**
6275 * Sets focus to the window identified by the token. This must be called
6276 * after updating any input window handles.
6277 *
6278 * Params:
6279 * request.token - input channel token used to identify the window that should gain focus.
6280 * request.focusedToken - the token that the caller expects currently to be focused. If the
6281 * specified token does not match the currently focused window, this request will be dropped.
6282 * If the specified focused token matches the currently focused window, the call will succeed.
6283 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6284 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6285 * when requesting the focus change. This determines which request gets
6286 * precedence if there is a focus change request from another source such as pointer down.
6287 */
Vishnu Nair958da932020-08-21 17:12:37 -07006288void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6289 { // acquire lock
6290 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006291 std::optional<FocusResolver::FocusChanges> changes =
6292 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6293 if (changes) {
6294 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006295 }
6296 } // release lock
6297 // Wake up poll loop since it may need to make new input dispatching choices.
6298 mLooper->wake();
6299}
6300
Vishnu Nairc519ff72021-01-21 08:23:08 -08006301void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6302 if (changes.oldFocus) {
6303 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006304 if (focusedInputChannel) {
6305 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6306 "focus left window");
6307 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006308 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006309 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006310 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006311 if (changes.newFocus) {
6312 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006313 }
6314
Prabir Pradhan99987712020-11-10 18:43:05 -08006315 // If a window has pointer capture, then it must have focus. We need to ensure that this
6316 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6317 // If the window loses focus before it loses pointer capture, then the window can be in a state
6318 // where it has pointer capture but not focus, violating the contract. Therefore we must
6319 // dispatch the pointer capture event before the focus event. Since focus events are added to
6320 // the front of the queue (above), we add the pointer capture event to the front of the queue
6321 // after the focus events are added. This ensures the pointer capture event ends up at the
6322 // front.
6323 disablePointerCaptureForcedLocked();
6324
Vishnu Nairc519ff72021-01-21 08:23:08 -08006325 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006326 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006327 }
6328}
Vishnu Nair958da932020-08-21 17:12:37 -07006329
Prabir Pradhan99987712020-11-10 18:43:05 -08006330void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006331 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006332 return;
6333 }
6334
6335 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6336
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006337 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006338 setPointerCaptureLocked(false);
6339 }
6340
6341 if (!mWindowTokenWithPointerCapture) {
6342 // No need to send capture changes because no window has capture.
6343 return;
6344 }
6345
6346 if (mPendingEvent != nullptr) {
6347 // Move the pending event to the front of the queue. This will give the chance
6348 // for the pending event to be dropped if it is a captured event.
6349 mInboundQueue.push_front(mPendingEvent);
6350 mPendingEvent = nullptr;
6351 }
6352
6353 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006354 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006355 mInboundQueue.push_front(std::move(entry));
6356}
6357
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006358void InputDispatcher::setPointerCaptureLocked(bool enable) {
6359 mCurrentPointerCaptureRequest.enable = enable;
6360 mCurrentPointerCaptureRequest.seq++;
6361 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006362 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006363 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006364 };
6365 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006366}
6367
Vishnu Nair599f1412021-06-21 10:39:58 -07006368void InputDispatcher::displayRemoved(int32_t displayId) {
6369 { // acquire lock
6370 std::scoped_lock _l(mLock);
6371 // Set an empty list to remove all handles from the specific display.
6372 setInputWindowsLocked(/* window handles */ {}, displayId);
6373 setFocusedApplicationLocked(displayId, nullptr);
6374 // Call focus resolver to clean up stale requests. This must be called after input windows
6375 // have been removed for the removed display.
6376 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006377 // Reset pointer capture eligibility, regardless of previous state.
6378 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006379 } // release lock
6380
6381 // Wake up poll loop since it may need to make new input dispatching choices.
6382 mLooper->wake();
6383}
6384
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006385void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6386 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006387 // The listener sends the windows as a flattened array. Separate the windows by display for
6388 // more convenient parsing.
6389 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006390 for (const auto& info : windowInfos) {
6391 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6392 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6393 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006394
6395 { // acquire lock
6396 std::scoped_lock _l(mLock);
6397 mDisplayInfos.clear();
6398 for (const auto& displayInfo : displayInfos) {
6399 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6400 }
6401
6402 for (const auto& [displayId, handles] : handlesPerDisplay) {
6403 setInputWindowsLocked(handles, displayId);
6404 }
6405 }
6406 // Wake up poll loop since it may need to make new input dispatching choices.
6407 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006408}
6409
Vishnu Nair062a8672021-09-03 16:07:44 -07006410bool InputDispatcher::shouldDropInput(
6411 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006412 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6413 (windowHandle->getInfo()->inputConfig.test(
6414 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006415 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006416 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6417 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006418 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006419 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006420 windowHandle->getInfo()->displayId);
6421 return true;
6422 }
6423 return false;
6424}
6425
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006426void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6427 const std::vector<gui::WindowInfo>& windowInfos,
6428 const std::vector<DisplayInfo>& displayInfos) {
6429 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6430}
6431
Arthur Hungdfd528e2021-12-08 13:23:04 +00006432void InputDispatcher::cancelCurrentTouch() {
6433 {
6434 std::scoped_lock _l(mLock);
6435 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6436 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6437 "cancel current touch");
6438 synthesizeCancelationEventsForAllConnectionsLocked(options);
6439
6440 mTouchStatesByDisplay.clear();
6441 mLastHoverWindowHandle.clear();
6442 }
6443 // Wake up poll loop since there might be work to do.
6444 mLooper->wake();
6445}
6446
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006447void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6448 std::scoped_lock _l(mLock);
6449 mMonitorDispatchingTimeout = timeout;
6450}
6451
Garfield Tane84e6f92019-08-29 17:28:41 -07006452} // namespace android::inputdispatcher