blob: 6bfac6cb5f2fc983eaa5bf9796a08c829a791d7c [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 Pradhan61a5d242021-07-26 16:41:09 +0000559} // namespace
560
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561// --- InputDispatcher ---
562
Garfield Tan00f511d2019-06-12 16:55:40 -0700563InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800564 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
565
566InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
567 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700568 : mPolicy(policy),
569 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700570 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800571 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700572 mAppSwitchSawKeyDown(false),
573 mAppSwitchDueTime(LONG_LONG_MAX),
574 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800575 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700576 mDispatchEnabled(false),
577 mDispatchFrozen(false),
578 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800579 // mInTouchMode will be initialized by the WindowManager to the default device config.
580 // To avoid leaking stack in case that call never comes, and for tests,
581 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000582 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100583 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000584 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800585 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800586 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000587 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800588 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800590 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700592 mWindowInfoListener = new DispatcherWindowListener(*this);
593 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
594
Yi Kong9b14ac62018-07-17 13:48:38 -0700595 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596
597 policy->getDispatcherConfiguration(&mConfig);
598}
599
600InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000601 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602
Prabir Pradhancef936d2021-07-21 16:17:52 +0000603 resetKeyRepeatLocked();
604 releasePendingEventLocked();
605 drainInboundQueueLocked();
606 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000608 while (!mConnectionsByToken.empty()) {
609 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000610 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
611 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
613}
614
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700615status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700616 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700617 return ALREADY_EXISTS;
618 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700619 mThread = std::make_unique<InputThread>(
620 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
621 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700622}
623
624status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700625 if (mThread && mThread->isCallingThread()) {
626 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700627 return INVALID_OPERATION;
628 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700629 mThread.reset();
630 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700631}
632
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633void InputDispatcher::dispatchOnce() {
634 nsecs_t nextWakeupTime = LONG_LONG_MAX;
635 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800636 std::scoped_lock _l(mLock);
637 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638
639 // Run a dispatch loop if there are no pending commands.
640 // The dispatch loop might enqueue commands to run afterwards.
641 if (!haveCommandsLocked()) {
642 dispatchOnceInnerLocked(&nextWakeupTime);
643 }
644
645 // Run all pending commands if there are any.
646 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000647 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 nextWakeupTime = LONG_LONG_MIN;
649 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800650
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700651 // If we are still waiting for ack on some events,
652 // we might have to wake up earlier to check if an app is anr'ing.
653 const nsecs_t nextAnrCheck = processAnrsLocked();
654 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
655
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800656 // We are about to enter an infinitely long sleep, because we have no commands or
657 // pending or queued events
658 if (nextWakeupTime == LONG_LONG_MAX) {
659 mDispatcherEnteredIdle.notify_all();
660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 } // release lock
662
663 // Wait for callback or timeout or wake. (make sure we round up, not down)
664 nsecs_t currentTime = now();
665 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
666 mLooper->pollOnce(timeoutMillis);
667}
668
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700669/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500670 * Raise ANR if there is no focused window.
671 * Before the ANR is raised, do a final state check:
672 * 1. The currently focused application must be the same one we are waiting for.
673 * 2. Ensure we still don't have a focused window.
674 */
675void InputDispatcher::processNoFocusedWindowAnrLocked() {
676 // Check if the application that we are waiting for is still focused.
677 std::shared_ptr<InputApplicationHandle> focusedApplication =
678 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
679 if (focusedApplication == nullptr ||
680 focusedApplication->getApplicationToken() !=
681 mAwaitedFocusedApplication->getApplicationToken()) {
682 // Unexpected because we should have reset the ANR timer when focused application changed
683 ALOGE("Waited for a focused window, but focused application has already changed to %s",
684 focusedApplication->getName().c_str());
685 return; // The focused application has changed.
686 }
687
chaviw98318de2021-05-19 16:45:23 -0500688 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500689 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
690 if (focusedWindowHandle != nullptr) {
691 return; // We now have a focused window. No need for ANR.
692 }
693 onAnrLocked(mAwaitedFocusedApplication);
694}
695
696/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700697 * Check if any of the connections' wait queues have events that are too old.
698 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
699 * Return the time at which we should wake up next.
700 */
701nsecs_t InputDispatcher::processAnrsLocked() {
702 const nsecs_t currentTime = now();
703 nsecs_t nextAnrCheck = LONG_LONG_MAX;
704 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
705 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
706 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500707 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700708 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500709 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700710 return LONG_LONG_MIN;
711 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500712 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
714 }
715 }
716
717 // Check if any connection ANRs are due
718 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
719 if (currentTime < nextAnrCheck) { // most likely scenario
720 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
721 }
722
723 // If we reached here, we have an unresponsive connection.
724 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
725 if (connection == nullptr) {
726 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
727 return nextAnrCheck;
728 }
729 connection->responsive = false;
730 // Stop waking up for this unresponsive connection
731 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000732 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700733 return LONG_LONG_MIN;
734}
735
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800736std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
737 const sp<Connection>& connection) {
738 if (connection->monitor) {
739 return mMonitorDispatchingTimeout;
740 }
741 const sp<WindowInfoHandle> window =
742 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700743 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500744 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700745 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500746 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700747}
748
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
750 nsecs_t currentTime = now();
751
Jeff Browndc5992e2014-04-11 01:27:26 -0700752 // Reset the key repeat timer whenever normal dispatch is suspended while the
753 // device is in a non-interactive state. This is to ensure that we abort a key
754 // repeat if the device is just coming out of sleep.
755 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 resetKeyRepeatLocked();
757 }
758
759 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
760 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100761 if (DEBUG_FOCUS) {
762 ALOGD("Dispatch frozen. Waiting some more.");
763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 return;
765 }
766
767 // Optimize latency of app switches.
768 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
769 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
770 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
771 if (mAppSwitchDueTime < *nextWakeupTime) {
772 *nextWakeupTime = mAppSwitchDueTime;
773 }
774
775 // Ready to start a new event.
776 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700778 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 if (isAppSwitchDue) {
780 // The inbound queue is empty so the app switch key we were waiting
781 // for will never arrive. Stop waiting for it.
782 resetPendingAppSwitchLocked(false);
783 isAppSwitchDue = false;
784 }
785
786 // Synthesize a key repeat if appropriate.
787 if (mKeyRepeatState.lastKeyEntry) {
788 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
789 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
790 } else {
791 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
792 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
793 }
794 }
795 }
796
797 // Nothing to do if there is no pending event.
798 if (!mPendingEvent) {
799 return;
800 }
801 } else {
802 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700803 mPendingEvent = mInboundQueue.front();
804 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 traceInboundQueueLengthLocked();
806 }
807
808 // Poke user activity for this event.
809 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700810 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 }
813
814 // Now we have an event to dispatch.
815 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700816 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700818 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700822 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
824
825 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700826 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828
829 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700830 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 const ConfigurationChangedEntry& typedEntry =
832 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 break;
836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700838 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 const DeviceResetEntry& typedEntry =
840 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700841 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700842 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 break;
844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100846 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700847 std::shared_ptr<FocusEntry> typedEntry =
848 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100849 dispatchFocusLocked(currentTime, typedEntry);
850 done = true;
851 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
852 break;
853 }
854
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700855 case EventEntry::Type::TOUCH_MODE_CHANGED: {
856 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
857 dispatchTouchModeChangeLocked(currentTime, typedEntry);
858 done = true;
859 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
860 break;
861 }
862
Prabir Pradhan99987712020-11-10 18:43:05 -0800863 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
864 const auto typedEntry =
865 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
866 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
867 done = true;
868 break;
869 }
870
arthurhungb89ccb02020-12-30 16:19:01 +0800871 case EventEntry::Type::DRAG: {
872 std::shared_ptr<DragEntry> typedEntry =
873 std::static_pointer_cast<DragEntry>(mPendingEvent);
874 dispatchDragLocked(currentTime, typedEntry);
875 done = true;
876 break;
877 }
878
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700879 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 resetPendingAppSwitchLocked(true);
884 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 } else if (dropReason == DropReason::NOT_DROPPED) {
886 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 }
888 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700889 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700890 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700892 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
893 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700895 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 break;
897 }
898
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700899 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700900 std::shared_ptr<MotionEntry> motionEntry =
901 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
903 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700905 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700906 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700908 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
909 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700911 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 }
Chris Yef59a2f42020-10-16 12:55:26 -0700914
915 case EventEntry::Type::SENSOR: {
916 std::shared_ptr<SensorEntry> sensorEntry =
917 std::static_pointer_cast<SensorEntry>(mPendingEvent);
918 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
919 dropReason = DropReason::APP_SWITCH;
920 }
921 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
922 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
923 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
924 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
925 dropReason = DropReason::STALE;
926 }
927 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
928 done = true;
929 break;
930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
932
933 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700934 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700935 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 }
Michael Wright3a981722015-06-10 15:26:13 +0100937 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938
939 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 }
942}
943
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800944bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
945 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
946}
947
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700948/**
949 * Return true if the events preceding this incoming motion event should be dropped
950 * Return false otherwise (the default behaviour)
951 */
952bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700953 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700954 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700955
956 // Optimize case where the current application is unresponsive and the user
957 // decides to touch a window in a different application.
958 // If the application takes too long to catch up then we drop all events preceding
959 // the touch into the other window.
960 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 int32_t displayId = motionEntry.displayId;
962 int32_t x = static_cast<int32_t>(
963 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
964 int32_t y = static_cast<int32_t>(
965 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700966
967 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500968 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700969 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700970 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700971 touchedWindowHandle->getApplicationToken() !=
972 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700973 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700974 ALOGI("Pruning input queue because user touched a different application while waiting "
975 "for %s",
976 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700977 return true;
978 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700979
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800980 // Alternatively, maybe there's a spy window that could handle this event.
981 const std::vector<sp<WindowInfoHandle>> touchedSpies =
982 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
983 for (const auto& windowHandle : touchedSpies) {
984 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000985 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800986 // This spy window could take more input. Drop all events preceding this
987 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700988 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800989 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700990 mAwaitedFocusedApplication->getName().c_str());
991 return true;
992 }
993 }
994 }
995
996 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
997 // yet been processed by some connections, the dispatcher will wait for these motion
998 // events to be processed before dispatching the key event. This is because these motion events
999 // may cause a new window to be launched, which the user might expect to receive focus.
1000 // To prevent waiting forever for such events, just send the key to the currently focused window
1001 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1002 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1003 "just send the pending key event to the focused window.");
1004 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001005 }
1006 return false;
1007}
1008
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001009bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001010 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001011 mInboundQueue.push_back(std::move(newEntry));
1012 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 traceInboundQueueLengthLocked();
1014
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001015 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001016 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 // Optimize app switch latency.
1018 // If the application takes too long to catch up then we drop all events preceding
1019 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001022 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001024 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001026 if (DEBUG_APP_SWITCH) {
1027 ALOGD("App switch is pending!");
1028 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001029 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 mAppSwitchSawKeyDown = false;
1031 needWake = true;
1032 }
1033 }
1034 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001035
1036 // If a new up event comes in, and the pending event with same key code has been asked
1037 // to try again later because of the policy. We have to reset the intercept key wake up
1038 // time for it may have been handled in the policy and could be dropped.
1039 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1040 mPendingEvent->type == EventEntry::Type::KEY) {
1041 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1042 if (pendingKey.keyCode == keyEntry.keyCode &&
1043 pendingKey.interceptKeyResult ==
1044 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1045 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1046 pendingKey.interceptKeyWakeupTime = 0;
1047 needWake = true;
1048 }
1049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 break;
1051 }
1052
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001053 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001054 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1055 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001056 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001060 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001061 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1062 break;
1063 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001064 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001065 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001066 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001067 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001068 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1069 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001070 // nothing to do
1071 break;
1072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074
1075 return needWake;
1076}
1077
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001078void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001079 // Do not store sensor event in recent queue to avoid flooding the queue.
1080 if (entry->type != EventEntry::Type::SENSOR) {
1081 mRecentQueue.push_back(entry);
1082 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001083 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001084 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086}
1087
chaviw98318de2021-05-19 16:45:23 -05001088sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1089 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001090 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001091 bool addOutsideTargets,
1092 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001093 if (addOutsideTargets && touchState == nullptr) {
1094 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001097 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001098 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001099 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001100 continue;
1101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001103 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001104 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001105 return windowHandle;
1106 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001107
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001108 if (addOutsideTargets &&
1109 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001110 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1111 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 }
1113 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001114 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115}
1116
Prabir Pradhand65552b2021-10-07 11:23:50 -07001117std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1118 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001119 // Traverse windows from front to back and gather the touched spy windows.
1120 std::vector<sp<WindowInfoHandle>> spyWindows;
1121 const auto& windowHandles = getWindowHandlesLocked(displayId);
1122 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1123 const WindowInfo& info = *windowHandle->getInfo();
1124
Prabir Pradhand65552b2021-10-07 11:23:50 -07001125 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001126 continue;
1127 }
1128 if (!info.isSpy()) {
1129 // The first touched non-spy window was found, so return the spy windows touched so far.
1130 return spyWindows;
1131 }
1132 spyWindows.push_back(windowHandle);
1133 }
1134 return spyWindows;
1135}
1136
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001137void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138 const char* reason;
1139 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001140 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001141 if (DEBUG_INBOUND_EVENT_DETAILS) {
1142 ALOGD("Dropped event because policy consumed it.");
1143 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 reason = "inbound event was dropped because the policy consumed it";
1145 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 case DropReason::DISABLED:
1147 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 ALOGI("Dropped event because input dispatch is disabled.");
1149 }
1150 reason = "inbound event was dropped because input dispatch is disabled";
1151 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001152 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 ALOGI("Dropped event because of pending overdue app switch.");
1154 reason = "inbound event was dropped because of pending overdue app switch";
1155 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 ALOGI("Dropped event because the current application is not responding and the user "
1158 "has started interacting with a different application.");
1159 reason = "inbound event was dropped because the current application is not responding "
1160 "and the user has started interacting with a different application";
1161 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001162 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 ALOGI("Dropped event because it is stale.");
1164 reason = "inbound event was dropped because it is stale";
1165 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001166 case DropReason::NO_POINTER_CAPTURE:
1167 ALOGI("Dropped event because there is no window with Pointer Capture.");
1168 reason = "inbound event was dropped because there is no window with Pointer Capture";
1169 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001170 case DropReason::NOT_DROPPED: {
1171 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001177 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1179 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001182 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001183 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1184 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001185 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1186 synthesizeCancelationEventsForAllConnectionsLocked(options);
1187 } else {
1188 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1189 synthesizeCancelationEventsForAllConnectionsLocked(options);
1190 }
1191 break;
1192 }
Chris Yef59a2f42020-10-16 12:55:26 -07001193 case EventEntry::Type::SENSOR: {
1194 break;
1195 }
arthurhungb89ccb02020-12-30 16:19:01 +08001196 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1197 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001198 break;
1199 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001200 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001201 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001202 case EventEntry::Type::CONFIGURATION_CHANGED:
1203 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001204 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001205 break;
1206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
1208}
1209
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001210static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1212 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213}
1214
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001215bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1216 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1217 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1218 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219}
1220
1221bool InputDispatcher::isAppSwitchPendingLocked() {
1222 return mAppSwitchDueTime != LONG_LONG_MAX;
1223}
1224
1225void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1226 mAppSwitchDueTime = LONG_LONG_MAX;
1227
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001228 if (DEBUG_APP_SWITCH) {
1229 if (handled) {
1230 ALOGD("App switch has arrived.");
1231 } else {
1232 ALOGD("App switch was abandoned.");
1233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001238 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239}
1240
Prabir Pradhancef936d2021-07-21 16:17:52 +00001241bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 return false;
1244 }
1245
1246 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001247 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001248 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001249 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1250 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001251 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 return true;
1253}
1254
Prabir Pradhancef936d2021-07-21 16:17:52 +00001255void InputDispatcher::postCommandLocked(Command&& command) {
1256 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257}
1258
1259void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001260 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001262 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 releaseInboundEventLocked(entry);
1264 }
1265 traceInboundQueueLengthLocked();
1266}
1267
1268void InputDispatcher::releasePendingEventLocked() {
1269 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001271 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273}
1274
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001277 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001278 if (DEBUG_DISPATCH_CYCLE) {
1279 ALOGD("Injected inbound event was dropped.");
1280 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 }
1283 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001284 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 }
1286 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287}
1288
1289void InputDispatcher::resetKeyRepeatLocked() {
1290 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001291 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 }
1293}
1294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1296 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297
Michael Wright2e732952014-09-24 13:26:59 -07001298 uint32_t policyFlags = entry->policyFlags &
1299 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 std::shared_ptr<KeyEntry> newEntry =
1302 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1303 entry->source, entry->displayId, policyFlags, entry->action,
1304 entry->flags, entry->keyCode, entry->scanCode,
1305 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 newEntry->syntheticRepeat = true;
1308 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001310 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311}
1312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001315 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1316 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318
1319 // Reset key repeating in case a keyboard device was added or removed or something.
1320 resetKeyRepeatLocked();
1321
1322 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001323 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1324 scoped_unlock unlock(mLock);
1325 mPolicy->notifyConfigurationChanged(eventTime);
1326 };
1327 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 return true;
1329}
1330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1332 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001333 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1334 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1335 entry.deviceId);
1336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337
liushenxiang42232912021-05-21 20:24:09 +08001338 // Reset key repeating in case a keyboard device was disabled or enabled.
1339 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1340 resetKeyRepeatLocked();
1341 }
1342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001343 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001344 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 synthesizeCancelationEventsForAllConnectionsLocked(options);
1346 return true;
1347}
1348
Vishnu Nairad321cd2020-08-20 16:40:21 -07001349void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001350 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001351 if (mPendingEvent != nullptr) {
1352 // Move the pending event to the front of the queue. This will give the chance
1353 // for the pending event to get dispatched to the newly focused window
1354 mInboundQueue.push_front(mPendingEvent);
1355 mPendingEvent = nullptr;
1356 }
1357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358 std::unique_ptr<FocusEntry> focusEntry =
1359 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1360 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001361
1362 // This event should go to the front of the queue, but behind all other focus events
1363 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001364 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001365 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001366 [](const std::shared_ptr<EventEntry>& event) {
1367 return event->type == EventEntry::Type::FOCUS;
1368 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001369
1370 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001371 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001372}
1373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001374void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001375 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001376 if (channel == nullptr) {
1377 return; // Window has gone away
1378 }
1379 InputTarget target;
1380 target.inputChannel = channel;
1381 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1382 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001383 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1384 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001385 std::string reason = std::string("reason=").append(entry->reason);
1386 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001387 dispatchEventLocked(currentTime, entry, {target});
1388}
1389
Prabir Pradhan99987712020-11-10 18:43:05 -08001390void InputDispatcher::dispatchPointerCaptureChangedLocked(
1391 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1392 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 dropReason = DropReason::NOT_DROPPED;
1394
Prabir Pradhan99987712020-11-10 18:43:05 -08001395 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001396 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001397
1398 if (entry->pointerCaptureRequest.enable) {
1399 // Enable Pointer Capture.
1400 if (haveWindowWithPointerCapture &&
1401 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1402 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1403 "to the window.");
1404 }
1405 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001406 // This can happen if a window requests capture and immediately releases capture.
1407 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001408 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001409 return;
1410 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001411 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1412 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1413 return;
1414 }
1415
Vishnu Nairc519ff72021-01-21 08:23:08 -08001416 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001417 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1418 mWindowTokenWithPointerCapture = token;
1419 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001420 // Disable Pointer Capture.
1421 // We do not check if the sequence number matches for requests to disable Pointer Capture
1422 // for two reasons:
1423 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1424 // to disable capture with the same sequence number: one generated by
1425 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1426 // Capture being disabled in InputReader.
1427 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1428 // actual Pointer Capture state that affects events being generated by input devices is
1429 // in InputReader.
1430 if (!haveWindowWithPointerCapture) {
1431 // Pointer capture was already forcefully disabled because of focus change.
1432 dropReason = DropReason::NOT_DROPPED;
1433 return;
1434 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001435 token = mWindowTokenWithPointerCapture;
1436 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001437 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001438 setPointerCaptureLocked(false);
1439 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001440 }
1441
1442 auto channel = getInputChannelLocked(token);
1443 if (channel == nullptr) {
1444 // Window has gone away, clean up Pointer Capture state.
1445 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001446 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001447 setPointerCaptureLocked(false);
1448 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001449 return;
1450 }
1451 InputTarget target;
1452 target.inputChannel = channel;
1453 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1454 entry->dispatchInProgress = true;
1455 dispatchEventLocked(currentTime, entry, {target});
1456
1457 dropReason = DropReason::NOT_DROPPED;
1458}
1459
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001460void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1461 const std::shared_ptr<TouchModeEntry>& entry) {
1462 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1463 getWindowHandlesLocked(mFocusedDisplayId);
1464 if (windowHandles.empty()) {
1465 return;
1466 }
1467 const std::vector<InputTarget> inputTargets =
1468 getInputTargetsFromWindowHandlesLocked(windowHandles);
1469 if (inputTargets.empty()) {
1470 return;
1471 }
1472 entry->dispatchInProgress = true;
1473 dispatchEventLocked(currentTime, entry, inputTargets);
1474}
1475
1476std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1477 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1478 std::vector<InputTarget> inputTargets;
1479 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1480 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1481 const sp<IBinder>& token = handle->getToken();
1482 if (token == nullptr) {
1483 continue;
1484 }
1485 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1486 if (channel == nullptr) {
1487 continue; // Window has gone away
1488 }
1489 InputTarget target;
1490 target.inputChannel = channel;
1491 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1492 inputTargets.push_back(target);
1493 }
1494 return inputTargets;
1495}
1496
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001497bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001498 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001500 if (!entry->dispatchInProgress) {
1501 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1502 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1503 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1504 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001505 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 // We have seen two identical key downs in a row which indicates that the device
1507 // driver is automatically generating key repeats itself. We take note of the
1508 // repeat here, but we disable our own next key repeat timer since it is clear that
1509 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001510 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1511 // Make sure we don't get key down from a different device. If a different
1512 // device Id has same key pressed down, the new device Id will replace the
1513 // current one to hold the key repeat with repeat count reset.
1514 // In the future when got a KEY_UP on the device id, drop it and do not
1515 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1517 resetKeyRepeatLocked();
1518 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1519 } else {
1520 // Not a repeat. Save key down state in case we do see a repeat later.
1521 resetKeyRepeatLocked();
1522 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1523 }
1524 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001525 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1526 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001527 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001528 if (DEBUG_INBOUND_EVENT_DETAILS) {
1529 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1530 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001531 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 resetKeyRepeatLocked();
1533 }
1534
1535 if (entry->repeatCount == 1) {
1536 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1537 } else {
1538 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1539 }
1540
1541 entry->dispatchInProgress = true;
1542
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001543 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
1546 // Handle case where the policy asked us to try again later last time.
1547 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1548 if (currentTime < entry->interceptKeyWakeupTime) {
1549 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1550 *nextWakeupTime = entry->interceptKeyWakeupTime;
1551 }
1552 return false; // wait until next wakeup
1553 }
1554 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1555 entry->interceptKeyWakeupTime = 0;
1556 }
1557
1558 // Give the policy a chance to intercept the key.
1559 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1560 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001561 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001562 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001563
1564 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1565 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1566 };
1567 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 return false; // wait for the command to run
1569 } else {
1570 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1571 }
1572 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001573 if (*dropReason == DropReason::NOT_DROPPED) {
1574 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 }
1576 }
1577
1578 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001579 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1582 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001583 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 return true;
1585 }
1586
1587 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001588 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001590 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 return false;
1593 }
1594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001596 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 return true;
1598 }
1599
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001600 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001601 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602
1603 // Dispatch the key.
1604 dispatchEventLocked(currentTime, entry, inputTargets);
1605 return true;
1606}
1607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001609 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1610 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1611 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1612 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1613 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1614 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1615 entry.metaState, entry.repeatCount, entry.downTime);
1616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617}
1618
Prabir Pradhancef936d2021-07-21 16:17:52 +00001619void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1620 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001621 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001622 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1623 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1624 "source=0x%x, sensorType=%s",
1625 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001626 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001627 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001628 auto command = [this, entry]() REQUIRES(mLock) {
1629 scoped_unlock unlock(mLock);
1630
1631 if (entry->accuracyChanged) {
1632 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1633 }
1634 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1635 entry->hwTimestamp, entry->values);
1636 };
1637 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001638}
1639
1640bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001641 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1642 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001643 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001644 }
Chris Yef59a2f42020-10-16 12:55:26 -07001645 { // acquire lock
1646 std::scoped_lock _l(mLock);
1647
1648 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1649 std::shared_ptr<EventEntry> entry = *it;
1650 if (entry->type == EventEntry::Type::SENSOR) {
1651 it = mInboundQueue.erase(it);
1652 releaseInboundEventLocked(entry);
1653 }
1654 }
1655 }
1656 return true;
1657}
1658
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001659bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001660 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001661 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 entry->dispatchInProgress = true;
1665
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001666 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
1668
1669 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001670 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001671 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001672 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1673 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return true;
1675 }
1676
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001677 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678
1679 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001680 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
1682 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001683 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 if (isPointerEvent) {
1685 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001686 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001687 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001688 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 } else {
1690 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001691 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001692 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001694 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 return false;
1696 }
1697
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001698 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001699 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001700 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1701 return true;
1702 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001703 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001704 CancelationOptions::Mode mode(isPointerEvent
1705 ? CancelationOptions::CANCEL_POINTER_EVENTS
1706 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1707 CancelationOptions options(mode, "input event injection failed");
1708 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 return true;
1710 }
1711
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001712 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001713 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714
1715 // Dispatch the motion.
1716 if (conflictingPointerActions) {
1717 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001718 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 synthesizeCancelationEventsForAllConnectionsLocked(options);
1720 }
1721 dispatchEventLocked(currentTime, entry, inputTargets);
1722 return true;
1723}
1724
chaviw98318de2021-05-19 16:45:23 -05001725void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001726 bool isExiting, const MotionEntry& motionEntry) {
1727 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1728 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1729 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1730 PointerCoords pointerCoords;
1731 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1732 pointerCoords.transform(windowHandle->getInfo()->transform);
1733
1734 std::unique_ptr<DragEntry> dragEntry =
1735 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1736 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1737 pointerCoords.getY());
1738
1739 enqueueInboundEventLocked(std::move(dragEntry));
1740}
1741
1742void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1743 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1744 if (channel == nullptr) {
1745 return; // Window has gone away
1746 }
1747 InputTarget target;
1748 target.inputChannel = channel;
1749 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1750 entry->dispatchInProgress = true;
1751 dispatchEventLocked(currentTime, entry, {target});
1752}
1753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001755 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1756 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1757 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001758 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001759 "metaState=0x%x, buttonState=0x%x,"
1760 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1761 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001762 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1763 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1764 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001766 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1767 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1768 "x=%f, y=%f, pressure=%f, size=%f, "
1769 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1770 "orientation=%f",
1771 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1772 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1773 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1774 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1775 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1776 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1777 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1778 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1779 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1780 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783}
1784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001785void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1786 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001788 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001789 if (DEBUG_DISPATCH_CYCLE) {
1790 ALOGD("dispatchEventToCurrentInputTargets");
1791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001793 updateInteractionTokensLocked(*eventEntry, inputTargets);
1794
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1796
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001799 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001800 sp<Connection> connection =
1801 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001802 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001803 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001805 if (DEBUG_FOCUS) {
1806 ALOGD("Dropping event delivery to target with channel '%s' because it "
1807 "is no longer registered with the input dispatcher.",
1808 inputTarget.inputChannel->getName().c_str());
1809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 }
1811 }
1812}
1813
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001814void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1815 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1816 // If the policy decides to close the app, we will get a channel removal event via
1817 // unregisterInputChannel, and will clean up the connection that way. We are already not
1818 // sending new pointers to the connection when it blocked, but focused events will continue to
1819 // pile up.
1820 ALOGW("Canceling events for %s because it is unresponsive",
1821 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001822 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1824 "application not responding");
1825 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827}
1828
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001830 if (DEBUG_FOCUS) {
1831 ALOGD("Resetting ANR timeouts.");
1832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833
1834 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001835 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001836 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837}
1838
Tiger Huang721e26f2018-07-24 22:26:19 +08001839/**
1840 * Get the display id that the given event should go to. If this event specifies a valid display id,
1841 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1842 * Focused display is the display that the user most recently interacted with.
1843 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001844int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001845 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001846 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001847 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001848 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1849 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001850 break;
1851 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001852 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001853 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1854 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001855 break;
1856 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001857 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001858 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001859 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001860 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001861 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001862 case EventEntry::Type::SENSOR:
1863 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001864 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 return ADISPLAY_ID_NONE;
1866 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001867 }
1868 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1869}
1870
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001871bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1872 const char* focusedWindowName) {
1873 if (mAnrTracker.empty()) {
1874 // already processed all events that we waited for
1875 mKeyIsWaitingForEventsTimeout = std::nullopt;
1876 return false;
1877 }
1878
1879 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1880 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001881 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001882 mKeyIsWaitingForEventsTimeout = currentTime +
1883 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1884 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001885 return true;
1886 }
1887
1888 // We still have pending events, and already started the timer
1889 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1890 return true; // Still waiting
1891 }
1892
1893 // Waited too long, and some connection still hasn't processed all motions
1894 // Just send the key to the focused window
1895 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1896 focusedWindowName);
1897 mKeyIsWaitingForEventsTimeout = std::nullopt;
1898 return false;
1899}
1900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001901InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1902 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1903 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001904 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905
Tiger Huang721e26f2018-07-24 22:26:19 +08001906 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001907 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001908 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001909 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1910
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 // If there is no currently focused window and no focused application
1912 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1914 ALOGI("Dropping %s event because there is no focused window or focused application in "
1915 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001916 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 }
1919
Vishnu Nair062a8672021-09-03 16:07:44 -07001920 // Drop key events if requested by input feature
1921 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1922 return InputEventInjectionResult::FAILED;
1923 }
1924
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001925 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1926 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1927 // start interacting with another application via touch (app switch). This code can be removed
1928 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1929 // an app is expected to have a focused window.
1930 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1931 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1932 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001933 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1934 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1935 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001937 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001938 ALOGW("Waiting because no window has focus but %s may eventually add a "
1939 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001940 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1944 // Already raised ANR. Drop the event
1945 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001946 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001948 } else {
1949 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 }
1952 }
1953
1954 // we have a valid, non-null focused window
1955 resetNoFocusedWindowTimeoutLocked();
1956
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001958 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
1961
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001962 if (focusedWindowHandle->getInfo()->inputConfig.test(
1963 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 }
1967
1968 // If the event is a key event, then we must wait for all previous events to
1969 // complete before delivering it because previous events may have the
1970 // side-effect of transferring focus to a different window and we want to
1971 // ensure that the following keys are sent to the new window.
1972 //
1973 // Suppose the user touches a button in a window then immediately presses "A".
1974 // If the button causes a pop-up window to appear then we want to ensure that
1975 // the "A" key is delivered to the new pop-up window. This is because users
1976 // often anticipate pending UI changes when typing on a keyboard.
1977 // To obtain this behavior, we must serialize key events with respect to all
1978 // prior input events.
1979 if (entry.type == EventEntry::Type::KEY) {
1980 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1981 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001982 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
1985
1986 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001987 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001988 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1989 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990
1991 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001992 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993}
1994
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995/**
1996 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1997 * that are currently unresponsive.
1998 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001999std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2000 const std::vector<Monitor>& monitors) const {
2001 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002002 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002003 [this](const Monitor& monitor) REQUIRES(mLock) {
2004 sp<Connection> connection =
2005 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002006 if (connection == nullptr) {
2007 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002008 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002009 return false;
2010 }
2011 if (!connection->responsive) {
2012 ALOGW("Unresponsive monitor %s will not get the new gesture",
2013 connection->inputChannel->getName().c_str());
2014 return false;
2015 }
2016 return true;
2017 });
2018 return responsiveMonitors;
2019}
2020
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002021InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2022 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2023 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002024 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 enum InjectionPermission {
2026 INJECTION_PERMISSION_UNKNOWN,
2027 INJECTION_PERMISSION_GRANTED,
2028 INJECTION_PERMISSION_DENIED
2029 };
2030
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 // For security reasons, we defer updating the touch state until we are sure that
2032 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002033 const int32_t displayId = entry.displayId;
2034 const int32_t action = entry.action;
2035 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
2037 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002038 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05002040 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2041 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002043 // Copy current touch state into tempTouchState.
2044 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2045 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002046 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002047 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002048 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2049 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002050 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002051 }
2052
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002053 bool isSplit = tempTouchState.split;
2054 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2055 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2056 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002057
2058 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2059 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2060 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2061 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2062 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002063 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 bool wrongDevice = false;
2065 if (newGesture) {
2066 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002067 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002068 ALOGI("Dropping event because a pointer for a different device is already down "
2069 "in display %" PRId32,
2070 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002071 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002072 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 switchedDevice = false;
2074 wrongDevice = true;
2075 goto Failed;
2076 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002077 tempTouchState.reset();
2078 tempTouchState.down = down;
2079 tempTouchState.deviceId = entry.deviceId;
2080 tempTouchState.source = entry.source;
2081 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002083 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002084 ALOGI("Dropping move event because a pointer for a different device is already active "
2085 "in display %" PRId32,
2086 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002087 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002088 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002089 switchedDevice = false;
2090 wrongDevice = true;
2091 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
2093
2094 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2095 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2096
Garfield Tan00f511d2019-06-12 16:55:40 -07002097 int32_t x;
2098 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002099 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002100 // Always dispatch mouse events to cursor position.
2101 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 x = int32_t(entry.xCursorPosition);
2103 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002104 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002105 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2106 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002107 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002108 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002109 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002110 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002111 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002112
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002114 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002115 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2116 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 }
2120
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002121 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002122 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002123 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2124 // New window supports splitting, but we should never split mouse events.
2125 isSplit = !isFromMouse;
2126 } else if (isSplit) {
2127 // New window does not support splitting but we have already split events.
2128 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002129 newTouchedWindowHandle = nullptr;
2130 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002131 } else {
2132 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002133 // be delivered to a new window which supports split touch. Pointers from a mouse device
2134 // should never be split.
2135 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002136 }
2137
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002138 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002140 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2141 newHoverWindowHandle = nullptr;
2142 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002145 }
2146
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002147 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002148 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002149 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002150 // Process the foreground window first so that it is the first to receive the event.
2151 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002152 }
2153
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002154 if (newTouchedWindows.empty()) {
2155 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2156 x, y, displayId);
2157 injectionResult = InputEventInjectionResult::FAILED;
2158 goto Failed;
2159 }
2160
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002161 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2162 const WindowInfo& info = *windowHandle->getInfo();
2163
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002164 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165 ALOGI("Not sending touch event to %s because it is paused",
2166 windowHandle->getName().c_str());
2167 continue;
2168 }
2169
2170 // Ensure the window has a connection and the connection is responsive
2171 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2172 if (!isResponsive) {
2173 ALOGW("Not sending touch gesture to %s because it is not responsive",
2174 windowHandle->getName().c_str());
2175 continue;
2176 }
2177
2178 // Drop events that can't be trusted due to occlusion
2179 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2180 TouchOcclusionInfo occlusionInfo =
2181 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2182 if (!isTouchTrustedLocked(occlusionInfo)) {
2183 if (DEBUG_TOUCH_OCCLUSION) {
2184 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2185 for (const auto& log : occlusionInfo.debugInfo) {
2186 ALOGD("%s", log.c_str());
2187 }
2188 }
2189 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2190 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2191 ALOGW("Dropping untrusted touch event due to %s/%d",
2192 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2193 continue;
2194 }
2195 }
2196 }
2197
2198 // Drop touch events if requested by input feature
2199 if (shouldDropInput(entry, windowHandle)) {
2200 continue;
2201 }
2202
2203 // Set target flags.
2204 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2205
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002206 if (!info.isSpy()) {
2207 // There should only be one new foreground (non-spy) window at this location.
2208 targetFlags |= InputTarget::FLAG_FOREGROUND;
2209 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002210
2211 if (isSplit) {
2212 targetFlags |= InputTarget::FLAG_SPLIT;
2213 }
2214 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2215 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2216 } else if (isWindowObscuredLocked(windowHandle)) {
2217 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2218 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002219
2220 // Update the temporary touch state.
2221 BitSet32 pointerIds;
2222 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002223 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002224 pointerIds.markBit(pointerId);
2225 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002226
2227 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 } else {
2230 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2231
2232 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002233 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002234 if (DEBUG_FOCUS) {
2235 ALOGD("Dropping event because the pointer is not down or we previously "
2236 "dropped the pointer down event in display %" PRId32,
2237 displayId);
2238 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002239 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 goto Failed;
2241 }
2242
arthurhung6d4bed92021-03-17 11:59:33 +08002243 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002244
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002246 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002248 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2249 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250
Prabir Pradhand65552b2021-10-07 11:23:50 -07002251 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002252 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002253 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002254 newTouchedWindowHandle =
2255 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002256
2257 // Drop touch events if requested by input feature
2258 if (newTouchedWindowHandle != nullptr &&
2259 shouldDropInput(entry, newTouchedWindowHandle)) {
2260 newTouchedWindowHandle = nullptr;
2261 }
2262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002263 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2264 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002265 if (DEBUG_FOCUS) {
2266 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2267 oldTouchedWindowHandle->getName().c_str(),
2268 newTouchedWindowHandle->getName().c_str(), displayId);
2269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002271 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2272 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2273 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274
2275 // Make a slippery entrance into the new window.
2276 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002277 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 }
2279
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 int32_t targetFlags =
2281 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 if (isSplit) {
2283 targetFlags |= InputTarget::FLAG_SPLIT;
2284 }
2285 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2286 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002287 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2288 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290
2291 BitSet32 pointerIds;
2292 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002293 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002295 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297 }
2298 }
2299
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002300 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002302 // Let the previous window know that the hover sequence is over, unless we already did
2303 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002304 if (mLastHoverWindowHandle != nullptr &&
2305 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2306 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002307 if (DEBUG_HOVER) {
2308 ALOGD("Sending hover exit event to window %s.",
2309 mLastHoverWindowHandle->getName().c_str());
2310 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2312 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 }
2314
Garfield Tandf26e862020-07-01 20:18:19 -07002315 // Let the new window know that the hover sequence is starting, unless we already did it
2316 // when dispatching it as is to newTouchedWindowHandle.
2317 if (newHoverWindowHandle != nullptr &&
2318 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2319 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002320 if (DEBUG_HOVER) {
2321 ALOGD("Sending hover enter event to window %s.",
2322 newHoverWindowHandle->getName().c_str());
2323 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002324 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2325 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2326 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328 }
2329
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002330 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2331 // of the touched windows we previously found if they became paused or unresponsive or were
2332 // removed.
2333 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2334 [](const TouchedWindow& touchedWindow) {
2335 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2336 touchedWindow.windowHandle->getInfo()->isSpy();
2337 })) {
2338 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2339 displayId);
2340 injectionResult = InputEventInjectionResult::FAILED;
2341 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 }
2343
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002344 // Check permission to inject into all touched foreground windows.
2345 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2346 [this, &entry](const TouchedWindow& touchedWindow) {
2347 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2348 !checkInjectionPermission(touchedWindow.windowHandle,
2349 entry.injectionState);
2350 })) {
2351 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2352 injectionPermission = INJECTION_PERMISSION_DENIED;
2353 goto Failed;
2354 }
2355 // Permission granted to inject into all touched foreground windows.
2356 injectionPermission = INJECTION_PERMISSION_GRANTED;
2357
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 // Check whether windows listening for outside touches are owned by the same UID. If it is
2359 // set the policy flag that we will not reveal coordinate information to this window.
2360 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002361 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002362 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002363 if (foregroundWindowHandle) {
2364 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002365 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002366 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002367 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2368 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2369 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002370 InputTarget::FLAG_ZERO_COORDS,
2371 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374 }
2375 }
2376 }
2377
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 // If this is the first pointer going down and the touched window has a wallpaper
2379 // then also add the touched wallpaper windows so they are locked in for the duration
2380 // of the touch gesture.
2381 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2382 // engine only supports touch events. We would need to add a mechanism similar
2383 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2384 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002385 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002386 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002387 if (foregroundWindowHandle &&
2388 foregroundWindowHandle->getInfo()->inputConfig.test(
2389 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002390 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002391 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002392 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2393 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002394 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002395 windowHandle->getInfo()->inputConfig.test(
2396 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002397 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 .addOrUpdateWindow(windowHandle,
2399 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2400 InputTarget::
2401 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2402 InputTarget::FLAG_DISPATCH_AS_IS,
2403 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405 }
2406 }
2407 }
2408
2409 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002410 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002412 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
2416
2417 // Drop the outside or hover touch windows since we will not care about them
2418 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002419 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
2421Failed:
2422 // Check injection permission once and for all.
2423 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002424 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 injectionPermission = INJECTION_PERMISSION_GRANTED;
2426 } else {
2427 injectionPermission = INJECTION_PERMISSION_DENIED;
2428 }
2429 }
2430
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002431 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2432 return injectionResult;
2433 }
2434
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002436 if (!wrongDevice) {
2437 if (switchedDevice) {
2438 if (DEBUG_FOCUS) {
2439 ALOGD("Conflicting pointer actions: Switched to a different device.");
2440 }
2441 *outConflictingPointerActions = true;
2442 }
2443
2444 if (isHoverAction) {
2445 // Started hovering, therefore no longer down.
2446 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002447 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002448 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2449 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 *outConflictingPointerActions = true;
2452 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002453 tempTouchState.reset();
2454 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2455 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2456 tempTouchState.deviceId = entry.deviceId;
2457 tempTouchState.source = entry.source;
2458 tempTouchState.displayId = displayId;
2459 }
2460 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2461 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2462 // All pointers up or canceled.
2463 tempTouchState.reset();
2464 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2465 // First pointer went down.
2466 if (oldState && oldState->down) {
2467 if (DEBUG_FOCUS) {
2468 ALOGD("Conflicting pointer actions: Down received while already down.");
2469 }
2470 *outConflictingPointerActions = true;
2471 }
2472 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2473 // One pointer went up.
2474 if (isSplit) {
2475 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2476 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002478 for (size_t i = 0; i < tempTouchState.windows.size();) {
2479 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2480 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2481 touchedWindow.pointerIds.clearBit(pointerId);
2482 if (touchedWindow.pointerIds.isEmpty()) {
2483 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2484 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002487 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002489 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002490 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002491
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002492 // Save changes unless the action was scroll in which case the temporary touch
2493 // state was only valid for this one action.
2494 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2495 if (tempTouchState.displayId >= 0) {
2496 mTouchStatesByDisplay[displayId] = tempTouchState;
2497 } else {
2498 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002502 // Update hover state.
2503 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 return injectionResult;
2507}
2508
arthurhung6d4bed92021-03-17 11:59:33 +08002509void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002510 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2511 // have an explicit reason to support it.
2512 constexpr bool isStylus = false;
2513
chaviw98318de2021-05-19 16:45:23 -05002514 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002515 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002516 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002517 if (dropWindow) {
2518 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002519 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002520 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002521 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002522 }
2523 mDragState.reset();
2524}
2525
2526void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2527 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002528 return;
2529 }
2530
arthurhung6d4bed92021-03-17 11:59:33 +08002531 if (!mDragState->isStartDrag) {
2532 mDragState->isStartDrag = true;
2533 mDragState->isStylusButtonDownAtStart =
2534 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2535 }
2536
arthurhungb89ccb02020-12-30 16:19:01 +08002537 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2538 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2539 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2540 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002541 // Handle the special case : stylus button no longer pressed.
2542 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2543 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2544 finishDragAndDrop(entry.displayId, x, y);
2545 return;
2546 }
2547
Prabir Pradhand65552b2021-10-07 11:23:50 -07002548 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2549 // we have an explicit reason to support it.
2550 constexpr bool isStylus = false;
2551
chaviw98318de2021-05-19 16:45:23 -05002552 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002553 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002554 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002555 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002556 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2557 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2558 if (mDragState->dragHoverWindowHandle != nullptr) {
2559 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2560 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002561 }
arthurhung6d4bed92021-03-17 11:59:33 +08002562 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002563 }
2564 // enqueue drag location if needed.
2565 if (hoverWindowHandle != nullptr) {
2566 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2567 }
arthurhung6d4bed92021-03-17 11:59:33 +08002568 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2569 finishDragAndDrop(entry.displayId, x, y);
2570 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002571 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002572 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002573 }
2574}
2575
chaviw98318de2021-05-19 16:45:23 -05002576void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 int32_t targetFlags, BitSet32 pointerIds,
2578 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002579 std::vector<InputTarget>::iterator it =
2580 std::find_if(inputTargets.begin(), inputTargets.end(),
2581 [&windowHandle](const InputTarget& inputTarget) {
2582 return inputTarget.inputChannel->getConnectionToken() ==
2583 windowHandle->getToken();
2584 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002585
chaviw98318de2021-05-19 16:45:23 -05002586 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002587
2588 if (it == inputTargets.end()) {
2589 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002590 std::shared_ptr<InputChannel> inputChannel =
2591 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002592 if (inputChannel == nullptr) {
2593 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2594 return;
2595 }
2596 inputTarget.inputChannel = inputChannel;
2597 inputTarget.flags = targetFlags;
2598 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002599 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2600 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002601 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002602 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002603 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002604 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002605 inputTargets.push_back(inputTarget);
2606 it = inputTargets.end() - 1;
2607 }
2608
2609 ALOG_ASSERT(it->flags == targetFlags);
2610 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2611
chaviw1ff3d1e2020-07-01 15:53:47 -07002612 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613}
2614
Michael Wright3dd60e22019-03-27 22:06:44 +00002615void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002616 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002617 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2618 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002619
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002620 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2621 InputTarget target;
2622 target.inputChannel = monitor.inputChannel;
2623 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2624 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2625 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002626 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002627 target.setDefaultPointerTransform(target.displayTransform);
2628 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 }
2630}
2631
chaviw98318de2021-05-19 16:45:23 -05002632bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002633 const InjectionState* injectionState) {
2634 if (injectionState &&
2635 (windowHandle == nullptr ||
2636 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2637 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002638 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002640 "owned by uid %d",
2641 injectionState->injectorPid, injectionState->injectorUid,
2642 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 } else {
2644 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002645 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 }
2647 return false;
2648 }
2649 return true;
2650}
2651
Robert Carrc9bf1d32020-04-13 17:21:08 -07002652/**
2653 * Indicate whether one window handle should be considered as obscuring
2654 * another window handle. We only check a few preconditions. Actually
2655 * checking the bounds is left to the caller.
2656 */
chaviw98318de2021-05-19 16:45:23 -05002657static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2658 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002659 // Compare by token so cloned layers aren't counted
2660 if (haveSameToken(windowHandle, otherHandle)) {
2661 return false;
2662 }
2663 auto info = windowHandle->getInfo();
2664 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002665 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002666 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002667 } else if (otherInfo->alpha == 0 &&
2668 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002669 // Those act as if they were invisible, so we don't need to flag them.
2670 // We do want to potentially flag touchable windows even if they have 0
2671 // opacity, since they can consume touches and alter the effects of the
2672 // user interaction (eg. apps that rely on
2673 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2674 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2675 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002676 } else if (info->ownerUid == otherInfo->ownerUid) {
2677 // If ownerUid is the same we don't generate occlusion events as there
2678 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002679 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002680 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002681 return false;
2682 } else if (otherInfo->displayId != info->displayId) {
2683 return false;
2684 }
2685 return true;
2686}
2687
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002688/**
2689 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2690 * untrusted, one should check:
2691 *
2692 * 1. If result.hasBlockingOcclusion is true.
2693 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2694 * BLOCK_UNTRUSTED.
2695 *
2696 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2697 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2698 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2699 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2700 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2701 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2702 *
2703 * If neither of those is true, then it means the touch can be allowed.
2704 */
2705InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002706 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2707 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002708 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002709 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002710 TouchOcclusionInfo info;
2711 info.hasBlockingOcclusion = false;
2712 info.obscuringOpacity = 0;
2713 info.obscuringUid = -1;
2714 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002715 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002716 if (windowHandle == otherHandle) {
2717 break; // All future windows are below us. Exit early.
2718 }
chaviw98318de2021-05-19 16:45:23 -05002719 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002720 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2721 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002722 if (DEBUG_TOUCH_OCCLUSION) {
2723 info.debugInfo.push_back(
2724 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2725 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002726 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2727 // we perform the checks below to see if the touch can be propagated or not based on the
2728 // window's touch occlusion mode
2729 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2730 info.hasBlockingOcclusion = true;
2731 info.obscuringUid = otherInfo->ownerUid;
2732 info.obscuringPackage = otherInfo->packageName;
2733 break;
2734 }
2735 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2736 uint32_t uid = otherInfo->ownerUid;
2737 float opacity =
2738 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2739 // Given windows A and B:
2740 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2741 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2742 opacityByUid[uid] = opacity;
2743 if (opacity > info.obscuringOpacity) {
2744 info.obscuringOpacity = opacity;
2745 info.obscuringUid = uid;
2746 info.obscuringPackage = otherInfo->packageName;
2747 }
2748 }
2749 }
2750 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002751 if (DEBUG_TOUCH_OCCLUSION) {
2752 info.debugInfo.push_back(
2753 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2754 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002755 return info;
2756}
2757
chaviw98318de2021-05-19 16:45:23 -05002758std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002759 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002760 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2761 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2762 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2763 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002764 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2765 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2766 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2767 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2768 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002769 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002770 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002771}
2772
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002773bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2774 if (occlusionInfo.hasBlockingOcclusion) {
2775 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2776 occlusionInfo.obscuringUid);
2777 return false;
2778 }
2779 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2780 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2781 "%.2f, maximum allowed = %.2f)",
2782 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2783 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2784 return false;
2785 }
2786 return true;
2787}
2788
chaviw98318de2021-05-19 16:45:23 -05002789bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002792 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2793 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002794 if (windowHandle == otherHandle) {
2795 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 }
chaviw98318de2021-05-19 16:45:23 -05002797 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002798 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002799 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 return true;
2801 }
2802 }
2803 return false;
2804}
2805
chaviw98318de2021-05-19 16:45:23 -05002806bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002807 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002808 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2809 const WindowInfo* windowInfo = windowHandle->getInfo();
2810 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002811 if (windowHandle == otherHandle) {
2812 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002813 }
chaviw98318de2021-05-19 16:45:23 -05002814 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002815 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002816 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002817 return true;
2818 }
2819 }
2820 return false;
2821}
2822
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002823std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002824 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002825 if (applicationHandle != nullptr) {
2826 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002827 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 } else {
2829 return applicationHandle->getName();
2830 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002831 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002832 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002834 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 }
2836}
2837
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002838void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002839 if (!isUserActivityEvent(eventEntry)) {
2840 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002841 return;
2842 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002843 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002844 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002845 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002846 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002847 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002848 if (DEBUG_DISPATCH_CYCLE) {
2849 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 return;
2852 }
2853 }
2854
2855 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002856 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002857 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002858 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2859 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 return;
2861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002863 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 eventType = USER_ACTIVITY_EVENT_TOUCH;
2865 }
2866 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002868 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002869 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2870 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 return;
2872 }
2873 eventType = USER_ACTIVITY_EVENT_BUTTON;
2874 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002876 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002877 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002878 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002879 break;
2880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 }
2882
Prabir Pradhancef936d2021-07-21 16:17:52 +00002883 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2884 REQUIRES(mLock) {
2885 scoped_unlock unlock(mLock);
2886 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2887 };
2888 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889}
2890
2891void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002893 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002894 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002895 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002897 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002898 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002899 ATRACE_NAME(message.c_str());
2900 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002901 if (DEBUG_DISPATCH_CYCLE) {
2902 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2903 "globalScaleFactor=%f, pointerIds=0x%x %s",
2904 connection->getInputChannelName().c_str(), inputTarget.flags,
2905 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2906 inputTarget.getPointerInfoString().c_str());
2907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
2909 // Skip this event if the connection status is not normal.
2910 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002911 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002912 if (DEBUG_DISPATCH_CYCLE) {
2913 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002914 connection->getInputChannelName().c_str(),
2915 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 return;
2918 }
2919
2920 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002921 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2922 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2923 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002924 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002927 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002928 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002929 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 if (!splitMotionEntry) {
2931 return; // split event was dropped
2932 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002933 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2934 std::string reason = std::string("reason=pointer cancel on split window");
2935 android_log_event_list(LOGTAG_INPUT_CANCEL)
2936 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2937 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002938 if (DEBUG_FOCUS) {
2939 ALOGD("channel '%s' ~ Split motion event.",
2940 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002941 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002942 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002943 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2944 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 return;
2946 }
2947 }
2948
2949 // Not splitting. Enqueue dispatch entries for the event as is.
2950 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2951}
2952
2953void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002956 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002957 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002959 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002960 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002961 ATRACE_NAME(message.c_str());
2962 }
2963
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002964 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965
2966 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002971 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002973 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002975 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002977 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979
2980 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002981 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 startDispatchCycleLocked(currentTime, connection);
2983 }
2984}
2985
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002987 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002988 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002990 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2992 connection->getInputChannelName().c_str(),
2993 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002994 ATRACE_NAME(message.c_str());
2995 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002996 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 if (!(inputTargetFlags & dispatchMode)) {
2998 return;
2999 }
3000 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3001
3002 // This is a new event.
3003 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003004 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003005 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003007 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3008 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003009 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003011 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003012 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003013 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003014 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003015 dispatchEntry->resolvedAction = keyEntry.action;
3016 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003018 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3019 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003020 if (DEBUG_DISPATCH_CYCLE) {
3021 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3022 "event",
3023 connection->getInputChannelName().c_str());
3024 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003025 return; // skip the inconsistent event
3026 }
3027 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003030 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003031 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003032 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3033 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3034 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3035 static_cast<int32_t>(IdGenerator::Source::OTHER);
3036 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3039 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3040 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3041 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3042 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3043 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3044 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3045 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3046 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3047 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003048 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003049 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 }
3051 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003052 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3053 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003054 if (DEBUG_DISPATCH_CYCLE) {
3055 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3056 "enter event",
3057 connection->getInputChannelName().c_str());
3058 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003059 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3060 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003064 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3066 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3067 }
3068 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3069 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3073 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003074 if (DEBUG_DISPATCH_CYCLE) {
3075 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3076 "event",
3077 connection->getInputChannelName().c_str());
3078 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 return; // skip the inconsistent event
3080 }
3081
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003082 dispatchEntry->resolvedEventId =
3083 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3084 ? mIdGenerator.nextId()
3085 : motionEntry.id;
3086 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3087 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3088 ") to MotionEvent(id=0x%" PRIx32 ").",
3089 motionEntry.id, dispatchEntry->resolvedEventId);
3090 ATRACE_NAME(message.c_str());
3091 }
3092
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003093 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3094 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3095 // Skip reporting pointer down outside focus to the policy.
3096 break;
3097 }
3098
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003099 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003100 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101
3102 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003104 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003105 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003106 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3107 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003108 break;
3109 }
Chris Yef59a2f42020-10-16 12:55:26 -07003110 case EventEntry::Type::SENSOR: {
3111 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3112 break;
3113 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003114 case EventEntry::Type::CONFIGURATION_CHANGED:
3115 case EventEntry::Type::DEVICE_RESET: {
3116 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003117 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003118 break;
3119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 }
3121
3122 // Remember that we are waiting for this dispatch to complete.
3123 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003124 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 }
3126
3127 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003128 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003129 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003130}
3131
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003132/**
3133 * This function is purely for debugging. It helps us understand where the user interaction
3134 * was taking place. For example, if user is touching launcher, we will see a log that user
3135 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3136 * We will see both launcher and wallpaper in that list.
3137 * Once the interaction with a particular set of connections starts, no new logs will be printed
3138 * until the set of interacted connections changes.
3139 *
3140 * The following items are skipped, to reduce the logspam:
3141 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3142 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3143 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3144 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3145 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003146 */
3147void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3148 const std::vector<InputTarget>& targets) {
3149 // Skip ACTION_UP events, and all events other than keys and motions
3150 if (entry.type == EventEntry::Type::KEY) {
3151 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3152 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3153 return;
3154 }
3155 } else if (entry.type == EventEntry::Type::MOTION) {
3156 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3157 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3158 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3159 return;
3160 }
3161 } else {
3162 return; // Not a key or a motion
3163 }
3164
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003165 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003166 std::vector<sp<Connection>> newConnections;
3167 for (const InputTarget& target : targets) {
3168 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3169 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3170 continue; // Skip windows that receive ACTION_OUTSIDE
3171 }
3172
3173 sp<IBinder> token = target.inputChannel->getConnectionToken();
3174 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003175 if (connection == nullptr) {
3176 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003177 }
3178 newConnectionTokens.insert(std::move(token));
3179 newConnections.emplace_back(connection);
3180 }
3181 if (newConnectionTokens == mInteractionConnectionTokens) {
3182 return; // no change
3183 }
3184 mInteractionConnectionTokens = newConnectionTokens;
3185
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003186 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003187 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003188 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003189 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003190 std::string message = "Interaction with: " + targetList;
3191 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003192 message += "<none>";
3193 }
3194 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3195}
3196
chaviwfd6d3512019-03-25 13:23:49 -07003197void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003198 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003199 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003200 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3201 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003202 return;
3203 }
3204
Vishnu Nairc519ff72021-01-21 08:23:08 -08003205 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003206 if (focusedToken == token) {
3207 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003208 return;
3209 }
3210
Prabir Pradhancef936d2021-07-21 16:17:52 +00003211 auto command = [this, token]() REQUIRES(mLock) {
3212 scoped_unlock unlock(mLock);
3213 mPolicy->onPointerDownOutsideFocus(token);
3214 };
3215 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216}
3217
3218void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003220 if (ATRACE_ENABLED()) {
3221 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003223 ATRACE_NAME(message.c_str());
3224 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003225 if (DEBUG_DISPATCH_CYCLE) {
3226 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003229 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003230 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003232 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003233 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234
3235 // Publish the event.
3236 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3238 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003239 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3241 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003244 status = connection->inputPublisher
3245 .publishKeyEvent(dispatchEntry->seq,
3246 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3247 keyEntry.source, keyEntry.displayId,
3248 std::move(hmac), dispatchEntry->resolvedAction,
3249 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3250 keyEntry.scanCode, keyEntry.metaState,
3251 keyEntry.repeatCount, keyEntry.downTime,
3252 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 }
3255
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003256 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261
chaviw82357092020-01-28 13:13:06 -08003262 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003263 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3265 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003266 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003267 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3268 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003269 // Don't apply window scale here since we don't want scale to affect raw
3270 // coordinates. The scale will be sent back to the client and applied
3271 // later when requesting relative coordinates.
3272 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3273 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 }
3275 usingCoords = scaledCoords;
3276 }
3277 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003278 // We don't want the dispatch target to know.
3279 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003280 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003281 scaledCoords[i].clear();
3282 }
3283 usingCoords = scaledCoords;
3284 }
3285 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003287 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288
3289 // Publish the motion event.
3290 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003291 .publishMotionEvent(dispatchEntry->seq,
3292 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 motionEntry.deviceId, motionEntry.source,
3294 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003295 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003298 motionEntry.edgeFlags, motionEntry.metaState,
3299 motionEntry.buttonState,
3300 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003301 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003302 motionEntry.xPrecision, motionEntry.yPrecision,
3303 motionEntry.xCursorPosition,
3304 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003305 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003306 motionEntry.downTime, motionEntry.eventTime,
3307 motionEntry.pointerCount,
3308 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 break;
3310 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003311
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003312 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003314 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003316 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003317 break;
3318 }
3319
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003320 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3321 const TouchModeEntry& touchModeEntry =
3322 static_cast<const TouchModeEntry&>(eventEntry);
3323 status = connection->inputPublisher
3324 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3325 touchModeEntry.inTouchMode);
3326
3327 break;
3328 }
3329
Prabir Pradhan99987712020-11-10 18:43:05 -08003330 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3331 const auto& captureEntry =
3332 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3333 status = connection->inputPublisher
3334 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003335 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003336 break;
3337 }
3338
arthurhungb89ccb02020-12-30 16:19:01 +08003339 case EventEntry::Type::DRAG: {
3340 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3341 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3342 dragEntry.id, dragEntry.x,
3343 dragEntry.y,
3344 dragEntry.isExiting);
3345 break;
3346 }
3347
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003348 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003349 case EventEntry::Type::DEVICE_RESET:
3350 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003351 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003352 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
3356
3357 // Check the result.
3358 if (status) {
3359 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003360 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 "This is unexpected because the wait queue is empty, so the pipe "
3363 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003364 "event to it, status=%s(%d)",
3365 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3366 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3368 } else {
3369 // Pipe is full and we are waiting for the app to finish process some events
3370 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003371 if (DEBUG_DISPATCH_CYCLE) {
3372 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3373 "waiting for the application to catch up",
3374 connection->getInputChannelName().c_str());
3375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 }
3377 } else {
3378 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003379 "status=%s(%d)",
3380 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3381 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3383 }
3384 return;
3385 }
3386
3387 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003388 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3389 connection->outboundQueue.end(),
3390 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003391 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003392 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003393 if (connection->responsive) {
3394 mAnrTracker.insert(dispatchEntry->timeoutTime,
3395 connection->inputChannel->getConnectionToken());
3396 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003397 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
3399}
3400
chaviw09c8d2d2020-08-24 15:48:26 -07003401std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3402 size_t size;
3403 switch (event.type) {
3404 case VerifiedInputEvent::Type::KEY: {
3405 size = sizeof(VerifiedKeyEvent);
3406 break;
3407 }
3408 case VerifiedInputEvent::Type::MOTION: {
3409 size = sizeof(VerifiedMotionEvent);
3410 break;
3411 }
3412 }
3413 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3414 return mHmacKeyManager.sign(start, size);
3415}
3416
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003417const std::array<uint8_t, 32> InputDispatcher::getSignature(
3418 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003419 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3420 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003421 // Only sign events up and down events as the purely move events
3422 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003423 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003424 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003425
3426 VerifiedMotionEvent verifiedEvent =
3427 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3428 verifiedEvent.actionMasked = actionMasked;
3429 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3430 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003431}
3432
3433const std::array<uint8_t, 32> InputDispatcher::getSignature(
3434 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3435 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3436 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3437 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003438 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003439}
3440
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003442 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003443 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003444 if (DEBUG_DISPATCH_CYCLE) {
3445 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3446 connection->getInputChannelName().c_str(), seq, toString(handled));
3447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003449 if (connection->status == Connection::Status::BROKEN ||
3450 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 return;
3452 }
3453
3454 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003455 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3456 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3457 };
3458 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459}
3460
3461void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003462 const sp<Connection>& connection,
3463 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003464 if (DEBUG_DISPATCH_CYCLE) {
3465 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3466 connection->getInputChannelName().c_str(), toString(notify));
3467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
3469 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003470 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003471 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003472 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003473 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474
3475 // The connection appears to be unrecoverably broken.
3476 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003477 if (connection->status == Connection::Status::NORMAL) {
3478 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
3480 if (notify) {
3481 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003482 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3483 connection->getInputChannelName().c_str());
3484
3485 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003486 scoped_unlock unlock(mLock);
3487 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3488 };
3489 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
3491 }
3492}
3493
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003494void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3495 while (!queue.empty()) {
3496 DispatchEntry* dispatchEntry = queue.front();
3497 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003498 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
3500}
3501
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003502void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003504 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506 delete dispatchEntry;
3507}
3508
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003509int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3510 std::scoped_lock _l(mLock);
3511 sp<Connection> connection = getConnectionLocked(connectionToken);
3512 if (connection == nullptr) {
3513 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3514 connectionToken.get(), events);
3515 return 0; // remove the callback
3516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003518 bool notify;
3519 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3520 if (!(events & ALOOPER_EVENT_INPUT)) {
3521 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3522 "events=0x%x",
3523 connection->getInputChannelName().c_str(), events);
3524 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
3526
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003527 nsecs_t currentTime = now();
3528 bool gotOne = false;
3529 status_t status = OK;
3530 for (;;) {
3531 Result<InputPublisher::ConsumerResponse> result =
3532 connection->inputPublisher.receiveConsumerResponse();
3533 if (!result.ok()) {
3534 status = result.error().code();
3535 break;
3536 }
3537
3538 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3539 const InputPublisher::Finished& finish =
3540 std::get<InputPublisher::Finished>(*result);
3541 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3542 finish.consumeTime);
3543 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003544 if (shouldReportMetricsForConnection(*connection)) {
3545 const InputPublisher::Timeline& timeline =
3546 std::get<InputPublisher::Timeline>(*result);
3547 mLatencyTracker
3548 .trackGraphicsLatency(timeline.inputEventId,
3549 connection->inputChannel->getConnectionToken(),
3550 std::move(timeline.graphicsTimeline));
3551 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003552 }
3553 gotOne = true;
3554 }
3555 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003556 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003557 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 return 1;
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003562 notify = status != DEAD_OBJECT || !connection->monitor;
3563 if (notify) {
3564 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3565 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3566 status);
3567 }
3568 } else {
3569 // Monitor channels are never explicitly unregistered.
3570 // We do it automatically when the remote endpoint is closed so don't warn about them.
3571 const bool stillHaveWindowHandle =
3572 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3573 notify = !connection->monitor && stillHaveWindowHandle;
3574 if (notify) {
3575 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3576 connection->getInputChannelName().c_str(), events);
3577 }
3578 }
3579
3580 // Remove the channel.
3581 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3582 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583}
3584
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003585void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003587 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003588 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
3590}
3591
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003592void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003593 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003594 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003595 for (const Monitor& monitor : monitors) {
3596 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003597 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003598 }
3599}
3600
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003602 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003603 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003604 if (connection == nullptr) {
3605 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003607
3608 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609}
3610
3611void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3612 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003613 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 return;
3615 }
3616
3617 nsecs_t currentTime = now();
3618
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003619 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003620 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003622 if (cancelationEvents.empty()) {
3623 return;
3624 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003625 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3626 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3627 "with reality: %s, mode=%d.",
3628 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3629 options.mode);
3630 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631
Arthur Hungb3307ee2021-10-14 10:57:37 +00003632 std::string reason = std::string("reason=").append(options.reason);
3633 android_log_event_list(LOGTAG_INPUT_CANCEL)
3634 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3635
Svet Ganov5d3bc372020-01-26 23:11:07 -08003636 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003637 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003638 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3639 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003640 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003641 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003642 target.globalScaleFactor = windowInfo->globalScaleFactor;
3643 }
3644 target.inputChannel = connection->inputChannel;
3645 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3646
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003647 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003648 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003649 switch (cancelationEventEntry->type) {
3650 case EventEntry::Type::KEY: {
3651 logOutboundKeyDetails("cancel - ",
3652 static_cast<const KeyEntry&>(*cancelationEventEntry));
3653 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003655 case EventEntry::Type::MOTION: {
3656 logOutboundMotionDetails("cancel - ",
3657 static_cast<const MotionEntry&>(*cancelationEventEntry));
3658 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003660 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003661 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003662 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3663 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003664 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003665 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003666 break;
3667 }
3668 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003669 case EventEntry::Type::DEVICE_RESET:
3670 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003671 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003672 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003673 break;
3674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 }
3676
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003677 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3678 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003680
3681 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682}
3683
Svet Ganov5d3bc372020-01-26 23:11:07 -08003684void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3685 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003686 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003687 return;
3688 }
3689
3690 nsecs_t currentTime = now();
3691
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003692 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003693 connection->inputState.synthesizePointerDownEvents(currentTime);
3694
3695 if (downEvents.empty()) {
3696 return;
3697 }
3698
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003699 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003700 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3701 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003702 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003703
3704 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003705 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003706 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3707 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003708 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003709 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003710 target.globalScaleFactor = windowInfo->globalScaleFactor;
3711 }
3712 target.inputChannel = connection->inputChannel;
3713 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3714
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 switch (downEventEntry->type) {
3717 case EventEntry::Type::MOTION: {
3718 logOutboundMotionDetails("down - ",
3719 static_cast<const MotionEntry&>(*downEventEntry));
3720 break;
3721 }
3722
3723 case EventEntry::Type::KEY:
3724 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003725 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003727 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003728 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003729 case EventEntry::Type::SENSOR:
3730 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003732 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003733 break;
3734 }
3735 }
3736
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003737 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3738 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003739 }
3740
3741 startDispatchCycleLocked(currentTime, connection);
3742}
3743
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003744std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3745 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 ALOG_ASSERT(pointerIds.value != 0);
3747
3748 uint32_t splitPointerIndexMap[MAX_POINTERS];
3749 PointerProperties splitPointerProperties[MAX_POINTERS];
3750 PointerCoords splitPointerCoords[MAX_POINTERS];
3751
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003752 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 uint32_t splitPointerCount = 0;
3754
3755 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003756 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003758 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 uint32_t pointerId = uint32_t(pointerProperties.id);
3760 if (pointerIds.hasBit(pointerId)) {
3761 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3762 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3763 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003764 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 splitPointerCount += 1;
3766 }
3767 }
3768
3769 if (splitPointerCount != pointerIds.count()) {
3770 // This is bad. We are missing some of the pointers that we expected to deliver.
3771 // Most likely this indicates that we received an ACTION_MOVE events that has
3772 // different pointer ids than we expected based on the previous ACTION_DOWN
3773 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3774 // in this way.
3775 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 "we expected there to be %d pointers. This probably means we received "
3777 "a broken sequence of pointer ids from the input device.",
3778 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003779 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 }
3781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003782 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003784 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3785 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3787 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003788 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 uint32_t pointerId = uint32_t(pointerProperties.id);
3790 if (pointerIds.hasBit(pointerId)) {
3791 if (pointerIds.count() == 1) {
3792 // The first/last pointer went down/up.
3793 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003794 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003795 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3796 ? AMOTION_EVENT_ACTION_CANCEL
3797 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 } else {
3799 // A secondary pointer went down/up.
3800 uint32_t splitPointerIndex = 0;
3801 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3802 splitPointerIndex += 1;
3803 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 action = maskedAction |
3805 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807 } else {
3808 // An unrelated pointer changed.
3809 action = AMOTION_EVENT_ACTION_MOVE;
3810 }
3811 }
3812
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003813 int32_t newId = mIdGenerator.nextId();
3814 if (ATRACE_ENABLED()) {
3815 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3816 ") to MotionEvent(id=0x%" PRIx32 ").",
3817 originalMotionEntry.id, newId);
3818 ATRACE_NAME(message.c_str());
3819 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003820 std::unique_ptr<MotionEntry> splitMotionEntry =
3821 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3822 originalMotionEntry.deviceId, originalMotionEntry.source,
3823 originalMotionEntry.displayId,
3824 originalMotionEntry.policyFlags, action,
3825 originalMotionEntry.actionButton,
3826 originalMotionEntry.flags, originalMotionEntry.metaState,
3827 originalMotionEntry.buttonState,
3828 originalMotionEntry.classification,
3829 originalMotionEntry.edgeFlags,
3830 originalMotionEntry.xPrecision,
3831 originalMotionEntry.yPrecision,
3832 originalMotionEntry.xCursorPosition,
3833 originalMotionEntry.yCursorPosition,
3834 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003835 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003837 if (originalMotionEntry.injectionState) {
3838 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 splitMotionEntry->injectionState->refCount += 1;
3840 }
3841
3842 return splitMotionEntry;
3843}
3844
3845void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003846 if (DEBUG_INBOUND_EVENT_DETAILS) {
3847 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849
Antonio Kantekf16f2832021-09-28 04:39:20 +00003850 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003852 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3855 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3856 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 } // release lock
3858
3859 if (needWake) {
3860 mLooper->wake();
3861 }
3862}
3863
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003864/**
3865 * If one of the meta shortcuts is detected, process them here:
3866 * Meta + Backspace -> generate BACK
3867 * Meta + Enter -> generate HOME
3868 * This will potentially overwrite keyCode and metaState.
3869 */
3870void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003871 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003872 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3873 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3874 if (keyCode == AKEYCODE_DEL) {
3875 newKeyCode = AKEYCODE_BACK;
3876 } else if (keyCode == AKEYCODE_ENTER) {
3877 newKeyCode = AKEYCODE_HOME;
3878 }
3879 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003880 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003881 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003882 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003883 keyCode = newKeyCode;
3884 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3885 }
3886 } else if (action == AKEY_EVENT_ACTION_UP) {
3887 // In order to maintain a consistent stream of up and down events, check to see if the key
3888 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3889 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003890 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003891 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003892 auto replacementIt = mReplacedKeys.find(replacement);
3893 if (replacementIt != mReplacedKeys.end()) {
3894 keyCode = replacementIt->second;
3895 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003896 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3897 }
3898 }
3899}
3900
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003902 if (DEBUG_INBOUND_EVENT_DETAILS) {
3903 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3904 "policyFlags=0x%x, action=0x%x, "
3905 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3906 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3907 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3908 args->downTime);
3909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 if (!validateKeyEvent(args->action)) {
3911 return;
3912 }
3913
3914 uint32_t policyFlags = args->policyFlags;
3915 int32_t flags = args->flags;
3916 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003917 // InputDispatcher tracks and generates key repeats on behalf of
3918 // whatever notifies it, so repeatCount should always be set to 0
3919 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3921 policyFlags |= POLICY_FLAG_VIRTUAL;
3922 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 if (policyFlags & POLICY_FLAG_FUNCTION) {
3925 metaState |= AMETA_FUNCTION_ON;
3926 }
3927
3928 policyFlags |= POLICY_FLAG_TRUSTED;
3929
Michael Wright78f24442014-08-06 15:55:28 -07003930 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003931 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003932
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003934 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003935 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3936 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
Michael Wright2b3c3302018-03-02 17:19:13 +00003938 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003940 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3941 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003942 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944
Antonio Kantekf16f2832021-09-28 04:39:20 +00003945 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 { // acquire lock
3947 mLock.lock();
3948
3949 if (shouldSendKeyToInputFilterLocked(args)) {
3950 mLock.unlock();
3951
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003952 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3954 return; // event was consumed by the filter
3955 }
3956
3957 mLock.lock();
3958 }
3959
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003960 std::unique_ptr<KeyEntry> newEntry =
3961 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3962 args->displayId, policyFlags, args->action, flags,
3963 keyCode, args->scanCode, metaState, repeatCount,
3964 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003966 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 mLock.unlock();
3968 } // release lock
3969
3970 if (needWake) {
3971 mLooper->wake();
3972 }
3973}
3974
3975bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3976 return mInputFilterEnabled;
3977}
3978
3979void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003980 if (DEBUG_INBOUND_EVENT_DETAILS) {
3981 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3982 "displayId=%" PRId32 ", policyFlags=0x%x, "
3983 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3984 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3985 "yCursorPosition=%f, downTime=%" PRId64,
3986 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3987 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3988 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3989 args->xCursorPosition, args->yCursorPosition, args->downTime);
3990 for (uint32_t i = 0; i < args->pointerCount; i++) {
3991 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3992 "x=%f, y=%f, pressure=%f, size=%f, "
3993 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3994 "orientation=%f",
3995 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3996 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3997 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3998 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3999 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4000 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4001 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4002 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4003 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4004 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004007 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4008 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 return;
4010 }
4011
4012 uint32_t policyFlags = args->policyFlags;
4013 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004014
4015 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004016 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004017 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4018 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004019 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
Antonio Kantekf16f2832021-09-28 04:39:20 +00004022 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 { // acquire lock
4024 mLock.lock();
4025
4026 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004027 ui::Transform displayTransform;
4028 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4029 displayTransform = it->second.transform;
4030 }
4031
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 mLock.unlock();
4033
4034 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004035 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4036 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004037 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004038 displayTransform, args->xPrecision, args->yPrecision,
4039 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004040 args->downTime, args->eventTime, args->pointerCount,
4041 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
4043 policyFlags |= POLICY_FLAG_FILTERED;
4044 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4045 return; // event was consumed by the filter
4046 }
4047
4048 mLock.lock();
4049 }
4050
4051 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004052 std::unique_ptr<MotionEntry> newEntry =
4053 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4054 args->source, args->displayId, policyFlags,
4055 args->action, args->actionButton, args->flags,
4056 args->metaState, args->buttonState,
4057 args->classification, args->edgeFlags,
4058 args->xPrecision, args->yPrecision,
4059 args->xCursorPosition, args->yCursorPosition,
4060 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004061 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004063 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4064 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4065 !mInputFilterEnabled) {
4066 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4067 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4068 }
4069
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004070 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 mLock.unlock();
4072 } // release lock
4073
4074 if (needWake) {
4075 mLooper->wake();
4076 }
4077}
4078
Chris Yef59a2f42020-10-16 12:55:26 -07004079void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004080 if (DEBUG_INBOUND_EVENT_DETAILS) {
4081 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4082 " sensorType=%s",
4083 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004084 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004085 }
Chris Yef59a2f42020-10-16 12:55:26 -07004086
Antonio Kantekf16f2832021-09-28 04:39:20 +00004087 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004088 { // acquire lock
4089 mLock.lock();
4090
4091 // Just enqueue a new sensor event.
4092 std::unique_ptr<SensorEntry> newEntry =
4093 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4094 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4095 args->sensorType, args->accuracy,
4096 args->accuracyChanged, args->values);
4097
4098 needWake = enqueueInboundEventLocked(std::move(newEntry));
4099 mLock.unlock();
4100 } // release lock
4101
4102 if (needWake) {
4103 mLooper->wake();
4104 }
4105}
4106
Chris Yefb552902021-02-03 17:18:37 -08004107void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004108 if (DEBUG_INBOUND_EVENT_DETAILS) {
4109 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4110 args->deviceId, args->isOn);
4111 }
Chris Yefb552902021-02-03 17:18:37 -08004112 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4113}
4114
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004116 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117}
4118
4119void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 if (DEBUG_INBOUND_EVENT_DETAILS) {
4121 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4122 "switchMask=0x%08x",
4123 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
4126 uint32_t policyFlags = args->policyFlags;
4127 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129}
4130
4131void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004132 if (DEBUG_INBOUND_EVENT_DETAILS) {
4133 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4134 args->deviceId);
4135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136
Antonio Kantekf16f2832021-09-28 04:39:20 +00004137 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004139 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004141 std::unique_ptr<DeviceResetEntry> newEntry =
4142 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4143 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 } // release lock
4145
4146 if (needWake) {
4147 mLooper->wake();
4148 }
4149}
4150
Prabir Pradhan7e186182020-11-10 13:56:45 -08004151void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004152 if (DEBUG_INBOUND_EVENT_DETAILS) {
4153 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004154 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004155 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004156
Antonio Kantekf16f2832021-09-28 04:39:20 +00004157 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004158 { // acquire lock
4159 std::scoped_lock _l(mLock);
4160 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004161 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004162 needWake = enqueueInboundEventLocked(std::move(entry));
4163 } // release lock
4164
4165 if (needWake) {
4166 mLooper->wake();
4167 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004168}
4169
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004170InputEventInjectionResult InputDispatcher::injectInputEvent(
4171 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4172 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004173 if (DEBUG_INBOUND_EVENT_DETAILS) {
4174 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4175 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4176 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4177 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004178 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
4180 policyFlags |= POLICY_FLAG_INJECTED;
4181 if (hasInjectionPermission(injectorPid, injectorUid)) {
4182 policyFlags |= POLICY_FLAG_TRUSTED;
4183 }
4184
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004185 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004186 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4187 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4188 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4189 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4190 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004191 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004192 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004193 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004194 }
4195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004196 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004198 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004199 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4200 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004202 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004205 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004206 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4207 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4208 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004209 int32_t keyCode = incomingKey.getKeyCode();
4210 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004211 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004213 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004214 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004215 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4216 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4217 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004219 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4220 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004221 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222
4223 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4224 android::base::Timer t;
4225 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4226 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4227 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4228 std::to_string(t.duration().count()).c_str());
4229 }
4230 }
4231
4232 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 std::unique_ptr<KeyEntry> injectedEntry =
4234 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004236 incomingKey.getDisplayId(), policyFlags, action,
4237 flags, keyCode, incomingKey.getScanCode(), metaState,
4238 incomingKey.getRepeatCount(),
4239 incomingKey.getDownTime());
4240 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 }
4243
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004245 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004246 const int32_t action = motionEvent.getAction();
4247 const bool isPointerEvent =
4248 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4249 // If a pointer event has no displayId specified, inject it to the default display.
4250 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4251 ? ADISPLAY_ID_DEFAULT
4252 : event->getDisplayId();
4253 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004254 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004255 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004256 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 }
4260
4261 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 android::base::Timer t;
4264 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4265 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4266 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4267 std::to_string(t.duration().count()).c_str());
4268 }
4269 }
4270
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004271 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4272 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4273 }
4274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004276 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4277 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4280 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004281 displayId, policyFlags, action, actionButton,
4282 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 motionEvent.getButtonState(),
4284 motionEvent.getClassification(),
4285 motionEvent.getEdgeFlags(),
4286 motionEvent.getXPrecision(),
4287 motionEvent.getYPrecision(),
4288 motionEvent.getRawXCursorPosition(),
4289 motionEvent.getRawYCursorPosition(),
4290 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004291 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004292 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004293 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 sampleEventTimes += 1;
4296 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004297 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004298 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4299 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004300 displayId, policyFlags, action, actionButton,
4301 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004302 motionEvent.getButtonState(),
4303 motionEvent.getClassification(),
4304 motionEvent.getEdgeFlags(),
4305 motionEvent.getXPrecision(),
4306 motionEvent.getYPrecision(),
4307 motionEvent.getRawXCursorPosition(),
4308 motionEvent.getRawYCursorPosition(),
4309 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004310 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004311 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004312 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4313 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004314 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 }
4316 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004319 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004320 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004321 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323
4324 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004325 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 injectionState->injectionIsAsync = true;
4327 }
4328
4329 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004330 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331
4332 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004333 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004334 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004335 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 }
4337
4338 mLock.unlock();
4339
4340 if (needWake) {
4341 mLooper->wake();
4342 }
4343
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004346 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004348 if (syncMode == InputEventInjectionSync::NONE) {
4349 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 } else {
4351 for (;;) {
4352 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004353 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 break;
4355 }
4356
4357 nsecs_t remainingTimeout = endTime - now();
4358 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004359 if (DEBUG_INJECTION) {
4360 ALOGD("injectInputEvent - Timed out waiting for injection result "
4361 "to become available.");
4362 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 break;
4365 }
4366
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004367 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004370 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4371 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004373 if (DEBUG_INJECTION) {
4374 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4375 injectionState->pendingForegroundDispatches);
4376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 nsecs_t remainingTimeout = endTime - now();
4378 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004379 if (DEBUG_INJECTION) {
4380 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4381 "dispatches to finish.");
4382 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 break;
4385 }
4386
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004387 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 }
4389 }
4390 }
4391
4392 injectionState->release();
4393 } // release lock
4394
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004395 if (DEBUG_INJECTION) {
4396 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4397 injectionResult, injectorPid, injectorUid);
4398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
4400 return injectionResult;
4401}
4402
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004403std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004404 std::array<uint8_t, 32> calculatedHmac;
4405 std::unique_ptr<VerifiedInputEvent> result;
4406 switch (event.getType()) {
4407 case AINPUT_EVENT_TYPE_KEY: {
4408 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4409 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4410 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004411 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004412 break;
4413 }
4414 case AINPUT_EVENT_TYPE_MOTION: {
4415 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4416 VerifiedMotionEvent verifiedMotionEvent =
4417 verifiedMotionEventFromMotionEvent(motionEvent);
4418 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004419 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004420 break;
4421 }
4422 default: {
4423 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4424 return nullptr;
4425 }
4426 }
4427 if (calculatedHmac == INVALID_HMAC) {
4428 return nullptr;
4429 }
4430 if (calculatedHmac != event.getHmac()) {
4431 return nullptr;
4432 }
4433 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004434}
4435
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 return injectorUid == 0 ||
4438 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439}
4440
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004441void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004443 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004445 if (DEBUG_INJECTION) {
4446 ALOGD("Setting input event injection result to %d. "
4447 "injectorPid=%d, injectorUid=%d",
4448 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004451 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 // Log the outcome since the injector did not wait for the injection result.
4453 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 ALOGV("Asynchronous input event injection succeeded.");
4456 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004457 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 ALOGW("Asynchronous input event injection failed.");
4459 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004460 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004461 ALOGW("Asynchronous input event injection permission denied.");
4462 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004463 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004464 ALOGW("Asynchronous input event injection timed out.");
4465 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004466 case InputEventInjectionResult::PENDING:
4467 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4468 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 }
4470 }
4471
4472 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004473 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 }
4475}
4476
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004477void InputDispatcher::transformMotionEntryForInjectionLocked(
4478 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004479 // Input injection works in the logical display coordinate space, but the input pipeline works
4480 // display space, so we need to transform the injected events accordingly.
4481 const auto it = mDisplayInfos.find(entry.displayId);
4482 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004483 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004484
4485 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004486 entry.pointerCoords[i] =
4487 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4488 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004489 }
4490}
4491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004492void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4493 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 if (injectionState) {
4495 injectionState->pendingForegroundDispatches += 1;
4496 }
4497}
4498
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004499void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4500 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 if (injectionState) {
4502 injectionState->pendingForegroundDispatches -= 1;
4503
4504 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004505 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 }
4507 }
4508}
4509
chaviw98318de2021-05-19 16:45:23 -05004510const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004511 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004512 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004513 auto it = mWindowHandlesByDisplay.find(displayId);
4514 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004515}
4516
chaviw98318de2021-05-19 16:45:23 -05004517sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004518 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004519 if (windowHandleToken == nullptr) {
4520 return nullptr;
4521 }
4522
Arthur Hungb92218b2018-08-14 12:00:21 +08004523 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004524 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4525 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004526 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004527 return windowHandle;
4528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 }
4530 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004531 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532}
4533
chaviw98318de2021-05-19 16:45:23 -05004534sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4535 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004536 if (windowHandleToken == nullptr) {
4537 return nullptr;
4538 }
4539
chaviw98318de2021-05-19 16:45:23 -05004540 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004541 if (windowHandle->getToken() == windowHandleToken) {
4542 return windowHandle;
4543 }
4544 }
4545 return nullptr;
4546}
4547
chaviw98318de2021-05-19 16:45:23 -05004548sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4549 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004550 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004551 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4552 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004553 if (handle->getId() == windowHandle->getId() &&
4554 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004555 if (windowHandle->getInfo()->displayId != it.first) {
4556 ALOGE("Found window %s in display %" PRId32
4557 ", but it should belong to display %" PRId32,
4558 windowHandle->getName().c_str(), it.first,
4559 windowHandle->getInfo()->displayId);
4560 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004561 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 }
4564 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004565 return nullptr;
4566}
4567
chaviw98318de2021-05-19 16:45:23 -05004568sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004569 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4570 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571}
4572
chaviw98318de2021-05-19 16:45:23 -05004573bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004574 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4575 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004576 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004577 if (connection != nullptr && noInputChannel) {
4578 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4579 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4580 return false;
4581 }
4582
4583 if (connection == nullptr) {
4584 if (!noInputChannel) {
4585 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4586 }
4587 return false;
4588 }
4589 if (!connection->responsive) {
4590 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4591 return false;
4592 }
4593 return true;
4594}
4595
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004596std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4597 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004598 auto connectionIt = mConnectionsByToken.find(token);
4599 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004600 return nullptr;
4601 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004602 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004603}
4604
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004605void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004606 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4607 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004608 // Remove all handles on a display if there are no windows left.
4609 mWindowHandlesByDisplay.erase(displayId);
4610 return;
4611 }
4612
4613 // Since we compare the pointer of input window handles across window updates, we need
4614 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004615 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4616 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4617 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004618 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004619 }
4620
chaviw98318de2021-05-19 16:45:23 -05004621 std::vector<sp<WindowInfoHandle>> newHandles;
4622 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004623 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004624 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004625 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004626 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004627 const bool canReceiveInput =
4628 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4629 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004630 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004631 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004632 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004633 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004634 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004635 }
4636
4637 if (info->displayId != displayId) {
4638 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4639 handle->getName().c_str(), displayId, info->displayId);
4640 continue;
4641 }
4642
Robert Carredd13602020-04-13 17:24:34 -07004643 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4644 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004645 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004646 oldHandle->updateFrom(handle);
4647 newHandles.push_back(oldHandle);
4648 } else {
4649 newHandles.push_back(handle);
4650 }
4651 }
4652
4653 // Insert or replace
4654 mWindowHandlesByDisplay[displayId] = newHandles;
4655}
4656
Arthur Hung72d8dc32020-03-28 00:48:39 +00004657void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004658 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004659 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004660 { // acquire lock
4661 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004662 for (const auto& [displayId, handles] : handlesPerDisplay) {
4663 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004664 }
4665 }
4666 // Wake up poll loop since it may need to make new input dispatching choices.
4667 mLooper->wake();
4668}
4669
Arthur Hungb92218b2018-08-14 12:00:21 +08004670/**
4671 * Called from InputManagerService, update window handle list by displayId that can receive input.
4672 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4673 * If set an empty list, remove all handles from the specific display.
4674 * For focused handle, check if need to change and send a cancel event to previous one.
4675 * For removed handle, check if need to send a cancel event if already in touch.
4676 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004677void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004678 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004679 if (DEBUG_FOCUS) {
4680 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004681 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004682 windowList += iwh->getName() + " ";
4683 }
4684 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Prabir Pradhand65552b2021-10-07 11:23:50 -07004687 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004688 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004689 const WindowInfo& info = *window->getInfo();
4690
4691 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004692 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004693 if (noInputWindow && window->getToken() != nullptr) {
4694 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4695 window->getName().c_str());
4696 window->releaseChannel();
4697 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004698
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004699 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004700 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4701 !info.inputConfig.test(
4702 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004703 "%s has feature SPY, but is not a trusted overlay.",
4704 window->getName().c_str());
4705
Prabir Pradhand65552b2021-10-07 11:23:50 -07004706 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004707 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4708 !info.inputConfig.test(
4709 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004710 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4711 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004712 }
4713
Arthur Hung72d8dc32020-03-28 00:48:39 +00004714 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004715 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004717 // Save the old windows' orientation by ID before it gets updated.
4718 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004719 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004720 oldWindowOrientations.emplace(handle->getId(),
4721 handle->getInfo()->transform.getOrientation());
4722 }
4723
chaviw98318de2021-05-19 16:45:23 -05004724 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004725
chaviw98318de2021-05-19 16:45:23 -05004726 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004727 if (mLastHoverWindowHandle &&
4728 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4729 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004730 mLastHoverWindowHandle = nullptr;
4731 }
4732
Vishnu Nairc519ff72021-01-21 08:23:08 -08004733 std::optional<FocusResolver::FocusChanges> changes =
4734 mFocusResolver.setInputWindows(displayId, windowHandles);
4735 if (changes) {
4736 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004739 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4740 mTouchStatesByDisplay.find(displayId);
4741 if (stateIt != mTouchStatesByDisplay.end()) {
4742 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004743 for (size_t i = 0; i < state.windows.size();) {
4744 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004745 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004746 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004747 ALOGD("Touched window was removed: %s in display %" PRId32,
4748 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004749 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004750 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004751 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4752 if (touchedInputChannel != nullptr) {
4753 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4754 "touched window was removed");
4755 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004756 // Since we are about to drop the touch, cancel the events for the wallpaper as
4757 // well.
4758 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004759 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4760 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004761 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4762 if (wallpaper != nullptr) {
4763 sp<Connection> wallpaperConnection =
4764 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004765 if (wallpaperConnection != nullptr) {
4766 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4767 options);
4768 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004769 }
4770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004772 state.windows.erase(state.windows.begin() + i);
4773 } else {
4774 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 }
4776 }
arthurhungb89ccb02020-12-30 16:19:01 +08004777
arthurhung6d4bed92021-03-17 11:59:33 +08004778 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004779 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004780 if (mDragState &&
4781 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004782 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004783 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004784 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004785 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004786
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004787 // Determine if the orientation of any of the input windows have changed, and cancel all
4788 // pointer events if necessary.
4789 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4790 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4791 if (newWindowHandle != nullptr &&
4792 newWindowHandle->getInfo()->transform.getOrientation() !=
4793 oldWindowOrientations[oldWindowHandle->getId()]) {
4794 std::shared_ptr<InputChannel> inputChannel =
4795 getInputChannelLocked(newWindowHandle->getToken());
4796 if (inputChannel != nullptr) {
4797 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4798 "touched window's orientation changed");
4799 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004800 }
4801 }
4802 }
4803
Arthur Hung72d8dc32020-03-28 00:48:39 +00004804 // Release information for windows that are no longer present.
4805 // This ensures that unused input channels are released promptly.
4806 // Otherwise, they might stick around until the window handle is destroyed
4807 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004808 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004809 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004810 if (DEBUG_FOCUS) {
4811 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004812 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004813 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004814 }
chaviw291d88a2019-02-14 10:33:58 -08004815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816}
4817
4818void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004819 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004820 if (DEBUG_FOCUS) {
4821 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4822 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4823 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004824 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004825 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004826 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 } // release lock
4828
4829 // Wake up poll loop since it may need to make new input dispatching choices.
4830 mLooper->wake();
4831}
4832
Vishnu Nair599f1412021-06-21 10:39:58 -07004833void InputDispatcher::setFocusedApplicationLocked(
4834 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4835 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4836 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4837
4838 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4839 return; // This application is already focused. No need to wake up or change anything.
4840 }
4841
4842 // Set the new application handle.
4843 if (inputApplicationHandle != nullptr) {
4844 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4845 } else {
4846 mFocusedApplicationHandlesByDisplay.erase(displayId);
4847 }
4848
4849 // No matter what the old focused application was, stop waiting on it because it is
4850 // no longer focused.
4851 resetNoFocusedWindowTimeoutLocked();
4852}
4853
Tiger Huang721e26f2018-07-24 22:26:19 +08004854/**
4855 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4856 * the display not specified.
4857 *
4858 * We track any unreleased events for each window. If a window loses the ability to receive the
4859 * released event, we will send a cancel event to it. So when the focused display is changed, we
4860 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4861 * display. The display-specified events won't be affected.
4862 */
4863void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004864 if (DEBUG_FOCUS) {
4865 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4866 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004867 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004868 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004869
4870 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004871 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004872 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004873 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004874 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004875 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004876 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004877 CancelationOptions
4878 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4879 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004880 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004881 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4882 }
4883 }
4884 mFocusedDisplayId = displayId;
4885
Chris Ye3c2d6f52020-08-09 10:39:48 -07004886 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004887 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004888 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004889
Vishnu Nairad321cd2020-08-20 16:40:21 -07004890 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004891 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004892 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004893 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004894 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004895 }
4896 }
4897 }
4898
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004899 if (DEBUG_FOCUS) {
4900 logDispatchStateLocked();
4901 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004902 } // release lock
4903
4904 // Wake up poll loop since it may need to make new input dispatching choices.
4905 mLooper->wake();
4906}
4907
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004909 if (DEBUG_FOCUS) {
4910 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
4913 bool changed;
4914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004915 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916
4917 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4918 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 }
4921
4922 if (mDispatchEnabled && !enabled) {
4923 resetAndDropEverythingLocked("dispatcher is being disabled");
4924 }
4925
4926 mDispatchEnabled = enabled;
4927 mDispatchFrozen = frozen;
4928 changed = true;
4929 } else {
4930 changed = false;
4931 }
4932
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004933 if (DEBUG_FOCUS) {
4934 logDispatchStateLocked();
4935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 } // release lock
4937
4938 if (changed) {
4939 // Wake up poll loop since it may need to make new input dispatching choices.
4940 mLooper->wake();
4941 }
4942}
4943
4944void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004945 if (DEBUG_FOCUS) {
4946 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948
4949 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004950 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
4952 if (mInputFilterEnabled == enabled) {
4953 return;
4954 }
4955
4956 mInputFilterEnabled = enabled;
4957 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4958 } // release lock
4959
4960 // Wake up poll loop since there might be work to do to drop everything.
4961 mLooper->wake();
4962}
4963
Antonio Kantekea47acb2021-12-23 12:41:25 -08004964bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4965 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004966 bool needWake = false;
4967 {
4968 std::scoped_lock lock(mLock);
4969 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004970 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004971 }
4972 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004973 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4974 "hasPermission=%s)",
4975 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4976 }
4977 if (!hasPermission) {
4978 const sp<IBinder> focusedToken =
4979 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4980
Antonio Kantek019eb662022-02-08 13:41:52 -08004981 // TODO(b/218541064): if no window is currently focused, then we need to check the last
Antonio Kantekea47acb2021-12-23 12:41:25 -08004982 // interacted window (within 1 second timeout). We should allow touch mode change
4983 // if the last interacted window owner's pid/uid match the calling ones.
4984 if (focusedToken == nullptr) {
4985 return false;
4986 }
4987 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4988 if (windowHandle == nullptr) {
4989 return false;
4990 }
4991 const WindowInfo* windowInfo = windowHandle->getInfo();
4992 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4993 return false;
4994 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004995 }
4996
4997 // TODO(b/198499018): Store touch mode per display.
4998 mInTouchMode = inTouchMode;
4999
Antonio Kantekf16f2832021-09-28 04:39:20 +00005000 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5001 needWake = enqueueInboundEventLocked(std::move(entry));
5002 } // release lock
5003
5004 if (needWake) {
5005 mLooper->wake();
5006 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005007 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005008}
5009
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005010void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5011 if (opacity < 0 || opacity > 1) {
5012 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5013 return;
5014 }
5015
5016 std::scoped_lock lock(mLock);
5017 mMaximumObscuringOpacityForTouch = opacity;
5018}
5019
5020void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5021 std::scoped_lock lock(mLock);
5022 mBlockUntrustedTouchesMode = mode;
5023}
5024
Arthur Hungabbb9d82021-09-01 14:52:30 +00005025std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5026 const sp<IBinder>& token) {
5027 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5028 for (TouchedWindow& w : state.windows) {
5029 if (w.windowHandle->getToken() == token) {
5030 return std::make_pair(&state, &w);
5031 }
5032 }
5033 }
5034 return std::make_pair(nullptr, nullptr);
5035}
5036
arthurhungb89ccb02020-12-30 16:19:01 +08005037bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5038 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005039 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005040 if (DEBUG_FOCUS) {
5041 ALOGD("Trivial transfer to same window.");
5042 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005043 return true;
5044 }
5045
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005047 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048
Arthur Hungabbb9d82021-09-01 14:52:30 +00005049 // Find the target touch state and touched window by fromToken.
5050 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5051 if (state == nullptr || touchedWindow == nullptr) {
5052 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 return false;
5054 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005055
5056 const int32_t displayId = state->displayId;
5057 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5058 if (toWindowHandle == nullptr) {
5059 ALOGW("Cannot transfer focus because to window not found.");
5060 return false;
5061 }
5062
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005063 if (DEBUG_FOCUS) {
5064 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005065 touchedWindow->windowHandle->getName().c_str(),
5066 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 }
5068
Arthur Hungabbb9d82021-09-01 14:52:30 +00005069 // Erase old window.
5070 int32_t oldTargetFlags = touchedWindow->targetFlags;
5071 BitSet32 pointerIds = touchedWindow->pointerIds;
5072 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073
Arthur Hungabbb9d82021-09-01 14:52:30 +00005074 // Add new window.
5075 int32_t newTargetFlags = oldTargetFlags &
5076 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5077 InputTarget::FLAG_DISPATCH_AS_IS);
5078 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
Arthur Hungabbb9d82021-09-01 14:52:30 +00005080 // Store the dragging window.
5081 if (isDragDrop) {
5082 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083 }
5084
Arthur Hungabbb9d82021-09-01 14:52:30 +00005085 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005086 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5087 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005088 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005089 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005090 CancelationOptions
5091 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5092 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005094 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 }
5096
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005097 if (DEBUG_FOCUS) {
5098 logDispatchStateLocked();
5099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 } // release lock
5101
5102 // Wake up poll loop since it may need to make new input dispatching choices.
5103 mLooper->wake();
5104 return true;
5105}
5106
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005107// Binder call
5108bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5109 sp<IBinder> fromToken;
5110 { // acquire lock
5111 std::scoped_lock _l(mLock);
5112
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5114 [](const auto& pair) { return pair.second.windows.size() == 1; });
5115 if (it == mTouchStatesByDisplay.end()) {
5116 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5117 return false;
5118 }
5119 const int32_t displayId = it->first;
5120 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005121 if (toWindowHandle == nullptr) {
5122 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5123 return false;
5124 }
5125
Arthur Hungabbb9d82021-09-01 14:52:30 +00005126 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005127 const TouchedWindow& touchedWindow = state.windows[0];
5128 fromToken = touchedWindow.windowHandle->getToken();
5129 } // release lock
5130
5131 return transferTouchFocus(fromToken, destChannelToken);
5132}
5133
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005135 if (DEBUG_FOCUS) {
5136 ALOGD("Resetting and dropping all events (%s).", reason);
5137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138
5139 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5140 synthesizeCancelationEventsForAllConnectionsLocked(options);
5141
5142 resetKeyRepeatLocked();
5143 releasePendingEventLocked();
5144 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005145 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005147 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005148 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005150 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151}
5152
5153void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005154 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 dumpDispatchStateLocked(dump);
5156
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005157 std::istringstream stream(dump);
5158 std::string line;
5159
5160 while (std::getline(stream, line, '\n')) {
5161 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163}
5164
Prabir Pradhan99987712020-11-10 18:43:05 -08005165std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5166 std::string dump;
5167
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005168 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5169 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005170
5171 std::string windowName = "None";
5172 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005173 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005174 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5175 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5176 : "token has capture without window";
5177 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005178 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005179
5180 return dump;
5181}
5182
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005183void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005184 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5185 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5186 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005187 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188
Tiger Huang721e26f2018-07-24 22:26:19 +08005189 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5190 dump += StringPrintf(INDENT "FocusedApplications:\n");
5191 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5192 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005193 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005194 const std::chrono::duration timeout =
5195 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005196 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005197 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005198 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005201 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005203
Vishnu Nairc519ff72021-01-21 08:23:08 -08005204 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005205 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005207 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005208 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005209 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5210 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005211 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005212 state.displayId, toString(state.down), toString(state.split),
5213 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005214 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005215 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005216 for (size_t i = 0; i < state.windows.size(); i++) {
5217 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005218 dump += StringPrintf(INDENT4
5219 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5220 i, touchedWindow.windowHandle->getName().c_str(),
5221 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005222 }
5223 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005224 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226 }
5227 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005228 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 }
5230
arthurhung6d4bed92021-03-17 11:59:33 +08005231 if (mDragState) {
5232 dump += StringPrintf(INDENT "DragState:\n");
5233 mDragState->dump(dump, INDENT2);
5234 }
5235
Arthur Hungb92218b2018-08-14 12:00:21 +08005236 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005237 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5238 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5239 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5240 const auto& displayInfo = it->second;
5241 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5242 displayInfo.logicalHeight);
5243 displayInfo.transform.dump(dump, "transform", INDENT4);
5244 } else {
5245 dump += INDENT2 "No DisplayInfo found!\n";
5246 }
5247
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005248 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005249 dump += INDENT2 "Windows:\n";
5250 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005251 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5252 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005254 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005255 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005256 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005257 "applicationInfo.name=%s, "
5258 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005259 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005260 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005261 windowInfo->displayId,
5262 windowInfo->inputConfig.string().c_str(),
5263 windowInfo->alpha, windowInfo->frameLeft,
5264 windowInfo->frameTop, windowInfo->frameRight,
5265 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005266 windowInfo->applicationInfo.name.c_str(),
5267 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005268 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005269 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005270 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005271 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005272 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005273 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005274 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005275 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005276 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005277 }
5278 } else {
5279 dump += INDENT2 "Windows: <none>\n";
5280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 }
5282 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005283 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 }
5285
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005286 if (!mGlobalMonitorsByDisplay.empty()) {
5287 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5288 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005289 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005292 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 }
5294
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005295 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296
5297 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005298 if (!mRecentQueue.empty()) {
5299 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005300 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005301 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005302 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005303 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 }
5305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 }
5308
5309 // Dump event currently being dispatched.
5310 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005311 dump += INDENT "PendingEvent:\n";
5312 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005313 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005314 dump += StringPrintf(", age=%" PRId64 "ms\n",
5315 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005317 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 }
5319
5320 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005321 if (!mInboundQueue.empty()) {
5322 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005323 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005324 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005325 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005326 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005329 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 }
5331
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005332 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005333 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005334 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5335 const KeyReplacement& replacement = pair.first;
5336 int32_t newKeyCode = pair.second;
5337 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005338 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005339 }
5340 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005341 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005342 }
5343
Prabir Pradhancef936d2021-07-21 16:17:52 +00005344 if (!mCommandQueue.empty()) {
5345 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5346 } else {
5347 dump += INDENT "CommandQueue: <empty>\n";
5348 }
5349
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005350 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005351 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005352 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005353 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005354 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005355 connection->inputChannel->getFd().get(),
5356 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005357 connection->getWindowName().c_str(),
5358 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005359 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005361 if (!connection->outboundQueue.empty()) {
5362 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5363 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005364 dump += dumpQueue(connection->outboundQueue, currentTime);
5365
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005367 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 }
5369
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005370 if (!connection->waitQueue.empty()) {
5371 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5372 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005373 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005375 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
5377 }
5378 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005379 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 }
5381
5382 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005383 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5384 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005386 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 }
5388
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005389 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005390 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5391 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5392 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005393 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005394 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395}
5396
Michael Wright3dd60e22019-03-27 22:06:44 +00005397void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5398 const size_t numMonitors = monitors.size();
5399 for (size_t i = 0; i < numMonitors; i++) {
5400 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005401 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005402 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5403 dump += "\n";
5404 }
5405}
5406
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005407class LooperEventCallback : public LooperCallback {
5408public:
5409 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5410 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5411
5412private:
5413 std::function<int(int events)> mCallback;
5414};
5415
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005416Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005417 if (DEBUG_CHANNEL_CREATION) {
5418 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005421 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005422 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005423 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005424
5425 if (result) {
5426 return base::Error(result) << "Failed to open input channel pair with name " << name;
5427 }
5428
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005430 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005431 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005432 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005433 sp<Connection> connection =
5434 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005436 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5437 ALOGE("Created a new connection, but the token %p is already known", token.get());
5438 }
5439 mConnectionsByToken.emplace(token, connection);
5440
5441 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5442 this, std::placeholders::_1, token);
5443
5444 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 } // release lock
5446
5447 // Wake the looper because some connections have changed.
5448 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005449 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450}
5451
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005452Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005453 const std::string& name,
5454 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005455 std::shared_ptr<InputChannel> serverChannel;
5456 std::unique_ptr<InputChannel> clientChannel;
5457 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5458 if (result) {
5459 return base::Error(result) << "Failed to open input channel pair with name " << name;
5460 }
5461
Michael Wright3dd60e22019-03-27 22:06:44 +00005462 { // acquire lock
5463 std::scoped_lock _l(mLock);
5464
5465 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005466 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5467 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005468 }
5469
Garfield Tan15601662020-09-22 15:32:38 -07005470 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005471 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005472 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005473
5474 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5475 ALOGE("Created a new connection, but the token %p is already known", token.get());
5476 }
5477 mConnectionsByToken.emplace(token, connection);
5478 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5479 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005480
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005481 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005482
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005483 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005484 }
Garfield Tan15601662020-09-22 15:32:38 -07005485
Michael Wright3dd60e22019-03-27 22:06:44 +00005486 // Wake the looper because some connections have changed.
5487 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005488 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005489}
5490
Garfield Tan15601662020-09-22 15:32:38 -07005491status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005493 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494
Garfield Tan15601662020-09-22 15:32:38 -07005495 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 if (status) {
5497 return status;
5498 }
5499 } // release lock
5500
5501 // Wake the poll loop because removing the connection may have changed the current
5502 // synchronization state.
5503 mLooper->wake();
5504 return OK;
5505}
5506
Garfield Tan15601662020-09-22 15:32:38 -07005507status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5508 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005509 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005510 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005511 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 return BAD_VALUE;
5513 }
5514
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005515 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005516
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005518 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 }
5520
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005521 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522
5523 nsecs_t currentTime = now();
5524 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5525
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005526 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 return OK;
5528}
5529
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005530void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005531 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5532 auto& [displayId, monitors] = *it;
5533 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5534 return monitor.inputChannel->getConnectionToken() == connectionToken;
5535 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005536
Michael Wright3dd60e22019-03-27 22:06:44 +00005537 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005538 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005539 } else {
5540 ++it;
5541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 }
5543}
5544
Michael Wright3dd60e22019-03-27 22:06:44 +00005545status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005546 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005547
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005548 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5549 if (!requestingChannel) {
5550 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5551 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005552 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005553
5554 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5555 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5556 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5557 " Ignoring.");
5558 return BAD_VALUE;
5559 }
5560
5561 TouchState& state = *statePtr;
5562
5563 // Send cancel events to all the input channels we're stealing from.
5564 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5565 "input channel stole pointer stream");
5566 options.deviceId = state.deviceId;
5567 options.displayId = state.displayId;
5568 std::string canceledWindows;
5569 for (const TouchedWindow& window : state.windows) {
5570 const std::shared_ptr<InputChannel> channel =
5571 getInputChannelLocked(window.windowHandle->getToken());
5572 if (channel != nullptr && channel->getConnectionToken() != token) {
5573 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5574 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5575 canceledWindows += channel->getName();
5576 }
5577 }
5578 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5579 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5580 canceledWindows.c_str());
5581
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005582 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005583 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005584 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005585 return OK;
5586}
5587
Prabir Pradhan99987712020-11-10 18:43:05 -08005588void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5589 { // acquire lock
5590 std::scoped_lock _l(mLock);
5591 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005592 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005593 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5594 windowHandle != nullptr ? windowHandle->getName().c_str()
5595 : "token without window");
5596 }
5597
Vishnu Nairc519ff72021-01-21 08:23:08 -08005598 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005599 if (focusedToken != windowToken) {
5600 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5601 enabled ? "enable" : "disable");
5602 return;
5603 }
5604
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005605 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005606 ALOGW("Ignoring request to %s Pointer Capture: "
5607 "window has %s requested pointer capture.",
5608 enabled ? "enable" : "disable", enabled ? "already" : "not");
5609 return;
5610 }
5611
Christine Franksb768bb42021-11-29 12:11:31 -08005612 if (enabled) {
5613 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5614 mIneligibleDisplaysForPointerCapture.end(),
5615 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5616 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5617 return;
5618 }
5619 }
5620
Prabir Pradhan99987712020-11-10 18:43:05 -08005621 setPointerCaptureLocked(enabled);
5622 } // release lock
5623
5624 // Wake the thread to process command entries.
5625 mLooper->wake();
5626}
5627
Christine Franksb768bb42021-11-29 12:11:31 -08005628void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5629 { // acquire lock
5630 std::scoped_lock _l(mLock);
5631 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5632 if (!isEligible) {
5633 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5634 }
5635 } // release lock
5636}
5637
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005638std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5639 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005640 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005641 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005642 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005643 }
5644 }
5645 }
5646 return std::nullopt;
5647}
5648
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005649sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005650 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005651 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005652 }
5653
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005654 for (const auto& [token, connection] : mConnectionsByToken) {
5655 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005656 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 }
5658 }
Robert Carr4e670e52018-08-15 13:26:12 -07005659
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005660 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661}
5662
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005663std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5664 sp<Connection> connection = getConnectionLocked(connectionToken);
5665 if (connection == nullptr) {
5666 return "<nullptr>";
5667 }
5668 return connection->getInputChannelName();
5669}
5670
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005671void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005672 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005673 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005674}
5675
Prabir Pradhancef936d2021-07-21 16:17:52 +00005676void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5677 const sp<Connection>& connection, uint32_t seq,
5678 bool handled, nsecs_t consumeTime) {
5679 // Handle post-event policy actions.
5680 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5681 if (dispatchEntryIt == connection->waitQueue.end()) {
5682 return;
5683 }
5684 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5685 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5686 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5687 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5688 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5689 }
5690 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5691 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5692 connection->inputChannel->getConnectionToken(),
5693 dispatchEntry->deliveryTime, consumeTime, finishTime);
5694 }
5695
5696 bool restartEvent;
5697 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5698 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5699 restartEvent =
5700 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5701 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5702 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5703 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5704 handled);
5705 } else {
5706 restartEvent = false;
5707 }
5708
5709 // Dequeue the event and start the next cycle.
5710 // Because the lock might have been released, it is possible that the
5711 // contents of the wait queue to have been drained, so we need to double-check
5712 // a few things.
5713 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5714 if (dispatchEntryIt != connection->waitQueue.end()) {
5715 dispatchEntry = *dispatchEntryIt;
5716 connection->waitQueue.erase(dispatchEntryIt);
5717 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5718 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5719 if (!connection->responsive) {
5720 connection->responsive = isConnectionResponsive(*connection);
5721 if (connection->responsive) {
5722 // The connection was unresponsive, and now it's responsive.
5723 processConnectionResponsiveLocked(*connection);
5724 }
5725 }
5726 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005727 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005728 connection->outboundQueue.push_front(dispatchEntry);
5729 traceOutboundQueueLength(*connection);
5730 } else {
5731 releaseDispatchEntry(dispatchEntry);
5732 }
5733 }
5734
5735 // Start the next dispatch cycle for this connection.
5736 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737}
5738
Prabir Pradhancef936d2021-07-21 16:17:52 +00005739void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5740 const sp<IBinder>& newToken) {
5741 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5742 scoped_unlock unlock(mLock);
5743 mPolicy->notifyFocusChanged(oldToken, newToken);
5744 };
5745 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005746}
5747
Prabir Pradhancef936d2021-07-21 16:17:52 +00005748void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5749 auto command = [this, token, x, y]() REQUIRES(mLock) {
5750 scoped_unlock unlock(mLock);
5751 mPolicy->notifyDropWindow(token, x, y);
5752 };
5753 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005754}
5755
Prabir Pradhancef936d2021-07-21 16:17:52 +00005756void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5757 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5758 scoped_unlock unlock(mLock);
5759 mPolicy->notifyUntrustedTouch(obscuringPackage);
5760 };
5761 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005762}
5763
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005764void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5765 if (connection == nullptr) {
5766 LOG_ALWAYS_FATAL("Caller must check for nullness");
5767 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005768 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5769 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005770 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005771 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005772 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005773 return;
5774 }
5775 /**
5776 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5777 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5778 * has changed. This could cause newer entries to time out before the already dispatched
5779 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5780 * processes the events linearly. So providing information about the oldest entry seems to be
5781 * most useful.
5782 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005783 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005784 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5785 std::string reason =
5786 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005787 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005788 ns2ms(currentWait),
5789 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005790 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005791 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005792
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005793 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5794
5795 // Stop waking up for events on this connection, it is already unresponsive
5796 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005797}
5798
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005799void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5800 std::string reason =
5801 StringPrintf("%s does not have a focused window", application->getName().c_str());
5802 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803
Prabir Pradhancef936d2021-07-21 16:17:52 +00005804 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5805 scoped_unlock unlock(mLock);
5806 mPolicy->notifyNoFocusedWindowAnr(application);
5807 };
5808 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005809}
5810
chaviw98318de2021-05-19 16:45:23 -05005811void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005812 const std::string& reason) {
5813 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5814 updateLastAnrStateLocked(windowLabel, reason);
5815}
5816
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005817void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5818 const std::string& reason) {
5819 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005820 updateLastAnrStateLocked(windowLabel, reason);
5821}
5822
5823void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5824 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005826 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 struct tm tm;
5828 localtime_r(&t, &tm);
5829 char timestr[64];
5830 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005831 mLastAnrState.clear();
5832 mLastAnrState += INDENT "ANR:\n";
5833 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005834 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5835 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005836 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837}
5838
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5840 KeyEntry& entry) {
5841 const KeyEvent event = createKeyEvent(entry);
5842 nsecs_t delay = 0;
5843 { // release lock
5844 scoped_unlock unlock(mLock);
5845 android::base::Timer t;
5846 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5847 entry.policyFlags);
5848 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5849 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5850 std::to_string(t.duration().count()).c_str());
5851 }
5852 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853
5854 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005855 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005857 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005859 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5860 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862}
5863
Prabir Pradhancef936d2021-07-21 16:17:52 +00005864void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005865 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005866 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005867 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005868 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005869 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005870 };
5871 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005872}
5873
Prabir Pradhanedd96402022-02-15 01:46:16 -08005874void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5875 std::optional<int32_t> pid) {
5876 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005877 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005878 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005879 };
5880 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005881}
5882
5883/**
5884 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5885 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5886 * command entry to the command queue.
5887 */
5888void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5889 std::string reason) {
5890 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005891 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005892 if (connection.monitor) {
5893 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5894 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005895 pid = findMonitorPidByTokenLocked(connectionToken);
5896 } else {
5897 // The connection is a window
5898 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5899 reason.c_str());
5900 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5901 if (handle != nullptr) {
5902 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005903 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005904 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005905 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906}
5907
5908/**
5909 * Tell the policy that a connection has become responsive so that it can stop ANR.
5910 */
5911void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5912 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005913 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005914 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005915 pid = findMonitorPidByTokenLocked(connectionToken);
5916 } else {
5917 // The connection is a window
5918 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5919 if (handle != nullptr) {
5920 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005921 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005922 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005923 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005924}
5925
Prabir Pradhancef936d2021-07-21 16:17:52 +00005926bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005927 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005928 KeyEntry& keyEntry, bool handled) {
5929 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005930 if (!handled) {
5931 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005933 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005934 return false;
5935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005937 // Get the fallback key state.
5938 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005939 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005941 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005942 connection->inputState.removeFallbackKey(originalKeyCode);
5943 }
5944
5945 if (handled || !dispatchEntry->hasForegroundTarget()) {
5946 // If the application handles the original key for which we previously
5947 // generated a fallback or if the window is not a foreground window,
5948 // then cancel the associated fallback key, if any.
5949 if (fallbackKeyCode != -1) {
5950 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005951 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5952 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5953 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5954 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5955 keyEntry.policyFlags);
5956 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005958 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
5960 mLock.unlock();
5961
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005962 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005963 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964
5965 mLock.lock();
5966
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967 // Cancel the fallback key.
5968 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005970 "application handled the original non-fallback key "
5971 "or is no longer a foreground target, "
5972 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 options.keyCode = fallbackKeyCode;
5974 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976 connection->inputState.removeFallbackKey(originalKeyCode);
5977 }
5978 } else {
5979 // If the application did not handle a non-fallback key, first check
5980 // that we are in a good state to perform unhandled key event processing
5981 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005982 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005984 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5985 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5986 "since this is not an initial down. "
5987 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5988 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5989 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005990 return false;
5991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005994 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5995 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5996 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5997 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5998 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005999 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006000
6001 mLock.unlock();
6002
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006003 bool fallback =
6004 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006005 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006006
6007 mLock.lock();
6008
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006009 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 connection->inputState.removeFallbackKey(originalKeyCode);
6011 return false;
6012 }
6013
6014 // Latch the fallback keycode for this key on an initial down.
6015 // The fallback keycode cannot change at any other point in the lifecycle.
6016 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018 fallbackKeyCode = event.getKeyCode();
6019 } else {
6020 fallbackKeyCode = AKEYCODE_UNKNOWN;
6021 }
6022 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6023 }
6024
6025 ALOG_ASSERT(fallbackKeyCode != -1);
6026
6027 // Cancel the fallback key if the policy decides not to send it anymore.
6028 // We will continue to dispatch the key to the policy but we will no
6029 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006030 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6031 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006032 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6033 if (fallback) {
6034 ALOGD("Unhandled key event: Policy requested to send key %d"
6035 "as a fallback for %d, but on the DOWN it had requested "
6036 "to send %d instead. Fallback canceled.",
6037 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6038 } else {
6039 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6040 "but on the DOWN it had requested to send %d. "
6041 "Fallback canceled.",
6042 originalKeyCode, fallbackKeyCode);
6043 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045
6046 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6047 "canceling fallback, policy no longer desires it");
6048 options.keyCode = fallbackKeyCode;
6049 synthesizeCancelationEventsForConnectionLocked(connection, options);
6050
6051 fallback = false;
6052 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006053 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006054 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055 }
6056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006058 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6059 {
6060 std::string msg;
6061 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6062 connection->inputState.getFallbackKeys();
6063 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6064 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6065 }
6066 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6067 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070
6071 if (fallback) {
6072 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006073 keyEntry.eventTime = event.getEventTime();
6074 keyEntry.deviceId = event.getDeviceId();
6075 keyEntry.source = event.getSource();
6076 keyEntry.displayId = event.getDisplayId();
6077 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6078 keyEntry.keyCode = fallbackKeyCode;
6079 keyEntry.scanCode = event.getScanCode();
6080 keyEntry.metaState = event.getMetaState();
6081 keyEntry.repeatCount = event.getRepeatCount();
6082 keyEntry.downTime = event.getDownTime();
6083 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006084
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006085 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6086 ALOGD("Unhandled key event: Dispatching fallback key. "
6087 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6088 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6089 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 return true; // restart the event
6091 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006092 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6093 ALOGD("Unhandled key event: No fallback key.");
6094 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006095
6096 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006097 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 }
6099 }
6100 return false;
6101}
6102
Prabir Pradhancef936d2021-07-21 16:17:52 +00006103bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006104 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106 return false;
6107}
6108
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109void InputDispatcher::traceInboundQueueLengthLocked() {
6110 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006111 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112 }
6113}
6114
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006115void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116 if (ATRACE_ENABLED()) {
6117 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006118 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6119 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 }
6121}
6122
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006123void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006124 if (ATRACE_ENABLED()) {
6125 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006126 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6127 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 }
6129}
6130
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006131void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006132 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006134 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006135 dumpDispatchStateLocked(dump);
6136
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006137 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006138 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006139 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140 }
6141}
6142
6143void InputDispatcher::monitor() {
6144 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006145 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006147 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148}
6149
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006150/**
6151 * Wake up the dispatcher and wait until it processes all events and commands.
6152 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6153 * this method can be safely called from any thread, as long as you've ensured that
6154 * the work you are interested in completing has already been queued.
6155 */
6156bool InputDispatcher::waitForIdle() {
6157 /**
6158 * Timeout should represent the longest possible time that a device might spend processing
6159 * events and commands.
6160 */
6161 constexpr std::chrono::duration TIMEOUT = 100ms;
6162 std::unique_lock lock(mLock);
6163 mLooper->wake();
6164 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6165 return result == std::cv_status::no_timeout;
6166}
6167
Vishnu Naire798b472020-07-23 13:52:21 -07006168/**
6169 * Sets focus to the window identified by the token. This must be called
6170 * after updating any input window handles.
6171 *
6172 * Params:
6173 * request.token - input channel token used to identify the window that should gain focus.
6174 * request.focusedToken - the token that the caller expects currently to be focused. If the
6175 * specified token does not match the currently focused window, this request will be dropped.
6176 * If the specified focused token matches the currently focused window, the call will succeed.
6177 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6178 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6179 * when requesting the focus change. This determines which request gets
6180 * precedence if there is a focus change request from another source such as pointer down.
6181 */
Vishnu Nair958da932020-08-21 17:12:37 -07006182void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6183 { // acquire lock
6184 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006185 std::optional<FocusResolver::FocusChanges> changes =
6186 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6187 if (changes) {
6188 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006189 }
6190 } // release lock
6191 // Wake up poll loop since it may need to make new input dispatching choices.
6192 mLooper->wake();
6193}
6194
Vishnu Nairc519ff72021-01-21 08:23:08 -08006195void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6196 if (changes.oldFocus) {
6197 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006198 if (focusedInputChannel) {
6199 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6200 "focus left window");
6201 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006202 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006203 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006204 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006205 if (changes.newFocus) {
6206 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006207 }
6208
Prabir Pradhan99987712020-11-10 18:43:05 -08006209 // If a window has pointer capture, then it must have focus. We need to ensure that this
6210 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6211 // If the window loses focus before it loses pointer capture, then the window can be in a state
6212 // where it has pointer capture but not focus, violating the contract. Therefore we must
6213 // dispatch the pointer capture event before the focus event. Since focus events are added to
6214 // the front of the queue (above), we add the pointer capture event to the front of the queue
6215 // after the focus events are added. This ensures the pointer capture event ends up at the
6216 // front.
6217 disablePointerCaptureForcedLocked();
6218
Vishnu Nairc519ff72021-01-21 08:23:08 -08006219 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006220 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006221 }
6222}
Vishnu Nair958da932020-08-21 17:12:37 -07006223
Prabir Pradhan99987712020-11-10 18:43:05 -08006224void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006225 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006226 return;
6227 }
6228
6229 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6230
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006231 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006232 setPointerCaptureLocked(false);
6233 }
6234
6235 if (!mWindowTokenWithPointerCapture) {
6236 // No need to send capture changes because no window has capture.
6237 return;
6238 }
6239
6240 if (mPendingEvent != nullptr) {
6241 // Move the pending event to the front of the queue. This will give the chance
6242 // for the pending event to be dropped if it is a captured event.
6243 mInboundQueue.push_front(mPendingEvent);
6244 mPendingEvent = nullptr;
6245 }
6246
6247 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006248 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006249 mInboundQueue.push_front(std::move(entry));
6250}
6251
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006252void InputDispatcher::setPointerCaptureLocked(bool enable) {
6253 mCurrentPointerCaptureRequest.enable = enable;
6254 mCurrentPointerCaptureRequest.seq++;
6255 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006257 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 };
6259 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006260}
6261
Vishnu Nair599f1412021-06-21 10:39:58 -07006262void InputDispatcher::displayRemoved(int32_t displayId) {
6263 { // acquire lock
6264 std::scoped_lock _l(mLock);
6265 // Set an empty list to remove all handles from the specific display.
6266 setInputWindowsLocked(/* window handles */ {}, displayId);
6267 setFocusedApplicationLocked(displayId, nullptr);
6268 // Call focus resolver to clean up stale requests. This must be called after input windows
6269 // have been removed for the removed display.
6270 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006271 // Reset pointer capture eligibility, regardless of previous state.
6272 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006273 } // release lock
6274
6275 // Wake up poll loop since it may need to make new input dispatching choices.
6276 mLooper->wake();
6277}
6278
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006279void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6280 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006281 // The listener sends the windows as a flattened array. Separate the windows by display for
6282 // more convenient parsing.
6283 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006284 for (const auto& info : windowInfos) {
6285 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6286 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6287 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006288
6289 { // acquire lock
6290 std::scoped_lock _l(mLock);
6291 mDisplayInfos.clear();
6292 for (const auto& displayInfo : displayInfos) {
6293 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6294 }
6295
6296 for (const auto& [displayId, handles] : handlesPerDisplay) {
6297 setInputWindowsLocked(handles, displayId);
6298 }
6299 }
6300 // Wake up poll loop since it may need to make new input dispatching choices.
6301 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006302}
6303
Vishnu Nair062a8672021-09-03 16:07:44 -07006304bool InputDispatcher::shouldDropInput(
6305 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006306 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6307 (windowHandle->getInfo()->inputConfig.test(
6308 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006309 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006310 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6311 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006312 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006313 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006314 windowHandle->getInfo()->displayId);
6315 return true;
6316 }
6317 return false;
6318}
6319
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006320void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6321 const std::vector<gui::WindowInfo>& windowInfos,
6322 const std::vector<DisplayInfo>& displayInfos) {
6323 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6324}
6325
Arthur Hungdfd528e2021-12-08 13:23:04 +00006326void InputDispatcher::cancelCurrentTouch() {
6327 {
6328 std::scoped_lock _l(mLock);
6329 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6330 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6331 "cancel current touch");
6332 synthesizeCancelationEventsForAllConnectionsLocked(options);
6333
6334 mTouchStatesByDisplay.clear();
6335 mLastHoverWindowHandle.clear();
6336 }
6337 // Wake up poll loop since there might be work to do.
6338 mLooper->wake();
6339}
6340
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006341void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6342 std::scoped_lock _l(mLock);
6343 mMonitorDispatchingTimeout = timeout;
6344}
6345
Garfield Tane84e6f92019-08-29 17:28:41 -07006346} // namespace android::inputdispatcher