blob: 06ad6a8f61cf9823a8cb2dfbde74c0952f3eecd0 [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 }
1035 break;
1036 }
1037
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001038 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001039 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1040 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001041 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001045 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001046 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1047 break;
1048 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001049 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001050 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001051 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001052 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001053 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1054 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001055 // nothing to do
1056 break;
1057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
1059
1060 return needWake;
1061}
1062
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001063void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001064 // Do not store sensor event in recent queue to avoid flooding the queue.
1065 if (entry->type != EventEntry::Type::SENSOR) {
1066 mRecentQueue.push_back(entry);
1067 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001068 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001069 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
1071}
1072
chaviw98318de2021-05-19 16:45:23 -05001073sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1074 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001075 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001076 bool addOutsideTargets,
1077 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001078 if (addOutsideTargets && touchState == nullptr) {
1079 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001082 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001083 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001084 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001085 continue;
1086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001088 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001089 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001090 return windowHandle;
1091 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001092
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001093 if (addOutsideTargets &&
1094 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001095 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1096 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
1098 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001099 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100}
1101
Prabir Pradhand65552b2021-10-07 11:23:50 -07001102std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1103 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001104 // Traverse windows from front to back and gather the touched spy windows.
1105 std::vector<sp<WindowInfoHandle>> spyWindows;
1106 const auto& windowHandles = getWindowHandlesLocked(displayId);
1107 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1108 const WindowInfo& info = *windowHandle->getInfo();
1109
Prabir Pradhand65552b2021-10-07 11:23:50 -07001110 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001111 continue;
1112 }
1113 if (!info.isSpy()) {
1114 // The first touched non-spy window was found, so return the spy windows touched so far.
1115 return spyWindows;
1116 }
1117 spyWindows.push_back(windowHandle);
1118 }
1119 return spyWindows;
1120}
1121
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001122void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 const char* reason;
1124 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001125 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001126 if (DEBUG_INBOUND_EVENT_DETAILS) {
1127 ALOGD("Dropped event because policy consumed it.");
1128 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 reason = "inbound event was dropped because the policy consumed it";
1130 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001131 case DropReason::DISABLED:
1132 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 ALOGI("Dropped event because input dispatch is disabled.");
1134 }
1135 reason = "inbound event was dropped because input dispatch is disabled";
1136 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001137 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 ALOGI("Dropped event because of pending overdue app switch.");
1139 reason = "inbound event was dropped because of pending overdue app switch";
1140 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001141 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 ALOGI("Dropped event because the current application is not responding and the user "
1143 "has started interacting with a different application.");
1144 reason = "inbound event was dropped because the current application is not responding "
1145 "and the user has started interacting with a different application";
1146 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001147 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 ALOGI("Dropped event because it is stale.");
1149 reason = "inbound event was dropped because it is stale";
1150 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001151 case DropReason::NO_POINTER_CAPTURE:
1152 ALOGI("Dropped event because there is no window with Pointer Capture.");
1153 reason = "inbound event was dropped because there is no window with Pointer Capture";
1154 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001155 case DropReason::NOT_DROPPED: {
1156 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 }
1160
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001161 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001162 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1164 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001167 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001168 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1169 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1171 synthesizeCancelationEventsForAllConnectionsLocked(options);
1172 } else {
1173 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1174 synthesizeCancelationEventsForAllConnectionsLocked(options);
1175 }
1176 break;
1177 }
Chris Yef59a2f42020-10-16 12:55:26 -07001178 case EventEntry::Type::SENSOR: {
1179 break;
1180 }
arthurhungb89ccb02020-12-30 16:19:01 +08001181 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1182 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001183 break;
1184 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001185 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001186 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001187 case EventEntry::Type::CONFIGURATION_CHANGED:
1188 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001189 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001190 break;
1191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 }
1193}
1194
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001195static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1197 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198}
1199
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001200bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1201 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1202 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1203 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204}
1205
1206bool InputDispatcher::isAppSwitchPendingLocked() {
1207 return mAppSwitchDueTime != LONG_LONG_MAX;
1208}
1209
1210void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1211 mAppSwitchDueTime = LONG_LONG_MAX;
1212
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001213 if (DEBUG_APP_SWITCH) {
1214 if (handled) {
1215 ALOGD("App switch has arrived.");
1216 } else {
1217 ALOGD("App switch was abandoned.");
1218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220}
1221
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001223 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224}
1225
Prabir Pradhancef936d2021-07-21 16:17:52 +00001226bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001227 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 return false;
1229 }
1230
1231 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001232 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001234 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1235 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 return true;
1238}
1239
Prabir Pradhancef936d2021-07-21 16:17:52 +00001240void InputDispatcher::postCommandLocked(Command&& command) {
1241 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242}
1243
1244void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001245 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001247 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 releaseInboundEventLocked(entry);
1249 }
1250 traceInboundQueueLengthLocked();
1251}
1252
1253void InputDispatcher::releasePendingEventLocked() {
1254 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001256 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 }
1258}
1259
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001262 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001263 if (DEBUG_DISPATCH_CYCLE) {
1264 ALOGD("Injected inbound event was dropped.");
1265 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001269 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 }
1271 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272}
1273
1274void InputDispatcher::resetKeyRepeatLocked() {
1275 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001276 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278}
1279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1281 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282
Michael Wright2e732952014-09-24 13:26:59 -07001283 uint32_t policyFlags = entry->policyFlags &
1284 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 std::shared_ptr<KeyEntry> newEntry =
1287 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1288 entry->source, entry->displayId, policyFlags, entry->action,
1289 entry->flags, entry->keyCode, entry->scanCode,
1290 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 newEntry->syntheticRepeat = true;
1293 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296}
1297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001300 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1301 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303
1304 // Reset key repeating in case a keyboard device was added or removed or something.
1305 resetKeyRepeatLocked();
1306
1307 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001308 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1309 scoped_unlock unlock(mLock);
1310 mPolicy->notifyConfigurationChanged(eventTime);
1311 };
1312 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 return true;
1314}
1315
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1317 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001318 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1319 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1320 entry.deviceId);
1321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
liushenxiang42232912021-05-21 20:24:09 +08001323 // Reset key repeating in case a keyboard device was disabled or enabled.
1324 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1325 resetKeyRepeatLocked();
1326 }
1327
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001329 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 synthesizeCancelationEventsForAllConnectionsLocked(options);
1331 return true;
1332}
1333
Vishnu Nairad321cd2020-08-20 16:40:21 -07001334void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001335 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001336 if (mPendingEvent != nullptr) {
1337 // Move the pending event to the front of the queue. This will give the chance
1338 // for the pending event to get dispatched to the newly focused window
1339 mInboundQueue.push_front(mPendingEvent);
1340 mPendingEvent = nullptr;
1341 }
1342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001343 std::unique_ptr<FocusEntry> focusEntry =
1344 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1345 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001346
1347 // This event should go to the front of the queue, but behind all other focus events
1348 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001349 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001350 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001351 [](const std::shared_ptr<EventEntry>& event) {
1352 return event->type == EventEntry::Type::FOCUS;
1353 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001354
1355 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001356 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001357}
1358
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001359void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001360 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001361 if (channel == nullptr) {
1362 return; // Window has gone away
1363 }
1364 InputTarget target;
1365 target.inputChannel = channel;
1366 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1367 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001368 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1369 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001370 std::string reason = std::string("reason=").append(entry->reason);
1371 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001372 dispatchEventLocked(currentTime, entry, {target});
1373}
1374
Prabir Pradhan99987712020-11-10 18:43:05 -08001375void InputDispatcher::dispatchPointerCaptureChangedLocked(
1376 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1377 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001378 dropReason = DropReason::NOT_DROPPED;
1379
Prabir Pradhan99987712020-11-10 18:43:05 -08001380 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001381 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001382
1383 if (entry->pointerCaptureRequest.enable) {
1384 // Enable Pointer Capture.
1385 if (haveWindowWithPointerCapture &&
1386 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1387 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1388 "to the window.");
1389 }
1390 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 // This can happen if a window requests capture and immediately releases capture.
1392 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001394 return;
1395 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001396 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1397 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1398 return;
1399 }
1400
Vishnu Nairc519ff72021-01-21 08:23:08 -08001401 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001402 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1403 mWindowTokenWithPointerCapture = token;
1404 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001405 // Disable Pointer Capture.
1406 // We do not check if the sequence number matches for requests to disable Pointer Capture
1407 // for two reasons:
1408 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1409 // to disable capture with the same sequence number: one generated by
1410 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1411 // Capture being disabled in InputReader.
1412 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1413 // actual Pointer Capture state that affects events being generated by input devices is
1414 // in InputReader.
1415 if (!haveWindowWithPointerCapture) {
1416 // Pointer capture was already forcefully disabled because of focus change.
1417 dropReason = DropReason::NOT_DROPPED;
1418 return;
1419 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001420 token = mWindowTokenWithPointerCapture;
1421 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001422 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001423 setPointerCaptureLocked(false);
1424 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001425 }
1426
1427 auto channel = getInputChannelLocked(token);
1428 if (channel == nullptr) {
1429 // Window has gone away, clean up Pointer Capture state.
1430 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001431 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001432 setPointerCaptureLocked(false);
1433 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001434 return;
1435 }
1436 InputTarget target;
1437 target.inputChannel = channel;
1438 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1439 entry->dispatchInProgress = true;
1440 dispatchEventLocked(currentTime, entry, {target});
1441
1442 dropReason = DropReason::NOT_DROPPED;
1443}
1444
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001445void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1446 const std::shared_ptr<TouchModeEntry>& entry) {
1447 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1448 getWindowHandlesLocked(mFocusedDisplayId);
1449 if (windowHandles.empty()) {
1450 return;
1451 }
1452 const std::vector<InputTarget> inputTargets =
1453 getInputTargetsFromWindowHandlesLocked(windowHandles);
1454 if (inputTargets.empty()) {
1455 return;
1456 }
1457 entry->dispatchInProgress = true;
1458 dispatchEventLocked(currentTime, entry, inputTargets);
1459}
1460
1461std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1462 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1463 std::vector<InputTarget> inputTargets;
1464 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1465 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1466 const sp<IBinder>& token = handle->getToken();
1467 if (token == nullptr) {
1468 continue;
1469 }
1470 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1471 if (channel == nullptr) {
1472 continue; // Window has gone away
1473 }
1474 InputTarget target;
1475 target.inputChannel = channel;
1476 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1477 inputTargets.push_back(target);
1478 }
1479 return inputTargets;
1480}
1481
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001485 if (!entry->dispatchInProgress) {
1486 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1487 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1488 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1489 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001490 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 // We have seen two identical key downs in a row which indicates that the device
1492 // driver is automatically generating key repeats itself. We take note of the
1493 // repeat here, but we disable our own next key repeat timer since it is clear that
1494 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001495 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1496 // Make sure we don't get key down from a different device. If a different
1497 // device Id has same key pressed down, the new device Id will replace the
1498 // current one to hold the key repeat with repeat count reset.
1499 // In the future when got a KEY_UP on the device id, drop it and do not
1500 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1502 resetKeyRepeatLocked();
1503 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1504 } else {
1505 // Not a repeat. Save key down state in case we do see a repeat later.
1506 resetKeyRepeatLocked();
1507 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1508 }
1509 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001510 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1511 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001512 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001513 if (DEBUG_INBOUND_EVENT_DETAILS) {
1514 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1515 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001516 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 resetKeyRepeatLocked();
1518 }
1519
1520 if (entry->repeatCount == 1) {
1521 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1522 } else {
1523 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1524 }
1525
1526 entry->dispatchInProgress = true;
1527
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001528 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530
1531 // Handle case where the policy asked us to try again later last time.
1532 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1533 if (currentTime < entry->interceptKeyWakeupTime) {
1534 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1535 *nextWakeupTime = entry->interceptKeyWakeupTime;
1536 }
1537 return false; // wait until next wakeup
1538 }
1539 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1540 entry->interceptKeyWakeupTime = 0;
1541 }
1542
1543 // Give the policy a chance to intercept the key.
1544 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1545 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001546 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001547 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001548
1549 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1550 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1551 };
1552 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 return false; // wait for the command to run
1554 } else {
1555 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1556 }
1557 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001558 if (*dropReason == DropReason::NOT_DROPPED) {
1559 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 }
1561 }
1562
1563 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001564 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001565 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1567 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001568 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 return true;
1570 }
1571
1572 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001573 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 return false;
1578 }
1579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 return true;
1583 }
1584
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001585 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001586 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587
1588 // Dispatch the key.
1589 dispatchEventLocked(currentTime, entry, inputTargets);
1590 return true;
1591}
1592
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001593void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001594 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1595 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1596 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1597 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1598 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1599 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1600 entry.metaState, entry.repeatCount, entry.downTime);
1601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602}
1603
Prabir Pradhancef936d2021-07-21 16:17:52 +00001604void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1605 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001606 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001607 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1608 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1609 "source=0x%x, sensorType=%s",
1610 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001611 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001612 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001613 auto command = [this, entry]() REQUIRES(mLock) {
1614 scoped_unlock unlock(mLock);
1615
1616 if (entry->accuracyChanged) {
1617 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1618 }
1619 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1620 entry->hwTimestamp, entry->values);
1621 };
1622 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001623}
1624
1625bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001626 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1627 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001628 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001629 }
Chris Yef59a2f42020-10-16 12:55:26 -07001630 { // acquire lock
1631 std::scoped_lock _l(mLock);
1632
1633 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1634 std::shared_ptr<EventEntry> entry = *it;
1635 if (entry->type == EventEntry::Type::SENSOR) {
1636 it = mInboundQueue.erase(it);
1637 releaseInboundEventLocked(entry);
1638 }
1639 }
1640 }
1641 return true;
1642}
1643
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001644bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001645 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001646 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 entry->dispatchInProgress = true;
1650
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001651 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 }
1653
1654 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001655 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001656 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001657 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1658 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 return true;
1660 }
1661
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001662 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663
1664 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001665 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666
1667 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001668 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 if (isPointerEvent) {
1670 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001671 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001672 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 } else {
1675 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001676 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001677 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001679 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 return false;
1681 }
1682
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001683 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001685 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1686 return true;
1687 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001688 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001689 CancelationOptions::Mode mode(isPointerEvent
1690 ? CancelationOptions::CANCEL_POINTER_EVENTS
1691 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1692 CancelationOptions options(mode, "input event injection failed");
1693 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 return true;
1695 }
1696
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001697 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001698 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699
1700 // Dispatch the motion.
1701 if (conflictingPointerActions) {
1702 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001703 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 synthesizeCancelationEventsForAllConnectionsLocked(options);
1705 }
1706 dispatchEventLocked(currentTime, entry, inputTargets);
1707 return true;
1708}
1709
chaviw98318de2021-05-19 16:45:23 -05001710void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001711 bool isExiting, const MotionEntry& motionEntry) {
1712 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1713 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1714 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1715 PointerCoords pointerCoords;
1716 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1717 pointerCoords.transform(windowHandle->getInfo()->transform);
1718
1719 std::unique_ptr<DragEntry> dragEntry =
1720 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1721 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1722 pointerCoords.getY());
1723
1724 enqueueInboundEventLocked(std::move(dragEntry));
1725}
1726
1727void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1728 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1729 if (channel == nullptr) {
1730 return; // Window has gone away
1731 }
1732 InputTarget target;
1733 target.inputChannel = channel;
1734 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1735 entry->dispatchInProgress = true;
1736 dispatchEventLocked(currentTime, entry, {target});
1737}
1738
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001739void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001740 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1741 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1742 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001743 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001744 "metaState=0x%x, buttonState=0x%x,"
1745 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1746 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001747 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1748 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1749 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001751 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1752 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1753 "x=%f, y=%f, pressure=%f, size=%f, "
1754 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1755 "orientation=%f",
1756 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1760 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1761 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1762 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1763 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1764 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1765 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768}
1769
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001770void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1771 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001772 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001773 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001774 if (DEBUG_DISPATCH_CYCLE) {
1775 ALOGD("dispatchEventToCurrentInputTargets");
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001778 updateInteractionTokensLocked(*eventEntry, inputTargets);
1779
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001782 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001784 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001785 sp<Connection> connection =
1786 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001787 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001788 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001790 if (DEBUG_FOCUS) {
1791 ALOGD("Dropping event delivery to target with channel '%s' because it "
1792 "is no longer registered with the input dispatcher.",
1793 inputTarget.inputChannel->getName().c_str());
1794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
1796 }
1797}
1798
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001799void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1800 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1801 // If the policy decides to close the app, we will get a channel removal event via
1802 // unregisterInputChannel, and will clean up the connection that way. We are already not
1803 // sending new pointers to the connection when it blocked, but focused events will continue to
1804 // pile up.
1805 ALOGW("Canceling events for %s because it is unresponsive",
1806 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001807 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001808 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1809 "application not responding");
1810 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 }
1812}
1813
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001814void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001815 if (DEBUG_FOCUS) {
1816 ALOGD("Resetting ANR timeouts.");
1817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818
1819 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001820 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001821 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822}
1823
Tiger Huang721e26f2018-07-24 22:26:19 +08001824/**
1825 * Get the display id that the given event should go to. If this event specifies a valid display id,
1826 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1827 * Focused display is the display that the user most recently interacted with.
1828 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001830 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001832 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001833 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1834 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001835 break;
1836 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001837 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1839 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001840 break;
1841 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001842 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001843 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001844 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001845 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001846 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001847 case EventEntry::Type::SENSOR:
1848 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001849 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001850 return ADISPLAY_ID_NONE;
1851 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001852 }
1853 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1854}
1855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001856bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1857 const char* focusedWindowName) {
1858 if (mAnrTracker.empty()) {
1859 // already processed all events that we waited for
1860 mKeyIsWaitingForEventsTimeout = std::nullopt;
1861 return false;
1862 }
1863
1864 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1865 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001866 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001867 mKeyIsWaitingForEventsTimeout = currentTime +
1868 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1869 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001870 return true;
1871 }
1872
1873 // We still have pending events, and already started the timer
1874 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1875 return true; // Still waiting
1876 }
1877
1878 // Waited too long, and some connection still hasn't processed all motions
1879 // Just send the key to the focused window
1880 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1881 focusedWindowName);
1882 mKeyIsWaitingForEventsTimeout = std::nullopt;
1883 return false;
1884}
1885
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1887 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1888 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001889 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
Tiger Huang721e26f2018-07-24 22:26:19 +08001891 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001892 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001893 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001894 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1895
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 // If there is no currently focused window and no focused application
1897 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1899 ALOGI("Dropping %s event because there is no focused window or focused application in "
1900 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001901 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904
Vishnu Nair062a8672021-09-03 16:07:44 -07001905 // Drop key events if requested by input feature
1906 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1907 return InputEventInjectionResult::FAILED;
1908 }
1909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1911 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1912 // start interacting with another application via touch (app switch). This code can be removed
1913 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1914 // an app is expected to have a focused window.
1915 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1916 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1917 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001918 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1919 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1920 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001921 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001922 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 ALOGW("Waiting because no window has focus but %s may eventually add a "
1924 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001925 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001926 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1929 // Already raised ANR. Drop the event
1930 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001931 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 } else {
1934 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 }
1937 }
1938
1939 // we have a valid, non-null focused window
1940 resetNoFocusedWindowTimeoutLocked();
1941
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001944 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 }
1946
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001947 if (focusedWindowHandle->getInfo()->inputConfig.test(
1948 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 }
1952
1953 // If the event is a key event, then we must wait for all previous events to
1954 // complete before delivering it because previous events may have the
1955 // side-effect of transferring focus to a different window and we want to
1956 // ensure that the following keys are sent to the new window.
1957 //
1958 // Suppose the user touches a button in a window then immediately presses "A".
1959 // If the button causes a pop-up window to appear then we want to ensure that
1960 // the "A" key is delivered to the new pop-up window. This is because users
1961 // often anticipate pending UI changes when typing on a keyboard.
1962 // To obtain this behavior, we must serialize key events with respect to all
1963 // prior input events.
1964 if (entry.type == EventEntry::Type::KEY) {
1965 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1966 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001967 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 }
1970
1971 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001972 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001973 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1974 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975
1976 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001977 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978}
1979
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001980/**
1981 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1982 * that are currently unresponsive.
1983 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001984std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1985 const std::vector<Monitor>& monitors) const {
1986 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001988 [this](const Monitor& monitor) REQUIRES(mLock) {
1989 sp<Connection> connection =
1990 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001991 if (connection == nullptr) {
1992 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001993 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 return false;
1995 }
1996 if (!connection->responsive) {
1997 ALOGW("Unresponsive monitor %s will not get the new gesture",
1998 connection->inputChannel->getName().c_str());
1999 return false;
2000 }
2001 return true;
2002 });
2003 return responsiveMonitors;
2004}
2005
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002006InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2007 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2008 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002009 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 enum InjectionPermission {
2011 INJECTION_PERMISSION_UNKNOWN,
2012 INJECTION_PERMISSION_GRANTED,
2013 INJECTION_PERMISSION_DENIED
2014 };
2015
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 // For security reasons, we defer updating the touch state until we are sure that
2017 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002018 const int32_t displayId = entry.displayId;
2019 const int32_t action = entry.action;
2020 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021
2022 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002023 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05002025 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2026 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002028 // Copy current touch state into tempTouchState.
2029 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2030 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002031 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002032 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002033 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2034 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002035 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002036 }
2037
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002038 bool isSplit = tempTouchState.split;
2039 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2040 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2041 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002042
2043 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2044 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2045 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2046 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2047 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002048 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 bool wrongDevice = false;
2050 if (newGesture) {
2051 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002052 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002053 ALOGI("Dropping event because a pointer for a different device is already down "
2054 "in display %" PRId32,
2055 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002056 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002057 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 switchedDevice = false;
2059 wrongDevice = true;
2060 goto Failed;
2061 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002062 tempTouchState.reset();
2063 tempTouchState.down = down;
2064 tempTouchState.deviceId = entry.deviceId;
2065 tempTouchState.source = entry.source;
2066 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002068 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002069 ALOGI("Dropping move event because a pointer for a different device is already active "
2070 "in display %" PRId32,
2071 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002072 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002073 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002074 switchedDevice = false;
2075 wrongDevice = true;
2076 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 }
2078
2079 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2080 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2081
Garfield Tan00f511d2019-06-12 16:55:40 -07002082 int32_t x;
2083 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002084 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002085 // Always dispatch mouse events to cursor position.
2086 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002087 x = int32_t(entry.xCursorPosition);
2088 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002089 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002090 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2091 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002092 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002093 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002094 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002095 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002096 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002097
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002099 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002100 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2101 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002104 }
2105
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002106 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002108 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2109 // New window supports splitting, but we should never split mouse events.
2110 isSplit = !isFromMouse;
2111 } else if (isSplit) {
2112 // New window does not support splitting but we have already split events.
2113 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002114 newTouchedWindowHandle = nullptr;
2115 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002116 } else {
2117 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002118 // be delivered to a new window which supports split touch. Pointers from a mouse device
2119 // should never be split.
2120 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 }
2122
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002123 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002124 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002125 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2126 newHoverWindowHandle = nullptr;
2127 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002128 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002129 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002130 }
2131
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002132 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002133 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002134 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002135 // Process the foreground window first so that it is the first to receive the event.
2136 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002137 }
2138
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002139 if (newTouchedWindows.empty()) {
2140 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2141 x, y, displayId);
2142 injectionResult = InputEventInjectionResult::FAILED;
2143 goto Failed;
2144 }
2145
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002146 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2147 const WindowInfo& info = *windowHandle->getInfo();
2148
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002149 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002150 ALOGI("Not sending touch event to %s because it is paused",
2151 windowHandle->getName().c_str());
2152 continue;
2153 }
2154
2155 // Ensure the window has a connection and the connection is responsive
2156 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2157 if (!isResponsive) {
2158 ALOGW("Not sending touch gesture to %s because it is not responsive",
2159 windowHandle->getName().c_str());
2160 continue;
2161 }
2162
2163 // Drop events that can't be trusted due to occlusion
2164 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2165 TouchOcclusionInfo occlusionInfo =
2166 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2167 if (!isTouchTrustedLocked(occlusionInfo)) {
2168 if (DEBUG_TOUCH_OCCLUSION) {
2169 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2170 for (const auto& log : occlusionInfo.debugInfo) {
2171 ALOGD("%s", log.c_str());
2172 }
2173 }
2174 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2175 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2176 ALOGW("Dropping untrusted touch event due to %s/%d",
2177 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2178 continue;
2179 }
2180 }
2181 }
2182
2183 // Drop touch events if requested by input feature
2184 if (shouldDropInput(entry, windowHandle)) {
2185 continue;
2186 }
2187
2188 // Set target flags.
2189 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2190
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002191 if (!info.isSpy()) {
2192 // There should only be one new foreground (non-spy) window at this location.
2193 targetFlags |= InputTarget::FLAG_FOREGROUND;
2194 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195
2196 if (isSplit) {
2197 targetFlags |= InputTarget::FLAG_SPLIT;
2198 }
2199 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2200 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2201 } else if (isWindowObscuredLocked(windowHandle)) {
2202 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2203 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002204
2205 // Update the temporary touch state.
2206 BitSet32 pointerIds;
2207 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002208 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002209 pointerIds.markBit(pointerId);
2210 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002211
2212 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 } else {
2215 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2216
2217 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002219 if (DEBUG_FOCUS) {
2220 ALOGD("Dropping event because the pointer is not down or we previously "
2221 "dropped the pointer down event in display %" PRId32,
2222 displayId);
2223 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002224 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 goto Failed;
2226 }
2227
arthurhung6d4bed92021-03-17 11:59:33 +08002228 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002229
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002231 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002232 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2234 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235
Prabir Pradhand65552b2021-10-07 11:23:50 -07002236 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002237 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002238 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002239 newTouchedWindowHandle =
2240 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002241
2242 // Drop touch events if requested by input feature
2243 if (newTouchedWindowHandle != nullptr &&
2244 shouldDropInput(entry, newTouchedWindowHandle)) {
2245 newTouchedWindowHandle = nullptr;
2246 }
2247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2249 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002250 if (DEBUG_FOCUS) {
2251 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2252 oldTouchedWindowHandle->getName().c_str(),
2253 newTouchedWindowHandle->getName().c_str(), displayId);
2254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002256 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2257 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2258 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259
2260 // Make a slippery entrance into the new window.
2261 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002262 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
2264
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 int32_t targetFlags =
2266 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 if (isSplit) {
2268 targetFlags |= InputTarget::FLAG_SPLIT;
2269 }
2270 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2271 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002272 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2273 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
2276 BitSet32 pointerIds;
2277 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002278 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282 }
2283 }
2284
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002287 // Let the previous window know that the hover sequence is over, unless we already did
2288 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002289 if (mLastHoverWindowHandle != nullptr &&
2290 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2291 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002292 if (DEBUG_HOVER) {
2293 ALOGD("Sending hover exit event to window %s.",
2294 mLastHoverWindowHandle->getName().c_str());
2295 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002296 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2297 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
2299
Garfield Tandf26e862020-07-01 20:18:19 -07002300 // Let the new window know that the hover sequence is starting, unless we already did it
2301 // when dispatching it as is to newTouchedWindowHandle.
2302 if (newHoverWindowHandle != nullptr &&
2303 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2304 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002305 if (DEBUG_HOVER) {
2306 ALOGD("Sending hover enter event to window %s.",
2307 newHoverWindowHandle->getName().c_str());
2308 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002309 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2310 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2311 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313 }
2314
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002315 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2316 // of the touched windows we previously found if they became paused or unresponsive or were
2317 // removed.
2318 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2319 [](const TouchedWindow& touchedWindow) {
2320 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2321 touchedWindow.windowHandle->getInfo()->isSpy();
2322 })) {
2323 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2324 displayId);
2325 injectionResult = InputEventInjectionResult::FAILED;
2326 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
2328
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002329 // Check permission to inject into all touched foreground windows.
2330 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2331 [this, &entry](const TouchedWindow& touchedWindow) {
2332 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2333 !checkInjectionPermission(touchedWindow.windowHandle,
2334 entry.injectionState);
2335 })) {
2336 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2337 injectionPermission = INJECTION_PERMISSION_DENIED;
2338 goto Failed;
2339 }
2340 // Permission granted to inject into all touched foreground windows.
2341 injectionPermission = INJECTION_PERMISSION_GRANTED;
2342
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 // Check whether windows listening for outside touches are owned by the same UID. If it is
2344 // set the policy flag that we will not reveal coordinate information to this window.
2345 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002346 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002347 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002348 if (foregroundWindowHandle) {
2349 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002350 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002351 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002352 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2353 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2354 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002355 InputTarget::FLAG_ZERO_COORDS,
2356 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359 }
2360 }
2361 }
2362
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 // If this is the first pointer going down and the touched window has a wallpaper
2364 // then also add the touched wallpaper windows so they are locked in for the duration
2365 // of the touch gesture.
2366 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2367 // engine only supports touch events. We would need to add a mechanism similar
2368 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2369 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002370 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002371 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002372 if (foregroundWindowHandle &&
2373 foregroundWindowHandle->getInfo()->inputConfig.test(
2374 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002375 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002376 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002377 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2378 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002380 windowHandle->getInfo()->inputConfig.test(
2381 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 .addOrUpdateWindow(windowHandle,
2384 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2385 InputTarget::
2386 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2387 InputTarget::FLAG_DISPATCH_AS_IS,
2388 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
2390 }
2391 }
2392 }
2393
2394 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002395 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002397 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002399 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 }
2401
2402 // Drop the outside or hover touch windows since we will not care about them
2403 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002404 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405
2406Failed:
2407 // Check injection permission once and for all.
2408 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002409 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 injectionPermission = INJECTION_PERMISSION_GRANTED;
2411 } else {
2412 injectionPermission = INJECTION_PERMISSION_DENIED;
2413 }
2414 }
2415
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002416 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2417 return injectionResult;
2418 }
2419
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002421 if (!wrongDevice) {
2422 if (switchedDevice) {
2423 if (DEBUG_FOCUS) {
2424 ALOGD("Conflicting pointer actions: Switched to a different device.");
2425 }
2426 *outConflictingPointerActions = true;
2427 }
2428
2429 if (isHoverAction) {
2430 // Started hovering, therefore no longer down.
2431 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002432 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002433 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2434 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 *outConflictingPointerActions = true;
2437 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002438 tempTouchState.reset();
2439 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2440 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2441 tempTouchState.deviceId = entry.deviceId;
2442 tempTouchState.source = entry.source;
2443 tempTouchState.displayId = displayId;
2444 }
2445 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2446 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2447 // All pointers up or canceled.
2448 tempTouchState.reset();
2449 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2450 // First pointer went down.
2451 if (oldState && oldState->down) {
2452 if (DEBUG_FOCUS) {
2453 ALOGD("Conflicting pointer actions: Down received while already down.");
2454 }
2455 *outConflictingPointerActions = true;
2456 }
2457 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2458 // One pointer went up.
2459 if (isSplit) {
2460 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2461 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002463 for (size_t i = 0; i < tempTouchState.windows.size();) {
2464 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2465 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2466 touchedWindow.pointerIds.clearBit(pointerId);
2467 if (touchedWindow.pointerIds.isEmpty()) {
2468 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2469 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002472 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002474 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002475 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002476
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002477 // Save changes unless the action was scroll in which case the temporary touch
2478 // state was only valid for this one action.
2479 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2480 if (tempTouchState.displayId >= 0) {
2481 mTouchStatesByDisplay[displayId] = tempTouchState;
2482 } else {
2483 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002487 // Update hover state.
2488 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
2490
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 return injectionResult;
2492}
2493
arthurhung6d4bed92021-03-17 11:59:33 +08002494void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002495 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2496 // have an explicit reason to support it.
2497 constexpr bool isStylus = false;
2498
chaviw98318de2021-05-19 16:45:23 -05002499 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002500 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002501 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002502 if (dropWindow) {
2503 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002504 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002505 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002506 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002507 }
2508 mDragState.reset();
2509}
2510
2511void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2512 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002513 return;
2514 }
2515
arthurhung6d4bed92021-03-17 11:59:33 +08002516 if (!mDragState->isStartDrag) {
2517 mDragState->isStartDrag = true;
2518 mDragState->isStylusButtonDownAtStart =
2519 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2520 }
2521
arthurhungb89ccb02020-12-30 16:19:01 +08002522 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2523 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2524 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2525 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002526 // Handle the special case : stylus button no longer pressed.
2527 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2528 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2529 finishDragAndDrop(entry.displayId, x, y);
2530 return;
2531 }
2532
Prabir Pradhand65552b2021-10-07 11:23:50 -07002533 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2534 // we have an explicit reason to support it.
2535 constexpr bool isStylus = false;
2536
chaviw98318de2021-05-19 16:45:23 -05002537 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002538 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002539 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002540 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002541 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2542 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2543 if (mDragState->dragHoverWindowHandle != nullptr) {
2544 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2545 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002546 }
arthurhung6d4bed92021-03-17 11:59:33 +08002547 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002548 }
2549 // enqueue drag location if needed.
2550 if (hoverWindowHandle != nullptr) {
2551 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2552 }
arthurhung6d4bed92021-03-17 11:59:33 +08002553 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2554 finishDragAndDrop(entry.displayId, x, y);
2555 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002556 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002557 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002558 }
2559}
2560
chaviw98318de2021-05-19 16:45:23 -05002561void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002562 int32_t targetFlags, BitSet32 pointerIds,
2563 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002564 std::vector<InputTarget>::iterator it =
2565 std::find_if(inputTargets.begin(), inputTargets.end(),
2566 [&windowHandle](const InputTarget& inputTarget) {
2567 return inputTarget.inputChannel->getConnectionToken() ==
2568 windowHandle->getToken();
2569 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002570
chaviw98318de2021-05-19 16:45:23 -05002571 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002572
2573 if (it == inputTargets.end()) {
2574 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002575 std::shared_ptr<InputChannel> inputChannel =
2576 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002577 if (inputChannel == nullptr) {
2578 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2579 return;
2580 }
2581 inputTarget.inputChannel = inputChannel;
2582 inputTarget.flags = targetFlags;
2583 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002584 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2585 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002586 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002587 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002588 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002589 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002590 inputTargets.push_back(inputTarget);
2591 it = inputTargets.end() - 1;
2592 }
2593
2594 ALOG_ASSERT(it->flags == targetFlags);
2595 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2596
chaviw1ff3d1e2020-07-01 15:53:47 -07002597 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598}
2599
Michael Wright3dd60e22019-03-27 22:06:44 +00002600void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002601 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002602 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2603 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002604
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002605 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2606 InputTarget target;
2607 target.inputChannel = monitor.inputChannel;
2608 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2609 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2610 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002611 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002612 target.setDefaultPointerTransform(target.displayTransform);
2613 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615}
2616
chaviw98318de2021-05-19 16:45:23 -05002617bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 const InjectionState* injectionState) {
2619 if (injectionState &&
2620 (windowHandle == nullptr ||
2621 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2622 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002623 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002625 "owned by uid %d",
2626 injectionState->injectorPid, injectionState->injectorUid,
2627 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 } else {
2629 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002630 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 }
2632 return false;
2633 }
2634 return true;
2635}
2636
Robert Carrc9bf1d32020-04-13 17:21:08 -07002637/**
2638 * Indicate whether one window handle should be considered as obscuring
2639 * another window handle. We only check a few preconditions. Actually
2640 * checking the bounds is left to the caller.
2641 */
chaviw98318de2021-05-19 16:45:23 -05002642static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2643 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002644 // Compare by token so cloned layers aren't counted
2645 if (haveSameToken(windowHandle, otherHandle)) {
2646 return false;
2647 }
2648 auto info = windowHandle->getInfo();
2649 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002650 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002651 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002652 } else if (otherInfo->alpha == 0 &&
2653 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002654 // Those act as if they were invisible, so we don't need to flag them.
2655 // We do want to potentially flag touchable windows even if they have 0
2656 // opacity, since they can consume touches and alter the effects of the
2657 // user interaction (eg. apps that rely on
2658 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2659 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2660 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002661 } else if (info->ownerUid == otherInfo->ownerUid) {
2662 // If ownerUid is the same we don't generate occlusion events as there
2663 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002664 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002665 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002666 return false;
2667 } else if (otherInfo->displayId != info->displayId) {
2668 return false;
2669 }
2670 return true;
2671}
2672
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002673/**
2674 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2675 * untrusted, one should check:
2676 *
2677 * 1. If result.hasBlockingOcclusion is true.
2678 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2679 * BLOCK_UNTRUSTED.
2680 *
2681 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2682 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2683 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2684 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2685 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2686 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2687 *
2688 * If neither of those is true, then it means the touch can be allowed.
2689 */
2690InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002691 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2692 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002693 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002694 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002695 TouchOcclusionInfo info;
2696 info.hasBlockingOcclusion = false;
2697 info.obscuringOpacity = 0;
2698 info.obscuringUid = -1;
2699 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002700 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002701 if (windowHandle == otherHandle) {
2702 break; // All future windows are below us. Exit early.
2703 }
chaviw98318de2021-05-19 16:45:23 -05002704 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002705 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2706 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002707 if (DEBUG_TOUCH_OCCLUSION) {
2708 info.debugInfo.push_back(
2709 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2710 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002711 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2712 // we perform the checks below to see if the touch can be propagated or not based on the
2713 // window's touch occlusion mode
2714 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2715 info.hasBlockingOcclusion = true;
2716 info.obscuringUid = otherInfo->ownerUid;
2717 info.obscuringPackage = otherInfo->packageName;
2718 break;
2719 }
2720 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2721 uint32_t uid = otherInfo->ownerUid;
2722 float opacity =
2723 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2724 // Given windows A and B:
2725 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2726 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2727 opacityByUid[uid] = opacity;
2728 if (opacity > info.obscuringOpacity) {
2729 info.obscuringOpacity = opacity;
2730 info.obscuringUid = uid;
2731 info.obscuringPackage = otherInfo->packageName;
2732 }
2733 }
2734 }
2735 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002736 if (DEBUG_TOUCH_OCCLUSION) {
2737 info.debugInfo.push_back(
2738 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2739 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002740 return info;
2741}
2742
chaviw98318de2021-05-19 16:45:23 -05002743std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002744 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002745 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2746 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2747 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2748 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002749 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2750 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2751 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2752 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2753 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002754 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002755 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002756}
2757
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002758bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2759 if (occlusionInfo.hasBlockingOcclusion) {
2760 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2761 occlusionInfo.obscuringUid);
2762 return false;
2763 }
2764 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2765 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2766 "%.2f, maximum allowed = %.2f)",
2767 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2768 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2769 return false;
2770 }
2771 return true;
2772}
2773
chaviw98318de2021-05-19 16:45:23 -05002774bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002777 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2778 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002779 if (windowHandle == otherHandle) {
2780 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 }
chaviw98318de2021-05-19 16:45:23 -05002782 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002783 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002784 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 return true;
2786 }
2787 }
2788 return false;
2789}
2790
chaviw98318de2021-05-19 16:45:23 -05002791bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002792 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002793 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2794 const WindowInfo* windowInfo = windowHandle->getInfo();
2795 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002796 if (windowHandle == otherHandle) {
2797 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002798 }
chaviw98318de2021-05-19 16:45:23 -05002799 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002800 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002801 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002802 return true;
2803 }
2804 }
2805 return false;
2806}
2807
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002808std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002809 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002810 if (applicationHandle != nullptr) {
2811 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002812 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 } else {
2814 return applicationHandle->getName();
2815 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002816 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002817 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002819 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821}
2822
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002823void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002824 if (!isUserActivityEvent(eventEntry)) {
2825 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002826 return;
2827 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002828 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002829 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002830 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002831 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002832 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002833 if (DEBUG_DISPATCH_CYCLE) {
2834 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 return;
2837 }
2838 }
2839
2840 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002841 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002842 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002843 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2844 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845 return;
2846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002848 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 eventType = USER_ACTIVITY_EVENT_TOUCH;
2850 }
2851 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002853 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002854 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2855 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002856 return;
2857 }
2858 eventType = USER_ACTIVITY_EVENT_BUTTON;
2859 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002861 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002862 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002863 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002864 break;
2865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
2867
Prabir Pradhancef936d2021-07-21 16:17:52 +00002868 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2869 REQUIRES(mLock) {
2870 scoped_unlock unlock(mLock);
2871 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2872 };
2873 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874}
2875
2876void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002878 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002879 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002880 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002882 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002883 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002884 ATRACE_NAME(message.c_str());
2885 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002886 if (DEBUG_DISPATCH_CYCLE) {
2887 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2888 "globalScaleFactor=%f, pointerIds=0x%x %s",
2889 connection->getInputChannelName().c_str(), inputTarget.flags,
2890 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2891 inputTarget.getPointerInfoString().c_str());
2892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
2894 // Skip this event if the connection status is not normal.
2895 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002896 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002897 if (DEBUG_DISPATCH_CYCLE) {
2898 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002899 connection->getInputChannelName().c_str(),
2900 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 return;
2903 }
2904
2905 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002906 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2907 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2908 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002909 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002911 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002912 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002913 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002914 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 if (!splitMotionEntry) {
2916 return; // split event was dropped
2917 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002918 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2919 std::string reason = std::string("reason=pointer cancel on split window");
2920 android_log_event_list(LOGTAG_INPUT_CANCEL)
2921 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2922 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002923 if (DEBUG_FOCUS) {
2924 ALOGD("channel '%s' ~ Split motion event.",
2925 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002927 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002928 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2929 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 return;
2931 }
2932 }
2933
2934 // Not splitting. Enqueue dispatch entries for the event as is.
2935 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2936}
2937
2938void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002940 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002941 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002942 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002944 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002945 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002946 ATRACE_NAME(message.c_str());
2947 }
2948
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002949 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
2951 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002952 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002954 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002956 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002958 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002960 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002962 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964
2965 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002966 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 startDispatchCycleLocked(currentTime, connection);
2968 }
2969}
2970
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002972 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002973 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002975 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2977 connection->getInputChannelName().c_str(),
2978 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002979 ATRACE_NAME(message.c_str());
2980 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002981 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 if (!(inputTargetFlags & dispatchMode)) {
2983 return;
2984 }
2985 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2986
2987 // This is a new event.
2988 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002989 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002990 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002992 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2993 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002994 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002996 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002997 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002998 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002999 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003000 dispatchEntry->resolvedAction = keyEntry.action;
3001 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3004 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003005 if (DEBUG_DISPATCH_CYCLE) {
3006 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3007 "event",
3008 connection->getInputChannelName().c_str());
3009 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 return; // skip the inconsistent event
3011 }
3012 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003015 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003016 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003017 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3018 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3019 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3020 static_cast<int32_t>(IdGenerator::Source::OTHER);
3021 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003022 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3023 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3024 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3025 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3026 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3027 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3028 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3029 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3030 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3032 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003033 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003034 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 }
3036 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003037 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3038 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003039 if (DEBUG_DISPATCH_CYCLE) {
3040 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3041 "enter event",
3042 connection->getInputChannelName().c_str());
3043 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003044 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3045 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003049 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3051 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3052 }
3053 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3054 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003057 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3058 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003059 if (DEBUG_DISPATCH_CYCLE) {
3060 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3061 "event",
3062 connection->getInputChannelName().c_str());
3063 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 return; // skip the inconsistent event
3065 }
3066
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003067 dispatchEntry->resolvedEventId =
3068 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3069 ? mIdGenerator.nextId()
3070 : motionEntry.id;
3071 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3072 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3073 ") to MotionEvent(id=0x%" PRIx32 ").",
3074 motionEntry.id, dispatchEntry->resolvedEventId);
3075 ATRACE_NAME(message.c_str());
3076 }
3077
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003078 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3079 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3080 // Skip reporting pointer down outside focus to the policy.
3081 break;
3082 }
3083
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003084 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003085 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086
3087 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003089 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003090 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003091 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3092 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003093 break;
3094 }
Chris Yef59a2f42020-10-16 12:55:26 -07003095 case EventEntry::Type::SENSOR: {
3096 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3097 break;
3098 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003099 case EventEntry::Type::CONFIGURATION_CHANGED:
3100 case EventEntry::Type::DEVICE_RESET: {
3101 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003102 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003103 break;
3104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 }
3106
3107 // Remember that we are waiting for this dispatch to complete.
3108 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003109 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 }
3111
3112 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003113 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003114 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003115}
3116
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003117/**
3118 * This function is purely for debugging. It helps us understand where the user interaction
3119 * was taking place. For example, if user is touching launcher, we will see a log that user
3120 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3121 * We will see both launcher and wallpaper in that list.
3122 * Once the interaction with a particular set of connections starts, no new logs will be printed
3123 * until the set of interacted connections changes.
3124 *
3125 * The following items are skipped, to reduce the logspam:
3126 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3127 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3128 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3129 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3130 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003131 */
3132void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3133 const std::vector<InputTarget>& targets) {
3134 // Skip ACTION_UP events, and all events other than keys and motions
3135 if (entry.type == EventEntry::Type::KEY) {
3136 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3137 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3138 return;
3139 }
3140 } else if (entry.type == EventEntry::Type::MOTION) {
3141 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3142 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3143 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3144 return;
3145 }
3146 } else {
3147 return; // Not a key or a motion
3148 }
3149
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003150 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003151 std::vector<sp<Connection>> newConnections;
3152 for (const InputTarget& target : targets) {
3153 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3154 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3155 continue; // Skip windows that receive ACTION_OUTSIDE
3156 }
3157
3158 sp<IBinder> token = target.inputChannel->getConnectionToken();
3159 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003160 if (connection == nullptr) {
3161 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003162 }
3163 newConnectionTokens.insert(std::move(token));
3164 newConnections.emplace_back(connection);
3165 }
3166 if (newConnectionTokens == mInteractionConnectionTokens) {
3167 return; // no change
3168 }
3169 mInteractionConnectionTokens = newConnectionTokens;
3170
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003171 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003172 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003173 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003174 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003175 std::string message = "Interaction with: " + targetList;
3176 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003177 message += "<none>";
3178 }
3179 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3180}
3181
chaviwfd6d3512019-03-25 13:23:49 -07003182void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003183 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003184 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003185 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3186 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003187 return;
3188 }
3189
Vishnu Nairc519ff72021-01-21 08:23:08 -08003190 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003191 if (focusedToken == token) {
3192 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003193 return;
3194 }
3195
Prabir Pradhancef936d2021-07-21 16:17:52 +00003196 auto command = [this, token]() REQUIRES(mLock) {
3197 scoped_unlock unlock(mLock);
3198 mPolicy->onPointerDownOutsideFocus(token);
3199 };
3200 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201}
3202
3203void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003205 if (ATRACE_ENABLED()) {
3206 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003208 ATRACE_NAME(message.c_str());
3209 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003210 if (DEBUG_DISPATCH_CYCLE) {
3211 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003214 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003215 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003217 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003218 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219
3220 // Publish the event.
3221 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003222 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3223 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003224 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003225 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3226 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003229 status = connection->inputPublisher
3230 .publishKeyEvent(dispatchEntry->seq,
3231 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3232 keyEntry.source, keyEntry.displayId,
3233 std::move(hmac), dispatchEntry->resolvedAction,
3234 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3235 keyEntry.scanCode, keyEntry.metaState,
3236 keyEntry.repeatCount, keyEntry.downTime,
3237 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 }
3240
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003241 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003242 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003245 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246
chaviw82357092020-01-28 13:13:06 -08003247 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003248 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3250 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003251 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003252 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3253 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003254 // Don't apply window scale here since we don't want scale to affect raw
3255 // coordinates. The scale will be sent back to the client and applied
3256 // later when requesting relative coordinates.
3257 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3258 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 }
3260 usingCoords = scaledCoords;
3261 }
3262 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003263 // We don't want the dispatch target to know.
3264 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003265 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003266 scaledCoords[i].clear();
3267 }
3268 usingCoords = scaledCoords;
3269 }
3270 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003271
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003272 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003273
3274 // Publish the motion event.
3275 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003276 .publishMotionEvent(dispatchEntry->seq,
3277 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003278 motionEntry.deviceId, motionEntry.source,
3279 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003280 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003281 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003282 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003283 motionEntry.edgeFlags, motionEntry.metaState,
3284 motionEntry.buttonState,
3285 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003286 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003287 motionEntry.xPrecision, motionEntry.yPrecision,
3288 motionEntry.xCursorPosition,
3289 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003290 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 motionEntry.downTime, motionEntry.eventTime,
3292 motionEntry.pointerCount,
3293 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 break;
3295 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003296
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003297 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003298 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003299 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003300 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003301 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003302 break;
3303 }
3304
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003305 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3306 const TouchModeEntry& touchModeEntry =
3307 static_cast<const TouchModeEntry&>(eventEntry);
3308 status = connection->inputPublisher
3309 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3310 touchModeEntry.inTouchMode);
3311
3312 break;
3313 }
3314
Prabir Pradhan99987712020-11-10 18:43:05 -08003315 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3316 const auto& captureEntry =
3317 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3318 status = connection->inputPublisher
3319 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003320 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003321 break;
3322 }
3323
arthurhungb89ccb02020-12-30 16:19:01 +08003324 case EventEntry::Type::DRAG: {
3325 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3326 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3327 dragEntry.id, dragEntry.x,
3328 dragEntry.y,
3329 dragEntry.isExiting);
3330 break;
3331 }
3332
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003333 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003334 case EventEntry::Type::DEVICE_RESET:
3335 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003336 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003337 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
3341
3342 // Check the result.
3343 if (status) {
3344 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003345 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 "This is unexpected because the wait queue is empty, so the pipe "
3348 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003349 "event to it, status=%s(%d)",
3350 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3351 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3353 } else {
3354 // Pipe is full and we are waiting for the app to finish process some events
3355 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003356 if (DEBUG_DISPATCH_CYCLE) {
3357 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3358 "waiting for the application to catch up",
3359 connection->getInputChannelName().c_str());
3360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 }
3362 } else {
3363 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003364 "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 }
3369 return;
3370 }
3371
3372 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003373 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3374 connection->outboundQueue.end(),
3375 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003376 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003377 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003378 if (connection->responsive) {
3379 mAnrTracker.insert(dispatchEntry->timeoutTime,
3380 connection->inputChannel->getConnectionToken());
3381 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003382 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
3384}
3385
chaviw09c8d2d2020-08-24 15:48:26 -07003386std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3387 size_t size;
3388 switch (event.type) {
3389 case VerifiedInputEvent::Type::KEY: {
3390 size = sizeof(VerifiedKeyEvent);
3391 break;
3392 }
3393 case VerifiedInputEvent::Type::MOTION: {
3394 size = sizeof(VerifiedMotionEvent);
3395 break;
3396 }
3397 }
3398 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3399 return mHmacKeyManager.sign(start, size);
3400}
3401
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003402const std::array<uint8_t, 32> InputDispatcher::getSignature(
3403 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003404 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3405 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003406 // Only sign events up and down events as the purely move events
3407 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003408 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003409 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003410
3411 VerifiedMotionEvent verifiedEvent =
3412 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3413 verifiedEvent.actionMasked = actionMasked;
3414 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3415 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003416}
3417
3418const std::array<uint8_t, 32> InputDispatcher::getSignature(
3419 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3420 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3421 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3422 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003423 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003424}
3425
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003428 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003429 if (DEBUG_DISPATCH_CYCLE) {
3430 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3431 connection->getInputChannelName().c_str(), seq, toString(handled));
3432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003434 if (connection->status == Connection::Status::BROKEN ||
3435 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 return;
3437 }
3438
3439 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003440 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3441 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3442 };
3443 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444}
3445
3446void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 const sp<Connection>& connection,
3448 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003449 if (DEBUG_DISPATCH_CYCLE) {
3450 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3451 connection->getInputChannelName().c_str(), toString(notify));
3452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453
3454 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003455 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003456 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003457 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003458 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459
3460 // The connection appears to be unrecoverably broken.
3461 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003462 if (connection->status == Connection::Status::NORMAL) {
3463 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464
3465 if (notify) {
3466 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003467 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3468 connection->getInputChannelName().c_str());
3469
3470 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003471 scoped_unlock unlock(mLock);
3472 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3473 };
3474 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
3476 }
3477}
3478
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003479void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3480 while (!queue.empty()) {
3481 DispatchEntry* dispatchEntry = queue.front();
3482 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003483 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 }
3485}
3486
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003487void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003489 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
3491 delete dispatchEntry;
3492}
3493
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003494int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3495 std::scoped_lock _l(mLock);
3496 sp<Connection> connection = getConnectionLocked(connectionToken);
3497 if (connection == nullptr) {
3498 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3499 connectionToken.get(), events);
3500 return 0; // remove the callback
3501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003503 bool notify;
3504 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3505 if (!(events & ALOOPER_EVENT_INPUT)) {
3506 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3507 "events=0x%x",
3508 connection->getInputChannelName().c_str(), events);
3509 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 }
3511
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003512 nsecs_t currentTime = now();
3513 bool gotOne = false;
3514 status_t status = OK;
3515 for (;;) {
3516 Result<InputPublisher::ConsumerResponse> result =
3517 connection->inputPublisher.receiveConsumerResponse();
3518 if (!result.ok()) {
3519 status = result.error().code();
3520 break;
3521 }
3522
3523 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3524 const InputPublisher::Finished& finish =
3525 std::get<InputPublisher::Finished>(*result);
3526 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3527 finish.consumeTime);
3528 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003529 if (shouldReportMetricsForConnection(*connection)) {
3530 const InputPublisher::Timeline& timeline =
3531 std::get<InputPublisher::Timeline>(*result);
3532 mLatencyTracker
3533 .trackGraphicsLatency(timeline.inputEventId,
3534 connection->inputChannel->getConnectionToken(),
3535 std::move(timeline.graphicsTimeline));
3536 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003537 }
3538 gotOne = true;
3539 }
3540 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003541 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003542 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 return 1;
3544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003547 notify = status != DEAD_OBJECT || !connection->monitor;
3548 if (notify) {
3549 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3550 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3551 status);
3552 }
3553 } else {
3554 // Monitor channels are never explicitly unregistered.
3555 // We do it automatically when the remote endpoint is closed so don't warn about them.
3556 const bool stillHaveWindowHandle =
3557 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3558 notify = !connection->monitor && stillHaveWindowHandle;
3559 if (notify) {
3560 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3561 connection->getInputChannelName().c_str(), events);
3562 }
3563 }
3564
3565 // Remove the channel.
3566 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3567 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568}
3569
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003570void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003572 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003573 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575}
3576
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003577void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003578 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003579 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003580 for (const Monitor& monitor : monitors) {
3581 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003582 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003583 }
3584}
3585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003587 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003588 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003589 if (connection == nullptr) {
3590 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003592
3593 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594}
3595
3596void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3597 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003598 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 return;
3600 }
3601
3602 nsecs_t currentTime = now();
3603
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003604 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003605 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003607 if (cancelationEvents.empty()) {
3608 return;
3609 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003610 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3611 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3612 "with reality: %s, mode=%d.",
3613 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3614 options.mode);
3615 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003616
Arthur Hungb3307ee2021-10-14 10:57:37 +00003617 std::string reason = std::string("reason=").append(options.reason);
3618 android_log_event_list(LOGTAG_INPUT_CANCEL)
3619 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3620
Svet Ganov5d3bc372020-01-26 23:11:07 -08003621 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003622 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3624 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003625 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003626 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003627 target.globalScaleFactor = windowInfo->globalScaleFactor;
3628 }
3629 target.inputChannel = connection->inputChannel;
3630 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3631
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003632 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003633 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003634 switch (cancelationEventEntry->type) {
3635 case EventEntry::Type::KEY: {
3636 logOutboundKeyDetails("cancel - ",
3637 static_cast<const KeyEntry&>(*cancelationEventEntry));
3638 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003640 case EventEntry::Type::MOTION: {
3641 logOutboundMotionDetails("cancel - ",
3642 static_cast<const MotionEntry&>(*cancelationEventEntry));
3643 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003645 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003646 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003647 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3648 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003649 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003650 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003651 break;
3652 }
3653 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003654 case EventEntry::Type::DEVICE_RESET:
3655 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003656 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003657 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003658 break;
3659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3663 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003665
3666 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667}
3668
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3670 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003671 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003672 return;
3673 }
3674
3675 nsecs_t currentTime = now();
3676
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003677 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003678 connection->inputState.synthesizePointerDownEvents(currentTime);
3679
3680 if (downEvents.empty()) {
3681 return;
3682 }
3683
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003684 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003685 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3686 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003687 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003688
3689 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003690 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003691 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3692 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003693 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003694 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003695 target.globalScaleFactor = windowInfo->globalScaleFactor;
3696 }
3697 target.inputChannel = connection->inputChannel;
3698 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3699
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003700 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003701 switch (downEventEntry->type) {
3702 case EventEntry::Type::MOTION: {
3703 logOutboundMotionDetails("down - ",
3704 static_cast<const MotionEntry&>(*downEventEntry));
3705 break;
3706 }
3707
3708 case EventEntry::Type::KEY:
3709 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003710 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003711 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003712 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003713 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003714 case EventEntry::Type::SENSOR:
3715 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003717 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003718 break;
3719 }
3720 }
3721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003722 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3723 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003724 }
3725
3726 startDispatchCycleLocked(currentTime, connection);
3727}
3728
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003729std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3730 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 ALOG_ASSERT(pointerIds.value != 0);
3732
3733 uint32_t splitPointerIndexMap[MAX_POINTERS];
3734 PointerProperties splitPointerProperties[MAX_POINTERS];
3735 PointerCoords splitPointerCoords[MAX_POINTERS];
3736
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003737 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 uint32_t splitPointerCount = 0;
3739
3740 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003743 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 uint32_t pointerId = uint32_t(pointerProperties.id);
3745 if (pointerIds.hasBit(pointerId)) {
3746 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3747 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3748 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003749 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 splitPointerCount += 1;
3751 }
3752 }
3753
3754 if (splitPointerCount != pointerIds.count()) {
3755 // This is bad. We are missing some of the pointers that we expected to deliver.
3756 // Most likely this indicates that we received an ACTION_MOVE events that has
3757 // different pointer ids than we expected based on the previous ACTION_DOWN
3758 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3759 // in this way.
3760 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003761 "we expected there to be %d pointers. This probably means we received "
3762 "a broken sequence of pointer ids from the input device.",
3763 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003764 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
3766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003767 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003769 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3770 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3772 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003773 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 uint32_t pointerId = uint32_t(pointerProperties.id);
3775 if (pointerIds.hasBit(pointerId)) {
3776 if (pointerIds.count() == 1) {
3777 // The first/last pointer went down/up.
3778 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003780 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3781 ? AMOTION_EVENT_ACTION_CANCEL
3782 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 } else {
3784 // A secondary pointer went down/up.
3785 uint32_t splitPointerIndex = 0;
3786 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3787 splitPointerIndex += 1;
3788 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003789 action = maskedAction |
3790 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 }
3792 } else {
3793 // An unrelated pointer changed.
3794 action = AMOTION_EVENT_ACTION_MOVE;
3795 }
3796 }
3797
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003798 int32_t newId = mIdGenerator.nextId();
3799 if (ATRACE_ENABLED()) {
3800 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3801 ") to MotionEvent(id=0x%" PRIx32 ").",
3802 originalMotionEntry.id, newId);
3803 ATRACE_NAME(message.c_str());
3804 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003805 std::unique_ptr<MotionEntry> splitMotionEntry =
3806 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3807 originalMotionEntry.deviceId, originalMotionEntry.source,
3808 originalMotionEntry.displayId,
3809 originalMotionEntry.policyFlags, action,
3810 originalMotionEntry.actionButton,
3811 originalMotionEntry.flags, originalMotionEntry.metaState,
3812 originalMotionEntry.buttonState,
3813 originalMotionEntry.classification,
3814 originalMotionEntry.edgeFlags,
3815 originalMotionEntry.xPrecision,
3816 originalMotionEntry.yPrecision,
3817 originalMotionEntry.xCursorPosition,
3818 originalMotionEntry.yCursorPosition,
3819 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003820 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003822 if (originalMotionEntry.injectionState) {
3823 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 splitMotionEntry->injectionState->refCount += 1;
3825 }
3826
3827 return splitMotionEntry;
3828}
3829
3830void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003831 if (DEBUG_INBOUND_EVENT_DETAILS) {
3832 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834
Antonio Kantekf16f2832021-09-28 04:39:20 +00003835 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003837 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003839 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3840 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3841 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 } // release lock
3843
3844 if (needWake) {
3845 mLooper->wake();
3846 }
3847}
3848
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003849/**
3850 * If one of the meta shortcuts is detected, process them here:
3851 * Meta + Backspace -> generate BACK
3852 * Meta + Enter -> generate HOME
3853 * This will potentially overwrite keyCode and metaState.
3854 */
3855void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003856 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003857 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3858 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3859 if (keyCode == AKEYCODE_DEL) {
3860 newKeyCode = AKEYCODE_BACK;
3861 } else if (keyCode == AKEYCODE_ENTER) {
3862 newKeyCode = AKEYCODE_HOME;
3863 }
3864 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003865 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003866 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003867 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003868 keyCode = newKeyCode;
3869 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3870 }
3871 } else if (action == AKEY_EVENT_ACTION_UP) {
3872 // In order to maintain a consistent stream of up and down events, check to see if the key
3873 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3874 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003875 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003876 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003877 auto replacementIt = mReplacedKeys.find(replacement);
3878 if (replacementIt != mReplacedKeys.end()) {
3879 keyCode = replacementIt->second;
3880 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003881 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3882 }
3883 }
3884}
3885
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003887 if (DEBUG_INBOUND_EVENT_DETAILS) {
3888 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3889 "policyFlags=0x%x, action=0x%x, "
3890 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3891 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3892 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3893 args->downTime);
3894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 if (!validateKeyEvent(args->action)) {
3896 return;
3897 }
3898
3899 uint32_t policyFlags = args->policyFlags;
3900 int32_t flags = args->flags;
3901 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003902 // InputDispatcher tracks and generates key repeats on behalf of
3903 // whatever notifies it, so repeatCount should always be set to 0
3904 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3906 policyFlags |= POLICY_FLAG_VIRTUAL;
3907 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 if (policyFlags & POLICY_FLAG_FUNCTION) {
3910 metaState |= AMETA_FUNCTION_ON;
3911 }
3912
3913 policyFlags |= POLICY_FLAG_TRUSTED;
3914
Michael Wright78f24442014-08-06 15:55:28 -07003915 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003916 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003917
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003919 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003920 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3921 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922
Michael Wright2b3c3302018-03-02 17:19:13 +00003923 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003925 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3926 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003927 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929
Antonio Kantekf16f2832021-09-28 04:39:20 +00003930 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 { // acquire lock
3932 mLock.lock();
3933
3934 if (shouldSendKeyToInputFilterLocked(args)) {
3935 mLock.unlock();
3936
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003937 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3939 return; // event was consumed by the filter
3940 }
3941
3942 mLock.lock();
3943 }
3944
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003945 std::unique_ptr<KeyEntry> newEntry =
3946 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3947 args->displayId, policyFlags, args->action, flags,
3948 keyCode, args->scanCode, metaState, repeatCount,
3949 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003951 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 mLock.unlock();
3953 } // release lock
3954
3955 if (needWake) {
3956 mLooper->wake();
3957 }
3958}
3959
3960bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3961 return mInputFilterEnabled;
3962}
3963
3964void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003965 if (DEBUG_INBOUND_EVENT_DETAILS) {
3966 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3967 "displayId=%" PRId32 ", policyFlags=0x%x, "
3968 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3969 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3970 "yCursorPosition=%f, downTime=%" PRId64,
3971 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3972 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3973 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3974 args->xCursorPosition, args->yCursorPosition, args->downTime);
3975 for (uint32_t i = 0; i < args->pointerCount; i++) {
3976 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3977 "x=%f, y=%f, pressure=%f, size=%f, "
3978 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3979 "orientation=%f",
3980 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3981 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3982 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3983 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3984 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3985 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3986 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3987 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3988 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3989 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003992 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3993 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 return;
3995 }
3996
3997 uint32_t policyFlags = args->policyFlags;
3998 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003999
4000 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004001 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004002 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4003 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006
Antonio Kantekf16f2832021-09-28 04:39:20 +00004007 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 { // acquire lock
4009 mLock.lock();
4010
4011 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004012 ui::Transform displayTransform;
4013 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4014 displayTransform = it->second.transform;
4015 }
4016
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 mLock.unlock();
4018
4019 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004020 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4021 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004022 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004023 displayTransform, args->xPrecision, args->yPrecision,
4024 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004025 args->downTime, args->eventTime, args->pointerCount,
4026 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027
4028 policyFlags |= POLICY_FLAG_FILTERED;
4029 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4030 return; // event was consumed by the filter
4031 }
4032
4033 mLock.lock();
4034 }
4035
4036 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004037 std::unique_ptr<MotionEntry> newEntry =
4038 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4039 args->source, args->displayId, policyFlags,
4040 args->action, args->actionButton, args->flags,
4041 args->metaState, args->buttonState,
4042 args->classification, args->edgeFlags,
4043 args->xPrecision, args->yPrecision,
4044 args->xCursorPosition, args->yCursorPosition,
4045 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004046 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004048 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4049 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4050 !mInputFilterEnabled) {
4051 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4052 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4053 }
4054
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004055 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 mLock.unlock();
4057 } // release lock
4058
4059 if (needWake) {
4060 mLooper->wake();
4061 }
4062}
4063
Chris Yef59a2f42020-10-16 12:55:26 -07004064void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004065 if (DEBUG_INBOUND_EVENT_DETAILS) {
4066 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4067 " sensorType=%s",
4068 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004069 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004070 }
Chris Yef59a2f42020-10-16 12:55:26 -07004071
Antonio Kantekf16f2832021-09-28 04:39:20 +00004072 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004073 { // acquire lock
4074 mLock.lock();
4075
4076 // Just enqueue a new sensor event.
4077 std::unique_ptr<SensorEntry> newEntry =
4078 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4079 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4080 args->sensorType, args->accuracy,
4081 args->accuracyChanged, args->values);
4082
4083 needWake = enqueueInboundEventLocked(std::move(newEntry));
4084 mLock.unlock();
4085 } // release lock
4086
4087 if (needWake) {
4088 mLooper->wake();
4089 }
4090}
4091
Chris Yefb552902021-02-03 17:18:37 -08004092void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004093 if (DEBUG_INBOUND_EVENT_DETAILS) {
4094 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4095 args->deviceId, args->isOn);
4096 }
Chris Yefb552902021-02-03 17:18:37 -08004097 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4098}
4099
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004101 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102}
4103
4104void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004105 if (DEBUG_INBOUND_EVENT_DETAILS) {
4106 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4107 "switchMask=0x%08x",
4108 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
4111 uint32_t policyFlags = args->policyFlags;
4112 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114}
4115
4116void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 if (DEBUG_INBOUND_EVENT_DETAILS) {
4118 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4119 args->deviceId);
4120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121
Antonio Kantekf16f2832021-09-28 04:39:20 +00004122 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004124 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004126 std::unique_ptr<DeviceResetEntry> newEntry =
4127 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4128 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 } // release lock
4130
4131 if (needWake) {
4132 mLooper->wake();
4133 }
4134}
4135
Prabir Pradhan7e186182020-11-10 13:56:45 -08004136void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004137 if (DEBUG_INBOUND_EVENT_DETAILS) {
4138 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004139 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004140 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004141
Antonio Kantekf16f2832021-09-28 04:39:20 +00004142 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004143 { // acquire lock
4144 std::scoped_lock _l(mLock);
4145 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004146 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004147 needWake = enqueueInboundEventLocked(std::move(entry));
4148 } // release lock
4149
4150 if (needWake) {
4151 mLooper->wake();
4152 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004153}
4154
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004155InputEventInjectionResult InputDispatcher::injectInputEvent(
4156 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4157 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004158 if (DEBUG_INBOUND_EVENT_DETAILS) {
4159 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4160 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4161 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4162 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004163 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
4165 policyFlags |= POLICY_FLAG_INJECTED;
4166 if (hasInjectionPermission(injectorPid, injectorUid)) {
4167 policyFlags |= POLICY_FLAG_TRUSTED;
4168 }
4169
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004170 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004171 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4172 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4173 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4174 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4175 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004176 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004177 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004178 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004179 }
4180
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004184 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4185 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004190 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004191 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4192 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4193 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004194 int32_t keyCode = incomingKey.getKeyCode();
4195 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004196 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004198 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004200 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4201 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4202 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4205 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004206 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207
4208 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4209 android::base::Timer t;
4210 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4211 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4212 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4213 std::to_string(t.duration().count()).c_str());
4214 }
4215 }
4216
4217 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004218 std::unique_ptr<KeyEntry> injectedEntry =
4219 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004221 incomingKey.getDisplayId(), policyFlags, action,
4222 flags, keyCode, incomingKey.getScanCode(), metaState,
4223 incomingKey.getRepeatCount(),
4224 incomingKey.getDownTime());
4225 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004231 const int32_t action = motionEvent.getAction();
4232 const bool isPointerEvent =
4233 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4234 // If a pointer event has no displayId specified, inject it to the default display.
4235 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4236 ? ADISPLAY_ID_DEFAULT
4237 : event->getDisplayId();
4238 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004240 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004243 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 }
4245
4246 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 android::base::Timer t;
4249 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4250 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4251 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4252 std::to_string(t.duration().count()).c_str());
4253 }
4254 }
4255
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004256 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4257 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4258 }
4259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004261 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4262 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004264 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4265 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004266 displayId, policyFlags, action, actionButton,
4267 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004268 motionEvent.getButtonState(),
4269 motionEvent.getClassification(),
4270 motionEvent.getEdgeFlags(),
4271 motionEvent.getXPrecision(),
4272 motionEvent.getYPrecision(),
4273 motionEvent.getRawXCursorPosition(),
4274 motionEvent.getRawYCursorPosition(),
4275 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004276 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004277 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 sampleEventTimes += 1;
4281 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4284 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004285 displayId, policyFlags, action, actionButton,
4286 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 motionEvent.getButtonState(),
4288 motionEvent.getClassification(),
4289 motionEvent.getEdgeFlags(),
4290 motionEvent.getXPrecision(),
4291 motionEvent.getYPrecision(),
4292 motionEvent.getRawXCursorPosition(),
4293 motionEvent.getRawYCursorPosition(),
4294 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004296 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004297 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4298 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 }
4301 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004305 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308
4309 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 injectionState->injectionIsAsync = true;
4312 }
4313
4314 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004315 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
4317 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004318 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004320 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 }
4322
4323 mLock.unlock();
4324
4325 if (needWake) {
4326 mLooper->wake();
4327 }
4328
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004331 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 if (syncMode == InputEventInjectionSync::NONE) {
4334 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 } else {
4336 for (;;) {
4337 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004338 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 break;
4340 }
4341
4342 nsecs_t remainingTimeout = endTime - now();
4343 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004344 if (DEBUG_INJECTION) {
4345 ALOGD("injectInputEvent - Timed out waiting for injection result "
4346 "to become available.");
4347 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004348 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 break;
4350 }
4351
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004352 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
4354
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4356 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 if (DEBUG_INJECTION) {
4359 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4360 injectionState->pendingForegroundDispatches);
4361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 nsecs_t remainingTimeout = endTime - now();
4363 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004364 if (DEBUG_INJECTION) {
4365 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4366 "dispatches to finish.");
4367 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 break;
4370 }
4371
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004372 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374 }
4375 }
4376
4377 injectionState->release();
4378 } // release lock
4379
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004380 if (DEBUG_INJECTION) {
4381 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4382 injectionResult, injectorPid, injectorUid);
4383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384
4385 return injectionResult;
4386}
4387
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004388std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004389 std::array<uint8_t, 32> calculatedHmac;
4390 std::unique_ptr<VerifiedInputEvent> result;
4391 switch (event.getType()) {
4392 case AINPUT_EVENT_TYPE_KEY: {
4393 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4394 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4395 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004396 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004397 break;
4398 }
4399 case AINPUT_EVENT_TYPE_MOTION: {
4400 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4401 VerifiedMotionEvent verifiedMotionEvent =
4402 verifiedMotionEventFromMotionEvent(motionEvent);
4403 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004404 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004405 break;
4406 }
4407 default: {
4408 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4409 return nullptr;
4410 }
4411 }
4412 if (calculatedHmac == INVALID_HMAC) {
4413 return nullptr;
4414 }
4415 if (calculatedHmac != event.getHmac()) {
4416 return nullptr;
4417 }
4418 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004419}
4420
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 return injectorUid == 0 ||
4423 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424}
4425
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004428 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 if (DEBUG_INJECTION) {
4431 ALOGD("Setting input event injection result to %d. "
4432 "injectorPid=%d, injectorUid=%d",
4433 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 // Log the outcome since the injector did not wait for the injection result.
4438 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004439 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 ALOGV("Asynchronous input event injection succeeded.");
4441 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 ALOGW("Asynchronous input event injection failed.");
4444 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004445 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004446 ALOGW("Asynchronous input event injection permission denied.");
4447 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 ALOGW("Asynchronous input event injection timed out.");
4450 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 case InputEventInjectionResult::PENDING:
4452 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4453 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 }
4455 }
4456
4457 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004458 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460}
4461
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004462void InputDispatcher::transformMotionEntryForInjectionLocked(
4463 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004464 // Input injection works in the logical display coordinate space, but the input pipeline works
4465 // display space, so we need to transform the injected events accordingly.
4466 const auto it = mDisplayInfos.find(entry.displayId);
4467 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004468 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004469
4470 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004471 entry.pointerCoords[i] =
4472 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4473 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004474 }
4475}
4476
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004477void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4478 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 if (injectionState) {
4480 injectionState->pendingForegroundDispatches += 1;
4481 }
4482}
4483
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004484void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4485 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 if (injectionState) {
4487 injectionState->pendingForegroundDispatches -= 1;
4488
4489 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004490 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 }
4492 }
4493}
4494
chaviw98318de2021-05-19 16:45:23 -05004495const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004496 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004497 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004498 auto it = mWindowHandlesByDisplay.find(displayId);
4499 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004500}
4501
chaviw98318de2021-05-19 16:45:23 -05004502sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004503 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004504 if (windowHandleToken == nullptr) {
4505 return nullptr;
4506 }
4507
Arthur Hungb92218b2018-08-14 12:00:21 +08004508 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004509 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4510 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004511 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004512 return windowHandle;
4513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 }
4515 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004516 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517}
4518
chaviw98318de2021-05-19 16:45:23 -05004519sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4520 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004521 if (windowHandleToken == nullptr) {
4522 return nullptr;
4523 }
4524
chaviw98318de2021-05-19 16:45:23 -05004525 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004526 if (windowHandle->getToken() == windowHandleToken) {
4527 return windowHandle;
4528 }
4529 }
4530 return nullptr;
4531}
4532
chaviw98318de2021-05-19 16:45:23 -05004533sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4534 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004535 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004536 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4537 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004538 if (handle->getId() == windowHandle->getId() &&
4539 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004540 if (windowHandle->getInfo()->displayId != it.first) {
4541 ALOGE("Found window %s in display %" PRId32
4542 ", but it should belong to display %" PRId32,
4543 windowHandle->getName().c_str(), it.first,
4544 windowHandle->getInfo()->displayId);
4545 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004546 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 }
4549 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004550 return nullptr;
4551}
4552
chaviw98318de2021-05-19 16:45:23 -05004553sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004554 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4555 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556}
4557
chaviw98318de2021-05-19 16:45:23 -05004558bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004559 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4560 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004561 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004562 if (connection != nullptr && noInputChannel) {
4563 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4564 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4565 return false;
4566 }
4567
4568 if (connection == nullptr) {
4569 if (!noInputChannel) {
4570 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4571 }
4572 return false;
4573 }
4574 if (!connection->responsive) {
4575 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4576 return false;
4577 }
4578 return true;
4579}
4580
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004581std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4582 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004583 auto connectionIt = mConnectionsByToken.find(token);
4584 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004585 return nullptr;
4586 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004587 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004588}
4589
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004590void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004591 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4592 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004593 // Remove all handles on a display if there are no windows left.
4594 mWindowHandlesByDisplay.erase(displayId);
4595 return;
4596 }
4597
4598 // Since we compare the pointer of input window handles across window updates, we need
4599 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004600 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4601 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4602 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004603 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004604 }
4605
chaviw98318de2021-05-19 16:45:23 -05004606 std::vector<sp<WindowInfoHandle>> newHandles;
4607 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004608 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004609 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004610 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004611 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004612 const bool canReceiveInput =
4613 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4614 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004615 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004616 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004617 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004618 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004619 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004620 }
4621
4622 if (info->displayId != displayId) {
4623 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4624 handle->getName().c_str(), displayId, info->displayId);
4625 continue;
4626 }
4627
Robert Carredd13602020-04-13 17:24:34 -07004628 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4629 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004630 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004631 oldHandle->updateFrom(handle);
4632 newHandles.push_back(oldHandle);
4633 } else {
4634 newHandles.push_back(handle);
4635 }
4636 }
4637
4638 // Insert or replace
4639 mWindowHandlesByDisplay[displayId] = newHandles;
4640}
4641
Arthur Hung72d8dc32020-03-28 00:48:39 +00004642void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004643 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004644 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004645 { // acquire lock
4646 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004647 for (const auto& [displayId, handles] : handlesPerDisplay) {
4648 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004649 }
4650 }
4651 // Wake up poll loop since it may need to make new input dispatching choices.
4652 mLooper->wake();
4653}
4654
Arthur Hungb92218b2018-08-14 12:00:21 +08004655/**
4656 * Called from InputManagerService, update window handle list by displayId that can receive input.
4657 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4658 * If set an empty list, remove all handles from the specific display.
4659 * For focused handle, check if need to change and send a cancel event to previous one.
4660 * For removed handle, check if need to send a cancel event if already in touch.
4661 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004662void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004663 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004664 if (DEBUG_FOCUS) {
4665 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004666 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004667 windowList += iwh->getName() + " ";
4668 }
4669 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Prabir Pradhand65552b2021-10-07 11:23:50 -07004672 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004673 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004674 const WindowInfo& info = *window->getInfo();
4675
4676 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004677 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004678 if (noInputWindow && window->getToken() != nullptr) {
4679 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4680 window->getName().c_str());
4681 window->releaseChannel();
4682 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004683
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004684 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004685 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4686 !info.inputConfig.test(
4687 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004688 "%s has feature SPY, but is not a trusted overlay.",
4689 window->getName().c_str());
4690
Prabir Pradhand65552b2021-10-07 11:23:50 -07004691 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004692 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4693 !info.inputConfig.test(
4694 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004695 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4696 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004697 }
4698
Arthur Hung72d8dc32020-03-28 00:48:39 +00004699 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004700 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004702 // Save the old windows' orientation by ID before it gets updated.
4703 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004704 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004705 oldWindowOrientations.emplace(handle->getId(),
4706 handle->getInfo()->transform.getOrientation());
4707 }
4708
chaviw98318de2021-05-19 16:45:23 -05004709 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004710
chaviw98318de2021-05-19 16:45:23 -05004711 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004712 if (mLastHoverWindowHandle &&
4713 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4714 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004715 mLastHoverWindowHandle = nullptr;
4716 }
4717
Vishnu Nairc519ff72021-01-21 08:23:08 -08004718 std::optional<FocusResolver::FocusChanges> changes =
4719 mFocusResolver.setInputWindows(displayId, windowHandles);
4720 if (changes) {
4721 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004724 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4725 mTouchStatesByDisplay.find(displayId);
4726 if (stateIt != mTouchStatesByDisplay.end()) {
4727 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728 for (size_t i = 0; i < state.windows.size();) {
4729 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004730 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004731 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004732 ALOGD("Touched window was removed: %s in display %" PRId32,
4733 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004734 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004735 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4737 if (touchedInputChannel != nullptr) {
4738 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4739 "touched window was removed");
4740 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004741 // Since we are about to drop the touch, cancel the events for the wallpaper as
4742 // well.
4743 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004744 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4745 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004746 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4747 if (wallpaper != nullptr) {
4748 sp<Connection> wallpaperConnection =
4749 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004750 if (wallpaperConnection != nullptr) {
4751 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4752 options);
4753 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004754 }
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004757 state.windows.erase(state.windows.begin() + i);
4758 } else {
4759 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 }
4761 }
arthurhungb89ccb02020-12-30 16:19:01 +08004762
arthurhung6d4bed92021-03-17 11:59:33 +08004763 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004764 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004765 if (mDragState &&
4766 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004767 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004768 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004769 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004770 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004771
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004772 // Determine if the orientation of any of the input windows have changed, and cancel all
4773 // pointer events if necessary.
4774 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4775 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4776 if (newWindowHandle != nullptr &&
4777 newWindowHandle->getInfo()->transform.getOrientation() !=
4778 oldWindowOrientations[oldWindowHandle->getId()]) {
4779 std::shared_ptr<InputChannel> inputChannel =
4780 getInputChannelLocked(newWindowHandle->getToken());
4781 if (inputChannel != nullptr) {
4782 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4783 "touched window's orientation changed");
4784 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004785 }
4786 }
4787 }
4788
Arthur Hung72d8dc32020-03-28 00:48:39 +00004789 // Release information for windows that are no longer present.
4790 // This ensures that unused input channels are released promptly.
4791 // Otherwise, they might stick around until the window handle is destroyed
4792 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004793 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004794 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004795 if (DEBUG_FOCUS) {
4796 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004797 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004798 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004799 }
chaviw291d88a2019-02-14 10:33:58 -08004800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801}
4802
4803void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004804 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 if (DEBUG_FOCUS) {
4806 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4807 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4808 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004809 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004810 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004811 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 } // release lock
4813
4814 // Wake up poll loop since it may need to make new input dispatching choices.
4815 mLooper->wake();
4816}
4817
Vishnu Nair599f1412021-06-21 10:39:58 -07004818void InputDispatcher::setFocusedApplicationLocked(
4819 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4820 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4821 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4822
4823 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4824 return; // This application is already focused. No need to wake up or change anything.
4825 }
4826
4827 // Set the new application handle.
4828 if (inputApplicationHandle != nullptr) {
4829 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4830 } else {
4831 mFocusedApplicationHandlesByDisplay.erase(displayId);
4832 }
4833
4834 // No matter what the old focused application was, stop waiting on it because it is
4835 // no longer focused.
4836 resetNoFocusedWindowTimeoutLocked();
4837}
4838
Tiger Huang721e26f2018-07-24 22:26:19 +08004839/**
4840 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4841 * the display not specified.
4842 *
4843 * We track any unreleased events for each window. If a window loses the ability to receive the
4844 * released event, we will send a cancel event to it. So when the focused display is changed, we
4845 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4846 * display. The display-specified events won't be affected.
4847 */
4848void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004849 if (DEBUG_FOCUS) {
4850 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4851 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004852 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004853 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004854
4855 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004856 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004857 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004858 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004859 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004860 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004861 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862 CancelationOptions
4863 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4864 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004865 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004866 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4867 }
4868 }
4869 mFocusedDisplayId = displayId;
4870
Chris Ye3c2d6f52020-08-09 10:39:48 -07004871 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004872 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004873 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004874
Vishnu Nairad321cd2020-08-20 16:40:21 -07004875 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004876 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004877 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004878 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004879 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004880 }
4881 }
4882 }
4883
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004884 if (DEBUG_FOCUS) {
4885 logDispatchStateLocked();
4886 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004887 } // release lock
4888
4889 // Wake up poll loop since it may need to make new input dispatching choices.
4890 mLooper->wake();
4891}
4892
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004894 if (DEBUG_FOCUS) {
4895 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897
4898 bool changed;
4899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
4902 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4903 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 }
4906
4907 if (mDispatchEnabled && !enabled) {
4908 resetAndDropEverythingLocked("dispatcher is being disabled");
4909 }
4910
4911 mDispatchEnabled = enabled;
4912 mDispatchFrozen = frozen;
4913 changed = true;
4914 } else {
4915 changed = false;
4916 }
4917
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004918 if (DEBUG_FOCUS) {
4919 logDispatchStateLocked();
4920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 } // release lock
4922
4923 if (changed) {
4924 // Wake up poll loop since it may need to make new input dispatching choices.
4925 mLooper->wake();
4926 }
4927}
4928
4929void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004930 if (DEBUG_FOCUS) {
4931 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
4934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936
4937 if (mInputFilterEnabled == enabled) {
4938 return;
4939 }
4940
4941 mInputFilterEnabled = enabled;
4942 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4943 } // release lock
4944
4945 // Wake up poll loop since there might be work to do to drop everything.
4946 mLooper->wake();
4947}
4948
Antonio Kantekea47acb2021-12-23 12:41:25 -08004949bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4950 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004951 bool needWake = false;
4952 {
4953 std::scoped_lock lock(mLock);
4954 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004955 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004956 }
4957 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004958 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4959 "hasPermission=%s)",
4960 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4961 }
4962 if (!hasPermission) {
4963 const sp<IBinder> focusedToken =
4964 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4965
Antonio Kantek019eb662022-02-08 13:41:52 -08004966 // TODO(b/218541064): if no window is currently focused, then we need to check the last
Antonio Kantekea47acb2021-12-23 12:41:25 -08004967 // interacted window (within 1 second timeout). We should allow touch mode change
4968 // if the last interacted window owner's pid/uid match the calling ones.
4969 if (focusedToken == nullptr) {
4970 return false;
4971 }
4972 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4973 if (windowHandle == nullptr) {
4974 return false;
4975 }
4976 const WindowInfo* windowInfo = windowHandle->getInfo();
4977 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4978 return false;
4979 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004980 }
4981
4982 // TODO(b/198499018): Store touch mode per display.
4983 mInTouchMode = inTouchMode;
4984
Antonio Kantekf16f2832021-09-28 04:39:20 +00004985 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4986 needWake = enqueueInboundEventLocked(std::move(entry));
4987 } // release lock
4988
4989 if (needWake) {
4990 mLooper->wake();
4991 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004992 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004993}
4994
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004995void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4996 if (opacity < 0 || opacity > 1) {
4997 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4998 return;
4999 }
5000
5001 std::scoped_lock lock(mLock);
5002 mMaximumObscuringOpacityForTouch = opacity;
5003}
5004
5005void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5006 std::scoped_lock lock(mLock);
5007 mBlockUntrustedTouchesMode = mode;
5008}
5009
Arthur Hungabbb9d82021-09-01 14:52:30 +00005010std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5011 const sp<IBinder>& token) {
5012 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5013 for (TouchedWindow& w : state.windows) {
5014 if (w.windowHandle->getToken() == token) {
5015 return std::make_pair(&state, &w);
5016 }
5017 }
5018 }
5019 return std::make_pair(nullptr, nullptr);
5020}
5021
arthurhungb89ccb02020-12-30 16:19:01 +08005022bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5023 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005024 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005025 if (DEBUG_FOCUS) {
5026 ALOGD("Trivial transfer to same window.");
5027 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005028 return true;
5029 }
5030
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005032 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033
Arthur Hungabbb9d82021-09-01 14:52:30 +00005034 // Find the target touch state and touched window by fromToken.
5035 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5036 if (state == nullptr || touchedWindow == nullptr) {
5037 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 return false;
5039 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005040
5041 const int32_t displayId = state->displayId;
5042 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5043 if (toWindowHandle == nullptr) {
5044 ALOGW("Cannot transfer focus because to window not found.");
5045 return false;
5046 }
5047
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005048 if (DEBUG_FOCUS) {
5049 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005050 touchedWindow->windowHandle->getName().c_str(),
5051 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 }
5053
Arthur Hungabbb9d82021-09-01 14:52:30 +00005054 // Erase old window.
5055 int32_t oldTargetFlags = touchedWindow->targetFlags;
5056 BitSet32 pointerIds = touchedWindow->pointerIds;
5057 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058
Arthur Hungabbb9d82021-09-01 14:52:30 +00005059 // Add new window.
5060 int32_t newTargetFlags = oldTargetFlags &
5061 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5062 InputTarget::FLAG_DISPATCH_AS_IS);
5063 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064
Arthur Hungabbb9d82021-09-01 14:52:30 +00005065 // Store the dragging window.
5066 if (isDragDrop) {
5067 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 }
5069
Arthur Hungabbb9d82021-09-01 14:52:30 +00005070 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005071 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5072 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005073 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005074 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005075 CancelationOptions
5076 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5077 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005079 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005082 if (DEBUG_FOCUS) {
5083 logDispatchStateLocked();
5084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085 } // release lock
5086
5087 // Wake up poll loop since it may need to make new input dispatching choices.
5088 mLooper->wake();
5089 return true;
5090}
5091
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005092// Binder call
5093bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5094 sp<IBinder> fromToken;
5095 { // acquire lock
5096 std::scoped_lock _l(mLock);
5097
Arthur Hungabbb9d82021-09-01 14:52:30 +00005098 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5099 [](const auto& pair) { return pair.second.windows.size() == 1; });
5100 if (it == mTouchStatesByDisplay.end()) {
5101 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5102 return false;
5103 }
5104 const int32_t displayId = it->first;
5105 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005106 if (toWindowHandle == nullptr) {
5107 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5108 return false;
5109 }
5110
Arthur Hungabbb9d82021-09-01 14:52:30 +00005111 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005112 const TouchedWindow& touchedWindow = state.windows[0];
5113 fromToken = touchedWindow.windowHandle->getToken();
5114 } // release lock
5115
5116 return transferTouchFocus(fromToken, destChannelToken);
5117}
5118
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005120 if (DEBUG_FOCUS) {
5121 ALOGD("Resetting and dropping all events (%s).", reason);
5122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123
5124 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5125 synthesizeCancelationEventsForAllConnectionsLocked(options);
5126
5127 resetKeyRepeatLocked();
5128 releasePendingEventLocked();
5129 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005130 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005133 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005135 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136}
5137
5138void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005139 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 dumpDispatchStateLocked(dump);
5141
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005142 std::istringstream stream(dump);
5143 std::string line;
5144
5145 while (std::getline(stream, line, '\n')) {
5146 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 }
5148}
5149
Prabir Pradhan99987712020-11-10 18:43:05 -08005150std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5151 std::string dump;
5152
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005153 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5154 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005155
5156 std::string windowName = "None";
5157 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005158 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005159 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5160 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5161 : "token has capture without window";
5162 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005163 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005164
5165 return dump;
5166}
5167
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005168void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005169 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5170 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5171 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005172 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173
Tiger Huang721e26f2018-07-24 22:26:19 +08005174 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5175 dump += StringPrintf(INDENT "FocusedApplications:\n");
5176 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5177 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005178 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005179 const std::chrono::duration timeout =
5180 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005181 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005182 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005183 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005186 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005188
Vishnu Nairc519ff72021-01-21 08:23:08 -08005189 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005190 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005192 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005193 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005194 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5195 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005196 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005197 state.displayId, toString(state.down), toString(state.split),
5198 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005199 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005200 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005201 for (size_t i = 0; i < state.windows.size(); i++) {
5202 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005203 dump += StringPrintf(INDENT4
5204 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5205 i, touchedWindow.windowHandle->getName().c_str(),
5206 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005207 }
5208 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005209 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005211 }
5212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005213 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 }
5215
arthurhung6d4bed92021-03-17 11:59:33 +08005216 if (mDragState) {
5217 dump += StringPrintf(INDENT "DragState:\n");
5218 mDragState->dump(dump, INDENT2);
5219 }
5220
Arthur Hungb92218b2018-08-14 12:00:21 +08005221 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005222 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5223 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5224 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5225 const auto& displayInfo = it->second;
5226 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5227 displayInfo.logicalHeight);
5228 displayInfo.transform.dump(dump, "transform", INDENT4);
5229 } else {
5230 dump += INDENT2 "No DisplayInfo found!\n";
5231 }
5232
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005233 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005234 dump += INDENT2 "Windows:\n";
5235 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005236 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5237 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005239 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005240 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005241 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005242 "applicationInfo.name=%s, "
5243 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005244 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005245 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005246 windowInfo->displayId,
5247 windowInfo->inputConfig.string().c_str(),
5248 windowInfo->alpha, windowInfo->frameLeft,
5249 windowInfo->frameTop, windowInfo->frameRight,
5250 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005251 windowInfo->applicationInfo.name.c_str(),
5252 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005253 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005254 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005255 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005256 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005258 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005259 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005260 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005261 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005262 }
5263 } else {
5264 dump += INDENT2 "Windows: <none>\n";
5265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 }
5267 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005268 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 }
5270
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005271 if (!mGlobalMonitorsByDisplay.empty()) {
5272 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5273 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005274 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005277 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 }
5279
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005280 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281
5282 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005283 if (!mRecentQueue.empty()) {
5284 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005285 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005286 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005287 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005288 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 }
5290 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005291 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 }
5293
5294 // Dump event currently being dispatched.
5295 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005296 dump += INDENT "PendingEvent:\n";
5297 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005298 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005299 dump += StringPrintf(", age=%" PRId64 "ms\n",
5300 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005302 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 }
5304
5305 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005306 if (!mInboundQueue.empty()) {
5307 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005308 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005309 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005310 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005311 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 }
5313 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005314 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 }
5316
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005317 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005318 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005319 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5320 const KeyReplacement& replacement = pair.first;
5321 int32_t newKeyCode = pair.second;
5322 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005323 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005324 }
5325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005326 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005327 }
5328
Prabir Pradhancef936d2021-07-21 16:17:52 +00005329 if (!mCommandQueue.empty()) {
5330 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5331 } else {
5332 dump += INDENT "CommandQueue: <empty>\n";
5333 }
5334
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005335 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005336 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005337 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005338 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005339 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005340 connection->inputChannel->getFd().get(),
5341 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005342 connection->getWindowName().c_str(),
5343 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005344 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005346 if (!connection->outboundQueue.empty()) {
5347 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5348 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005349 dump += dumpQueue(connection->outboundQueue, currentTime);
5350
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005352 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353 }
5354
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005355 if (!connection->waitQueue.empty()) {
5356 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5357 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005358 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005360 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 }
5362 }
5363 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005364 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 }
5366
5367 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005368 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5369 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005371 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372 }
5373
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005374 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005375 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5376 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5377 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005378 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005379 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380}
5381
Michael Wright3dd60e22019-03-27 22:06:44 +00005382void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5383 const size_t numMonitors = monitors.size();
5384 for (size_t i = 0; i < numMonitors; i++) {
5385 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005386 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005387 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5388 dump += "\n";
5389 }
5390}
5391
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005392class LooperEventCallback : public LooperCallback {
5393public:
5394 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5395 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5396
5397private:
5398 std::function<int(int events)> mCallback;
5399};
5400
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005401Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005402 if (DEBUG_CHANNEL_CREATION) {
5403 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005406 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005407 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005408 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005409
5410 if (result) {
5411 return base::Error(result) << "Failed to open input channel pair with name " << name;
5412 }
5413
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005415 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005416 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005417 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005418 sp<Connection> connection =
5419 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005421 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5422 ALOGE("Created a new connection, but the token %p is already known", token.get());
5423 }
5424 mConnectionsByToken.emplace(token, connection);
5425
5426 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5427 this, std::placeholders::_1, token);
5428
5429 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 } // release lock
5431
5432 // Wake the looper because some connections have changed.
5433 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005434 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435}
5436
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005437Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005438 const std::string& name,
5439 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005440 std::shared_ptr<InputChannel> serverChannel;
5441 std::unique_ptr<InputChannel> clientChannel;
5442 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5443 if (result) {
5444 return base::Error(result) << "Failed to open input channel pair with name " << name;
5445 }
5446
Michael Wright3dd60e22019-03-27 22:06:44 +00005447 { // acquire lock
5448 std::scoped_lock _l(mLock);
5449
5450 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005451 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5452 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005453 }
5454
Garfield Tan15601662020-09-22 15:32:38 -07005455 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005456 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005457 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005458
5459 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5460 ALOGE("Created a new connection, but the token %p is already known", token.get());
5461 }
5462 mConnectionsByToken.emplace(token, connection);
5463 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5464 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005465
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005466 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005467
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005468 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005469 }
Garfield Tan15601662020-09-22 15:32:38 -07005470
Michael Wright3dd60e22019-03-27 22:06:44 +00005471 // Wake the looper because some connections have changed.
5472 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005473 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005474}
5475
Garfield Tan15601662020-09-22 15:32:38 -07005476status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005478 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479
Garfield Tan15601662020-09-22 15:32:38 -07005480 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 if (status) {
5482 return status;
5483 }
5484 } // release lock
5485
5486 // Wake the poll loop because removing the connection may have changed the current
5487 // synchronization state.
5488 mLooper->wake();
5489 return OK;
5490}
5491
Garfield Tan15601662020-09-22 15:32:38 -07005492status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5493 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005494 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005495 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005496 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 return BAD_VALUE;
5498 }
5499
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005500 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005501
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005503 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005504 }
5505
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005506 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507
5508 nsecs_t currentTime = now();
5509 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5510
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005511 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 return OK;
5513}
5514
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005515void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005516 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5517 auto& [displayId, monitors] = *it;
5518 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5519 return monitor.inputChannel->getConnectionToken() == connectionToken;
5520 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005521
Michael Wright3dd60e22019-03-27 22:06:44 +00005522 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005523 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005524 } else {
5525 ++it;
5526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 }
5528}
5529
Michael Wright3dd60e22019-03-27 22:06:44 +00005530status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005531 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005532
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005533 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5534 if (!requestingChannel) {
5535 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5536 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005537 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005538
5539 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5540 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5541 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5542 " Ignoring.");
5543 return BAD_VALUE;
5544 }
5545
5546 TouchState& state = *statePtr;
5547
5548 // Send cancel events to all the input channels we're stealing from.
5549 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5550 "input channel stole pointer stream");
5551 options.deviceId = state.deviceId;
5552 options.displayId = state.displayId;
5553 std::string canceledWindows;
5554 for (const TouchedWindow& window : state.windows) {
5555 const std::shared_ptr<InputChannel> channel =
5556 getInputChannelLocked(window.windowHandle->getToken());
5557 if (channel != nullptr && channel->getConnectionToken() != token) {
5558 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5559 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5560 canceledWindows += channel->getName();
5561 }
5562 }
5563 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5564 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5565 canceledWindows.c_str());
5566
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005567 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005568 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005569 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005570 return OK;
5571}
5572
Prabir Pradhan99987712020-11-10 18:43:05 -08005573void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5574 { // acquire lock
5575 std::scoped_lock _l(mLock);
5576 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005577 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005578 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5579 windowHandle != nullptr ? windowHandle->getName().c_str()
5580 : "token without window");
5581 }
5582
Vishnu Nairc519ff72021-01-21 08:23:08 -08005583 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005584 if (focusedToken != windowToken) {
5585 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5586 enabled ? "enable" : "disable");
5587 return;
5588 }
5589
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005590 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005591 ALOGW("Ignoring request to %s Pointer Capture: "
5592 "window has %s requested pointer capture.",
5593 enabled ? "enable" : "disable", enabled ? "already" : "not");
5594 return;
5595 }
5596
Christine Franksb768bb42021-11-29 12:11:31 -08005597 if (enabled) {
5598 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5599 mIneligibleDisplaysForPointerCapture.end(),
5600 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5601 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5602 return;
5603 }
5604 }
5605
Prabir Pradhan99987712020-11-10 18:43:05 -08005606 setPointerCaptureLocked(enabled);
5607 } // release lock
5608
5609 // Wake the thread to process command entries.
5610 mLooper->wake();
5611}
5612
Christine Franksb768bb42021-11-29 12:11:31 -08005613void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5614 { // acquire lock
5615 std::scoped_lock _l(mLock);
5616 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5617 if (!isEligible) {
5618 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5619 }
5620 } // release lock
5621}
5622
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005623std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5624 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005625 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005626 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005627 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005628 }
5629 }
5630 }
5631 return std::nullopt;
5632}
5633
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005634sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005635 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005636 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005637 }
5638
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005639 for (const auto& [token, connection] : mConnectionsByToken) {
5640 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005641 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 }
5643 }
Robert Carr4e670e52018-08-15 13:26:12 -07005644
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005645 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646}
5647
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005648std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5649 sp<Connection> connection = getConnectionLocked(connectionToken);
5650 if (connection == nullptr) {
5651 return "<nullptr>";
5652 }
5653 return connection->getInputChannelName();
5654}
5655
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005656void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005657 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005658 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005659}
5660
Prabir Pradhancef936d2021-07-21 16:17:52 +00005661void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5662 const sp<Connection>& connection, uint32_t seq,
5663 bool handled, nsecs_t consumeTime) {
5664 // Handle post-event policy actions.
5665 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5666 if (dispatchEntryIt == connection->waitQueue.end()) {
5667 return;
5668 }
5669 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5670 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5671 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5672 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5673 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5674 }
5675 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5676 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5677 connection->inputChannel->getConnectionToken(),
5678 dispatchEntry->deliveryTime, consumeTime, finishTime);
5679 }
5680
5681 bool restartEvent;
5682 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5683 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5684 restartEvent =
5685 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5686 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5687 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5688 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5689 handled);
5690 } else {
5691 restartEvent = false;
5692 }
5693
5694 // Dequeue the event and start the next cycle.
5695 // Because the lock might have been released, it is possible that the
5696 // contents of the wait queue to have been drained, so we need to double-check
5697 // a few things.
5698 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5699 if (dispatchEntryIt != connection->waitQueue.end()) {
5700 dispatchEntry = *dispatchEntryIt;
5701 connection->waitQueue.erase(dispatchEntryIt);
5702 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5703 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5704 if (!connection->responsive) {
5705 connection->responsive = isConnectionResponsive(*connection);
5706 if (connection->responsive) {
5707 // The connection was unresponsive, and now it's responsive.
5708 processConnectionResponsiveLocked(*connection);
5709 }
5710 }
5711 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005712 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005713 connection->outboundQueue.push_front(dispatchEntry);
5714 traceOutboundQueueLength(*connection);
5715 } else {
5716 releaseDispatchEntry(dispatchEntry);
5717 }
5718 }
5719
5720 // Start the next dispatch cycle for this connection.
5721 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722}
5723
Prabir Pradhancef936d2021-07-21 16:17:52 +00005724void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5725 const sp<IBinder>& newToken) {
5726 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5727 scoped_unlock unlock(mLock);
5728 mPolicy->notifyFocusChanged(oldToken, newToken);
5729 };
5730 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731}
5732
Prabir Pradhancef936d2021-07-21 16:17:52 +00005733void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5734 auto command = [this, token, x, y]() REQUIRES(mLock) {
5735 scoped_unlock unlock(mLock);
5736 mPolicy->notifyDropWindow(token, x, y);
5737 };
5738 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005739}
5740
Prabir Pradhancef936d2021-07-21 16:17:52 +00005741void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5742 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5743 scoped_unlock unlock(mLock);
5744 mPolicy->notifyUntrustedTouch(obscuringPackage);
5745 };
5746 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005747}
5748
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005749void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5750 if (connection == nullptr) {
5751 LOG_ALWAYS_FATAL("Caller must check for nullness");
5752 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5754 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005755 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005756 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005757 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005758 return;
5759 }
5760 /**
5761 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5762 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5763 * has changed. This could cause newer entries to time out before the already dispatched
5764 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5765 * processes the events linearly. So providing information about the oldest entry seems to be
5766 * most useful.
5767 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005768 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005769 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5770 std::string reason =
5771 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005772 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005773 ns2ms(currentWait),
5774 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005775 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005776 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005777
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005778 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5779
5780 // Stop waking up for events on this connection, it is already unresponsive
5781 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005782}
5783
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005784void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5785 std::string reason =
5786 StringPrintf("%s does not have a focused window", application->getName().c_str());
5787 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005788
Prabir Pradhancef936d2021-07-21 16:17:52 +00005789 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5790 scoped_unlock unlock(mLock);
5791 mPolicy->notifyNoFocusedWindowAnr(application);
5792 };
5793 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005794}
5795
chaviw98318de2021-05-19 16:45:23 -05005796void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005797 const std::string& reason) {
5798 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5799 updateLastAnrStateLocked(windowLabel, reason);
5800}
5801
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005802void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5803 const std::string& reason) {
5804 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005805 updateLastAnrStateLocked(windowLabel, reason);
5806}
5807
5808void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5809 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005811 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812 struct tm tm;
5813 localtime_r(&t, &tm);
5814 char timestr[64];
5815 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005816 mLastAnrState.clear();
5817 mLastAnrState += INDENT "ANR:\n";
5818 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005819 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5820 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005821 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822}
5823
Prabir Pradhancef936d2021-07-21 16:17:52 +00005824void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5825 KeyEntry& entry) {
5826 const KeyEvent event = createKeyEvent(entry);
5827 nsecs_t delay = 0;
5828 { // release lock
5829 scoped_unlock unlock(mLock);
5830 android::base::Timer t;
5831 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5832 entry.policyFlags);
5833 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5834 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5835 std::to_string(t.duration().count()).c_str());
5836 }
5837 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838
5839 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005840 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005841 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005842 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005844 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5845 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847}
5848
Prabir Pradhancef936d2021-07-21 16:17:52 +00005849void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005850 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005851 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005852 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005853 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005854 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005855 };
5856 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005857}
5858
Prabir Pradhanedd96402022-02-15 01:46:16 -08005859void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5860 std::optional<int32_t> pid) {
5861 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005862 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005863 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005864 };
5865 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005866}
5867
5868/**
5869 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5870 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5871 * command entry to the command queue.
5872 */
5873void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5874 std::string reason) {
5875 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005876 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005877 if (connection.monitor) {
5878 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5879 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005880 pid = findMonitorPidByTokenLocked(connectionToken);
5881 } else {
5882 // The connection is a window
5883 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5884 reason.c_str());
5885 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5886 if (handle != nullptr) {
5887 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005888 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005889 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005890 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005891}
5892
5893/**
5894 * Tell the policy that a connection has become responsive so that it can stop ANR.
5895 */
5896void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5897 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005898 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005900 pid = findMonitorPidByTokenLocked(connectionToken);
5901 } else {
5902 // The connection is a window
5903 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5904 if (handle != nullptr) {
5905 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005907 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005908 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005909}
5910
Prabir Pradhancef936d2021-07-21 16:17:52 +00005911bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005912 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005913 KeyEntry& keyEntry, bool handled) {
5914 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005915 if (!handled) {
5916 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005917 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005918 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005919 return false;
5920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005922 // Get the fallback key state.
5923 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005924 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005925 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005926 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927 connection->inputState.removeFallbackKey(originalKeyCode);
5928 }
5929
5930 if (handled || !dispatchEntry->hasForegroundTarget()) {
5931 // If the application handles the original key for which we previously
5932 // generated a fallback or if the window is not a foreground window,
5933 // then cancel the associated fallback key, if any.
5934 if (fallbackKeyCode != -1) {
5935 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005936 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5937 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5938 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5939 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5940 keyEntry.policyFlags);
5941 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005942 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005943 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944
5945 mLock.unlock();
5946
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005947 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005948 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949
5950 mLock.lock();
5951
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005952 // Cancel the fallback key.
5953 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955 "application handled the original non-fallback key "
5956 "or is no longer a foreground target, "
5957 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 options.keyCode = fallbackKeyCode;
5959 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005961 connection->inputState.removeFallbackKey(originalKeyCode);
5962 }
5963 } else {
5964 // If the application did not handle a non-fallback key, first check
5965 // that we are in a good state to perform unhandled key event processing
5966 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005967 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005968 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005969 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5970 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5971 "since this is not an initial down. "
5972 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5973 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5974 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005975 return false;
5976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005978 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005979 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5980 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5981 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5982 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5983 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005984 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005985
5986 mLock.unlock();
5987
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005988 bool fallback =
5989 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005990 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005991
5992 mLock.lock();
5993
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005994 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005995 connection->inputState.removeFallbackKey(originalKeyCode);
5996 return false;
5997 }
5998
5999 // Latch the fallback keycode for this key on an initial down.
6000 // The fallback keycode cannot change at any other point in the lifecycle.
6001 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006002 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006003 fallbackKeyCode = event.getKeyCode();
6004 } else {
6005 fallbackKeyCode = AKEYCODE_UNKNOWN;
6006 }
6007 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6008 }
6009
6010 ALOG_ASSERT(fallbackKeyCode != -1);
6011
6012 // Cancel the fallback key if the policy decides not to send it anymore.
6013 // We will continue to dispatch the key to the policy but we will no
6014 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006015 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6016 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006017 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6018 if (fallback) {
6019 ALOGD("Unhandled key event: Policy requested to send key %d"
6020 "as a fallback for %d, but on the DOWN it had requested "
6021 "to send %d instead. Fallback canceled.",
6022 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6023 } else {
6024 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6025 "but on the DOWN it had requested to send %d. "
6026 "Fallback canceled.",
6027 originalKeyCode, fallbackKeyCode);
6028 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006029 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006030
6031 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6032 "canceling fallback, policy no longer desires it");
6033 options.keyCode = fallbackKeyCode;
6034 synthesizeCancelationEventsForConnectionLocked(connection, options);
6035
6036 fallback = false;
6037 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006039 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 }
6041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006043 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6044 {
6045 std::string msg;
6046 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6047 connection->inputState.getFallbackKeys();
6048 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6049 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6050 }
6051 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6052 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055
6056 if (fallback) {
6057 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006058 keyEntry.eventTime = event.getEventTime();
6059 keyEntry.deviceId = event.getDeviceId();
6060 keyEntry.source = event.getSource();
6061 keyEntry.displayId = event.getDisplayId();
6062 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6063 keyEntry.keyCode = fallbackKeyCode;
6064 keyEntry.scanCode = event.getScanCode();
6065 keyEntry.metaState = event.getMetaState();
6066 keyEntry.repeatCount = event.getRepeatCount();
6067 keyEntry.downTime = event.getDownTime();
6068 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006070 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6071 ALOGD("Unhandled key event: Dispatching fallback key. "
6072 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6073 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6074 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006075 return true; // restart the event
6076 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006077 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6078 ALOGD("Unhandled key event: No fallback key.");
6079 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006080
6081 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006082 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 }
6084 }
6085 return false;
6086}
6087
Prabir Pradhancef936d2021-07-21 16:17:52 +00006088bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006089 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006090 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 return false;
6092}
6093
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094void InputDispatcher::traceInboundQueueLengthLocked() {
6095 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006096 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 }
6098}
6099
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006100void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101 if (ATRACE_ENABLED()) {
6102 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006103 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6104 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 }
6106}
6107
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006108void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109 if (ATRACE_ENABLED()) {
6110 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006111 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6112 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006113 }
6114}
6115
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006116void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006117 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006119 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 dumpDispatchStateLocked(dump);
6121
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006122 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006123 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006124 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006125 }
6126}
6127
6128void InputDispatcher::monitor() {
6129 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006130 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006132 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133}
6134
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006135/**
6136 * Wake up the dispatcher and wait until it processes all events and commands.
6137 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6138 * this method can be safely called from any thread, as long as you've ensured that
6139 * the work you are interested in completing has already been queued.
6140 */
6141bool InputDispatcher::waitForIdle() {
6142 /**
6143 * Timeout should represent the longest possible time that a device might spend processing
6144 * events and commands.
6145 */
6146 constexpr std::chrono::duration TIMEOUT = 100ms;
6147 std::unique_lock lock(mLock);
6148 mLooper->wake();
6149 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6150 return result == std::cv_status::no_timeout;
6151}
6152
Vishnu Naire798b472020-07-23 13:52:21 -07006153/**
6154 * Sets focus to the window identified by the token. This must be called
6155 * after updating any input window handles.
6156 *
6157 * Params:
6158 * request.token - input channel token used to identify the window that should gain focus.
6159 * request.focusedToken - the token that the caller expects currently to be focused. If the
6160 * specified token does not match the currently focused window, this request will be dropped.
6161 * If the specified focused token matches the currently focused window, the call will succeed.
6162 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6163 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6164 * when requesting the focus change. This determines which request gets
6165 * precedence if there is a focus change request from another source such as pointer down.
6166 */
Vishnu Nair958da932020-08-21 17:12:37 -07006167void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6168 { // acquire lock
6169 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006170 std::optional<FocusResolver::FocusChanges> changes =
6171 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6172 if (changes) {
6173 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006174 }
6175 } // release lock
6176 // Wake up poll loop since it may need to make new input dispatching choices.
6177 mLooper->wake();
6178}
6179
Vishnu Nairc519ff72021-01-21 08:23:08 -08006180void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6181 if (changes.oldFocus) {
6182 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006183 if (focusedInputChannel) {
6184 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6185 "focus left window");
6186 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006187 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006188 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006189 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006190 if (changes.newFocus) {
6191 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006192 }
6193
Prabir Pradhan99987712020-11-10 18:43:05 -08006194 // If a window has pointer capture, then it must have focus. We need to ensure that this
6195 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6196 // If the window loses focus before it loses pointer capture, then the window can be in a state
6197 // where it has pointer capture but not focus, violating the contract. Therefore we must
6198 // dispatch the pointer capture event before the focus event. Since focus events are added to
6199 // the front of the queue (above), we add the pointer capture event to the front of the queue
6200 // after the focus events are added. This ensures the pointer capture event ends up at the
6201 // front.
6202 disablePointerCaptureForcedLocked();
6203
Vishnu Nairc519ff72021-01-21 08:23:08 -08006204 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006205 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006206 }
6207}
Vishnu Nair958da932020-08-21 17:12:37 -07006208
Prabir Pradhan99987712020-11-10 18:43:05 -08006209void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006210 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006211 return;
6212 }
6213
6214 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6215
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006216 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006217 setPointerCaptureLocked(false);
6218 }
6219
6220 if (!mWindowTokenWithPointerCapture) {
6221 // No need to send capture changes because no window has capture.
6222 return;
6223 }
6224
6225 if (mPendingEvent != nullptr) {
6226 // Move the pending event to the front of the queue. This will give the chance
6227 // for the pending event to be dropped if it is a captured event.
6228 mInboundQueue.push_front(mPendingEvent);
6229 mPendingEvent = nullptr;
6230 }
6231
6232 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006233 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006234 mInboundQueue.push_front(std::move(entry));
6235}
6236
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006237void InputDispatcher::setPointerCaptureLocked(bool enable) {
6238 mCurrentPointerCaptureRequest.enable = enable;
6239 mCurrentPointerCaptureRequest.seq++;
6240 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006241 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006242 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006243 };
6244 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006245}
6246
Vishnu Nair599f1412021-06-21 10:39:58 -07006247void InputDispatcher::displayRemoved(int32_t displayId) {
6248 { // acquire lock
6249 std::scoped_lock _l(mLock);
6250 // Set an empty list to remove all handles from the specific display.
6251 setInputWindowsLocked(/* window handles */ {}, displayId);
6252 setFocusedApplicationLocked(displayId, nullptr);
6253 // Call focus resolver to clean up stale requests. This must be called after input windows
6254 // have been removed for the removed display.
6255 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006256 // Reset pointer capture eligibility, regardless of previous state.
6257 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006258 } // release lock
6259
6260 // Wake up poll loop since it may need to make new input dispatching choices.
6261 mLooper->wake();
6262}
6263
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006264void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6265 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006266 // The listener sends the windows as a flattened array. Separate the windows by display for
6267 // more convenient parsing.
6268 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006269 for (const auto& info : windowInfos) {
6270 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6271 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6272 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006273
6274 { // acquire lock
6275 std::scoped_lock _l(mLock);
6276 mDisplayInfos.clear();
6277 for (const auto& displayInfo : displayInfos) {
6278 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6279 }
6280
6281 for (const auto& [displayId, handles] : handlesPerDisplay) {
6282 setInputWindowsLocked(handles, displayId);
6283 }
6284 }
6285 // Wake up poll loop since it may need to make new input dispatching choices.
6286 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006287}
6288
Vishnu Nair062a8672021-09-03 16:07:44 -07006289bool InputDispatcher::shouldDropInput(
6290 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006291 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6292 (windowHandle->getInfo()->inputConfig.test(
6293 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006294 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006295 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6296 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006297 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006298 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006299 windowHandle->getInfo()->displayId);
6300 return true;
6301 }
6302 return false;
6303}
6304
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006305void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6306 const std::vector<gui::WindowInfo>& windowInfos,
6307 const std::vector<DisplayInfo>& displayInfos) {
6308 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6309}
6310
Arthur Hungdfd528e2021-12-08 13:23:04 +00006311void InputDispatcher::cancelCurrentTouch() {
6312 {
6313 std::scoped_lock _l(mLock);
6314 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6315 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6316 "cancel current touch");
6317 synthesizeCancelationEventsForAllConnectionsLocked(options);
6318
6319 mTouchStatesByDisplay.clear();
6320 mLastHoverWindowHandle.clear();
6321 }
6322 // Wake up poll loop since there might be work to do.
6323 mLooper->wake();
6324}
6325
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006326void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6327 std::scoped_lock _l(mLock);
6328 mMonitorDispatchingTimeout = timeout;
6329}
6330
Garfield Tane84e6f92019-08-29 17:28:41 -07006331} // namespace android::inputdispatcher