blob: 176cf8943af5132e285c41e77ac28b65e0227bf7 [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
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -070022#include <InputFlingerProperties.sysprop.h>
Michael Wright2b3c3302018-03-02 17:19:13 +000023#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100028#include <binder/IServiceManager.h>
29#include <com/android/internal/compat/IPlatformCompatNative.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080030#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050031#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070033#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000034#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070048#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#define INDENT " "
51#define INDENT2 " "
52#define INDENT3 " "
53#define INDENT4 " "
54
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080055using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000056using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070058using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050059using android::gui::FocusRequest;
60using android::gui::TouchOcclusionMode;
61using android::gui::WindowInfo;
62using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080063using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100064using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080065using android::os::InputEventInjectionResult;
66using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100067using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068
Garfield Tane84e6f92019-08-29 17:28:41 -070069namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
Prabir Pradhancef936d2021-07-21 16:17:52 +000071namespace {
72
Prabir Pradhan61a5d242021-07-26 16:41:09 +000073// Log detailed debug messages about each inbound event notification to the dispatcher.
74constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
75
76// Log detailed debug messages about each outbound event processed by the dispatcher.
77constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
78
79// Log debug messages about the dispatch cycle.
80constexpr bool DEBUG_DISPATCH_CYCLE = false;
81
82// Log debug messages about channel creation
83constexpr bool DEBUG_CHANNEL_CREATION = false;
84
85// Log debug messages about input event injection.
86constexpr bool DEBUG_INJECTION = false;
87
88// Log debug messages about input focus tracking.
89constexpr bool DEBUG_FOCUS = false;
90
Antonio Kantekf16f2832021-09-28 04:39:20 +000091// Log debug messages about touch mode event
92constexpr bool DEBUG_TOUCH_MODE = false;
93
Prabir Pradhan61a5d242021-07-26 16:41:09 +000094// Log debug messages about touch occlusion
95// STOPSHIP(b/169067926): Set to false
96constexpr bool DEBUG_TOUCH_OCCLUSION = true;
97
98// Log debug messages about the app switch latency optimization.
99constexpr bool DEBUG_APP_SWITCH = false;
100
101// Log debug messages about hover events.
102constexpr bool DEBUG_HOVER = false;
103
Prabir Pradhancef936d2021-07-21 16:17:52 +0000104// Temporarily releases a held mutex for the lifetime of the instance.
105// Named to match std::scoped_lock
106class scoped_unlock {
107public:
108 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
109 ~scoped_unlock() { mMutex.lock(); }
110
111private:
112 std::mutex& mMutex;
113};
114
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700115// When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
116// coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117bool isPerWindowInputRotationEnabled() {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700118 static const bool PER_WINDOW_INPUT_ROTATION =
Prabir Pradhan9c2d28c2021-09-29 17:42:14 +0000119 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(true);
Prabir Pradhand2c9e8e2021-05-24 15:00:12 -0700120
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700121 return PER_WINDOW_INPUT_ROTATION;
122}
123
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124// Default input dispatching timeout if there is no focused application or paused window
125// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800126const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
127 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
128 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129
130// Amount of time to allow for all pending events to be processed when an app switch
131// key is on the way. This is used to preempt input dispatch and drop input events
132// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000133constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134
135// Amount of time to allow for an event to be dispatched (measured since its eventTime)
136// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000137constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139// 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 +0000140constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
141
142// Log a warning when an interception call takes longer than this to process.
143constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700145// Additional key latency in case a connection is still processing some motion events.
146// This will help with the case when a user touched a button that opens a new window,
147// and gives us the chance to dispatch the key to this new window.
148constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
149
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000151constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
152
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000153// Event log tags. See EventLogTags.logtags for reference
154constexpr int LOGTAG_INPUT_INTERACTION = 62000;
155constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000156constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000157
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000158inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 return systemTime(SYSTEM_TIME_MONOTONIC);
160}
161
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000162inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163 return value ? "true" : "false";
164}
165
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000166inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000167 if (binder == nullptr) {
168 return "<null>";
169 }
170 return StringPrintf("%p", binder.get());
171}
172
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000173inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
175 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176}
177
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000178bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 case AKEY_EVENT_ACTION_DOWN:
181 case AKEY_EVENT_ACTION_UP:
182 return true;
183 default:
184 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 }
186}
187
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000188bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 ALOGE("Key event has invalid action code 0x%x", action);
191 return false;
192 }
193 return true;
194}
195
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000196bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700198 case AMOTION_EVENT_ACTION_DOWN:
199 case AMOTION_EVENT_ACTION_UP:
200 case AMOTION_EVENT_ACTION_CANCEL:
201 case AMOTION_EVENT_ACTION_MOVE:
202 case AMOTION_EVENT_ACTION_OUTSIDE:
203 case AMOTION_EVENT_ACTION_HOVER_ENTER:
204 case AMOTION_EVENT_ACTION_HOVER_MOVE:
205 case AMOTION_EVENT_ACTION_HOVER_EXIT:
206 case AMOTION_EVENT_ACTION_SCROLL:
207 return true;
208 case AMOTION_EVENT_ACTION_POINTER_DOWN:
209 case AMOTION_EVENT_ACTION_POINTER_UP: {
210 int32_t index = getMotionEventActionPointerIndex(action);
211 return index >= 0 && index < pointerCount;
212 }
213 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
214 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
215 return actionButton != 0;
216 default:
217 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
219}
220
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000221int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500222 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
223}
224
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000225bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
226 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700227 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 ALOGE("Motion event has invalid action code 0x%x", action);
229 return false;
230 }
231 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000232 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700233 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 return false;
235 }
236 BitSet32 pointerIdBits;
237 for (size_t i = 0; i < pointerCount; i++) {
238 int32_t id = pointerProperties[i].id;
239 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700240 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
241 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 return false;
243 }
244 if (pointerIdBits.hasBit(id)) {
245 ALOGE("Motion event has duplicate pointer id %d", id);
246 return false;
247 }
248 pointerIdBits.markBit(id);
249 }
250 return true;
251}
252
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000253std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000255 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 }
257
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 bool first = true;
260 Region::const_iterator cur = region.begin();
261 Region::const_iterator const tail = region.end();
262 while (cur != tail) {
263 if (first) {
264 first = false;
265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 cur++;
270 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000271 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500275 constexpr size_t maxEntries = 50; // max events to print
276 constexpr size_t skipBegin = maxEntries / 2;
277 const size_t skipEnd = queue.size() - maxEntries / 2;
278 // skip from maxEntries / 2 ... size() - maxEntries/2
279 // only print from 0 .. skipBegin and then from skipEnd .. size()
280
281 std::string dump;
282 for (size_t i = 0; i < queue.size(); i++) {
283 const DispatchEntry& entry = *queue[i];
284 if (i >= skipBegin && i < skipEnd) {
285 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
286 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
287 continue;
288 }
289 dump.append(INDENT4);
290 dump += entry.eventEntry->getDescription();
291 dump += StringPrintf(", seq=%" PRIu32
292 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
293 entry.seq, entry.targetFlags, entry.resolvedAction,
294 ns2ms(currentTime - entry.eventEntry->eventTime));
295 if (entry.deliveryTime != 0) {
296 // This entry was delivered, so add information on how long we've been waiting
297 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
298 }
299 dump.append("\n");
300 }
301 return dump;
302}
303
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700304/**
305 * Find the entry in std::unordered_map by key, and return it.
306 * If the entry is not found, return a default constructed entry.
307 *
308 * Useful when the entries are vectors, since an empty vector will be returned
309 * if the entry is not found.
310 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
311 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700312template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000313V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700314 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800316}
317
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700319 if (first == second) {
320 return true;
321 }
322
323 if (first == nullptr || second == nullptr) {
324 return false;
325 }
326
327 return first->getToken() == second->getToken();
328}
329
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000330bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000331 if (first == nullptr || second == nullptr) {
332 return false;
333 }
334 return first->applicationInfo.token != nullptr &&
335 first->applicationInfo.token == second->applicationInfo.token;
336}
337
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000338bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800339 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
340}
341
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000342std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
343 std::shared_ptr<EventEntry> eventEntry,
344 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900345 if (eventEntry->type == EventEntry::Type::MOTION) {
346 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhan664834b2021-05-20 16:00:42 -0700347 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
348 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900349 const ui::Transform identityTransform;
Prabir Pradhan664834b2021-05-20 16:00:42 -0700350 // Use identity transform for joystick and position-based (touchpad) events because they
351 // don't depend on the window transform.
yunho.shinf4a80b82020-11-16 21:13:57 +0900352 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700353 identityTransform, 1.0f /*globalScaleFactor*/);
yunho.shinf4a80b82020-11-16 21:13:57 +0900354 }
355 }
356
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 if (inputTarget.useDefaultPointerTransform()) {
358 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700359 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700360 inputTarget.displayTransform,
361 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000362 }
363
364 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
365 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::vector<PointerCoords> pointerCoords;
368 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000369
370 // Use the first pointer information to normalize all other pointers. This could be any pointer
371 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 // uses the transform for the normalized pointer.
373 const ui::Transform& firstPointerTransform =
374 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
375 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376
377 // Iterate through all pointers in the event to normalize against the first.
378 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
379 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
380 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700381 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382
383 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700384 // First, apply the current pointer's transform to update the coordinates into
385 // window space.
386 pointerCoords[pointerIndex].transform(currTransform);
387 // Next, apply the inverse transform of the normalized coordinates so the
388 // current coordinates are transformed into the normalized coordinate space.
389 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 }
391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700392 std::unique_ptr<MotionEntry> combinedMotionEntry =
393 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
394 motionEntry.deviceId, motionEntry.source,
395 motionEntry.displayId, motionEntry.policyFlags,
396 motionEntry.action, motionEntry.actionButton,
397 motionEntry.flags, motionEntry.metaState,
398 motionEntry.buttonState, motionEntry.classification,
399 motionEntry.edgeFlags, motionEntry.xPrecision,
400 motionEntry.yPrecision, motionEntry.xCursorPosition,
401 motionEntry.yCursorPosition, motionEntry.downTime,
402 motionEntry.pointerCount, motionEntry.pointerProperties,
403 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000404
405 if (motionEntry.injectionState) {
406 combinedMotionEntry->injectionState = motionEntry.injectionState;
407 combinedMotionEntry->injectionState->refCount += 1;
408 }
409
410 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700411 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700412 firstPointerTransform, inputTarget.displayTransform,
413 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000414 return dispatchEntry;
415}
416
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000417status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
418 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700419 std::unique_ptr<InputChannel> uniqueServerChannel;
420 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
421
422 serverChannel = std::move(uniqueServerChannel);
423 return result;
424}
425
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500426template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000427bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500428 if (lhs == nullptr && rhs == nullptr) {
429 return true;
430 }
431 if (lhs == nullptr || rhs == nullptr) {
432 return false;
433 }
434 return *lhs == *rhs;
435}
436
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000437sp<IPlatformCompatNative> getCompatService() {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000438 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
439 if (service == nullptr) {
440 ALOGE("Failed to link to compat service");
441 return nullptr;
442 }
443 return interface_cast<IPlatformCompatNative>(service);
444}
445
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000446KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000447 KeyEvent event;
448 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
449 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
450 entry.repeatCount, entry.downTime, entry.eventTime);
451 return event;
452}
453
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000454std::optional<int32_t> findMonitorPidByToken(
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000455 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
456 const sp<IBinder>& token) {
457 for (const auto& it : monitorsByDisplay) {
458 const std::vector<Monitor>& monitors = it.second;
459 for (const Monitor& monitor : monitors) {
460 if (monitor.inputChannel->getConnectionToken() == token) {
461 return monitor.pid;
462 }
463 }
464 }
465 return std::nullopt;
466}
467
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000468bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000469 // Do not keep track of gesture monitors. They receive every event and would disproportionately
470 // affect the statistics.
471 if (connection.monitor) {
472 return false;
473 }
474 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
475 if (!connection.responsive) {
476 return false;
477 }
478 return true;
479}
480
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000481bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000482 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
483 const int32_t& inputEventId = eventEntry.id;
484 if (inputEventId != dispatchEntry.resolvedEventId) {
485 // Event was transmuted
486 return false;
487 }
488 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
489 return false;
490 }
491 // Only track latency for events that originated from hardware
492 if (eventEntry.isSynthesized()) {
493 return false;
494 }
495 const EventEntry::Type& inputEventEntryType = eventEntry.type;
496 if (inputEventEntryType == EventEntry::Type::KEY) {
497 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
498 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
499 return false;
500 }
501 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
502 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
503 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
504 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
505 return false;
506 }
507 } else {
508 // Not a key or a motion
509 return false;
510 }
511 if (!shouldReportMetricsForConnection(connection)) {
512 return false;
513 }
514 return true;
515}
516
Prabir Pradhancef936d2021-07-21 16:17:52 +0000517/**
518 * Connection is responsive if it has no events in the waitQueue that are older than the
519 * current time.
520 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000521bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000522 const nsecs_t currentTime = now();
523 for (const DispatchEntry* entry : connection.waitQueue) {
524 if (entry->timeoutTime < currentTime) {
525 return false;
526 }
527 }
528 return true;
529}
530
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700531bool isFromSource(uint32_t source, uint32_t test) {
532 return (source & test) == test;
533}
534
535vec2 transformWithoutTranslation(const ui::Transform& transform, float x, float y) {
536 const vec2 transformedXy = transform.transform(x, y);
537 const vec2 transformedOrigin = transform.transform(0, 0);
538 return transformedXy - transformedOrigin;
539}
540
Antonio Kantekf16f2832021-09-28 04:39:20 +0000541// Returns true if the event type passed as argument represents a user activity.
542bool isUserActivityEvent(const EventEntry& eventEntry) {
543 switch (eventEntry.type) {
544 case EventEntry::Type::FOCUS:
545 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
546 case EventEntry::Type::DRAG:
547 case EventEntry::Type::TOUCH_MODE_CHANGED:
548 case EventEntry::Type::SENSOR:
549 case EventEntry::Type::CONFIGURATION_CHANGED:
550 return false;
551 case EventEntry::Type::DEVICE_RESET:
552 case EventEntry::Type::KEY:
553 case EventEntry::Type::MOTION:
554 return true;
555 }
556}
557
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000558} // namespace
559
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560// --- InputDispatcher ---
561
Garfield Tan00f511d2019-06-12 16:55:40 -0700562InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
563 : mPolicy(policy),
564 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700565 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800566 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700567 mAppSwitchSawKeyDown(false),
568 mAppSwitchDueTime(LONG_LONG_MAX),
569 mNextUnblockedEvent(nullptr),
570 mDispatchEnabled(false),
571 mDispatchFrozen(false),
572 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800573 // mInTouchMode will be initialized by the WindowManager to the default device config.
574 // To avoid leaking stack in case that call never comes, and for tests,
575 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000576 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100577 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000578 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800579 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000580 mLatencyAggregator(),
581 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000582 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800584 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700586 mWindowInfoListener = new DispatcherWindowListener(*this);
587 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
588
Yi Kong9b14ac62018-07-17 13:48:38 -0700589 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590
591 policy->getDispatcherConfiguration(&mConfig);
592}
593
594InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000595 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596
Prabir Pradhancef936d2021-07-21 16:17:52 +0000597 resetKeyRepeatLocked();
598 releasePendingEventLocked();
599 drainInboundQueueLocked();
600 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000602 while (!mConnectionsByToken.empty()) {
603 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000604 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
605 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 }
607}
608
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700611 return ALREADY_EXISTS;
612 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700613 mThread = std::make_unique<InputThread>(
614 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
615 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700616}
617
618status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700619 if (mThread && mThread->isCallingThread()) {
620 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700621 return INVALID_OPERATION;
622 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700623 mThread.reset();
624 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700625}
626
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627void InputDispatcher::dispatchOnce() {
628 nsecs_t nextWakeupTime = LONG_LONG_MAX;
629 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800630 std::scoped_lock _l(mLock);
631 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632
633 // Run a dispatch loop if there are no pending commands.
634 // The dispatch loop might enqueue commands to run afterwards.
635 if (!haveCommandsLocked()) {
636 dispatchOnceInnerLocked(&nextWakeupTime);
637 }
638
639 // Run all pending commands if there are any.
640 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000641 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 nextWakeupTime = LONG_LONG_MIN;
643 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800644
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700645 // If we are still waiting for ack on some events,
646 // we might have to wake up earlier to check if an app is anr'ing.
647 const nsecs_t nextAnrCheck = processAnrsLocked();
648 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
649
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800650 // We are about to enter an infinitely long sleep, because we have no commands or
651 // pending or queued events
652 if (nextWakeupTime == LONG_LONG_MAX) {
653 mDispatcherEnteredIdle.notify_all();
654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 } // release lock
656
657 // Wait for callback or timeout or wake. (make sure we round up, not down)
658 nsecs_t currentTime = now();
659 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
660 mLooper->pollOnce(timeoutMillis);
661}
662
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700663/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500664 * Raise ANR if there is no focused window.
665 * Before the ANR is raised, do a final state check:
666 * 1. The currently focused application must be the same one we are waiting for.
667 * 2. Ensure we still don't have a focused window.
668 */
669void InputDispatcher::processNoFocusedWindowAnrLocked() {
670 // Check if the application that we are waiting for is still focused.
671 std::shared_ptr<InputApplicationHandle> focusedApplication =
672 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
673 if (focusedApplication == nullptr ||
674 focusedApplication->getApplicationToken() !=
675 mAwaitedFocusedApplication->getApplicationToken()) {
676 // Unexpected because we should have reset the ANR timer when focused application changed
677 ALOGE("Waited for a focused window, but focused application has already changed to %s",
678 focusedApplication->getName().c_str());
679 return; // The focused application has changed.
680 }
681
chaviw98318de2021-05-19 16:45:23 -0500682 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
684 if (focusedWindowHandle != nullptr) {
685 return; // We now have a focused window. No need for ANR.
686 }
687 onAnrLocked(mAwaitedFocusedApplication);
688}
689
690/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 * Check if any of the connections' wait queues have events that are too old.
692 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
693 * Return the time at which we should wake up next.
694 */
695nsecs_t InputDispatcher::processAnrsLocked() {
696 const nsecs_t currentTime = now();
697 nsecs_t nextAnrCheck = LONG_LONG_MAX;
698 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
699 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
700 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500701 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700702 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500703 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 return LONG_LONG_MIN;
705 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500706 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
708 }
709 }
710
711 // Check if any connection ANRs are due
712 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
713 if (currentTime < nextAnrCheck) { // most likely scenario
714 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
715 }
716
717 // If we reached here, we have an unresponsive connection.
718 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
719 if (connection == nullptr) {
720 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
721 return nextAnrCheck;
722 }
723 connection->responsive = false;
724 // Stop waking up for this unresponsive connection
725 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000726 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700727 return LONG_LONG_MIN;
728}
729
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500730std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
chaviw98318de2021-05-19 16:45:23 -0500731 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500733 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700734 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500735 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736}
737
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
739 nsecs_t currentTime = now();
740
Jeff Browndc5992e2014-04-11 01:27:26 -0700741 // Reset the key repeat timer whenever normal dispatch is suspended while the
742 // device is in a non-interactive state. This is to ensure that we abort a key
743 // repeat if the device is just coming out of sleep.
744 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 resetKeyRepeatLocked();
746 }
747
748 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
749 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100750 if (DEBUG_FOCUS) {
751 ALOGD("Dispatch frozen. Waiting some more.");
752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 return;
754 }
755
756 // Optimize latency of app switches.
757 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
758 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
759 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
760 if (mAppSwitchDueTime < *nextWakeupTime) {
761 *nextWakeupTime = mAppSwitchDueTime;
762 }
763
764 // Ready to start a new event.
765 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700767 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 if (isAppSwitchDue) {
769 // The inbound queue is empty so the app switch key we were waiting
770 // for will never arrive. Stop waiting for it.
771 resetPendingAppSwitchLocked(false);
772 isAppSwitchDue = false;
773 }
774
775 // Synthesize a key repeat if appropriate.
776 if (mKeyRepeatState.lastKeyEntry) {
777 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
778 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
779 } else {
780 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
781 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
782 }
783 }
784 }
785
786 // Nothing to do if there is no pending event.
787 if (!mPendingEvent) {
788 return;
789 }
790 } else {
791 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700792 mPendingEvent = mInboundQueue.front();
793 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 traceInboundQueueLengthLocked();
795 }
796
797 // Poke user activity for this event.
798 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700799 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802
803 // Now we have an event to dispatch.
804 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700805 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700807 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700809 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 }
813
814 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700815 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700819 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 const ConfigurationChangedEntry& typedEntry =
821 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 break;
825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700827 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700828 const DeviceResetEntry& typedEntry =
829 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700831 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 break;
833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100835 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700836 std::shared_ptr<FocusEntry> typedEntry =
837 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100838 dispatchFocusLocked(currentTime, typedEntry);
839 done = true;
840 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
841 break;
842 }
843
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700844 case EventEntry::Type::TOUCH_MODE_CHANGED: {
845 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
846 dispatchTouchModeChangeLocked(currentTime, typedEntry);
847 done = true;
848 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
849 break;
850 }
851
Prabir Pradhan99987712020-11-10 18:43:05 -0800852 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
853 const auto typedEntry =
854 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
855 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
856 done = true;
857 break;
858 }
859
arthurhungb89ccb02020-12-30 16:19:01 +0800860 case EventEntry::Type::DRAG: {
861 std::shared_ptr<DragEntry> typedEntry =
862 std::static_pointer_cast<DragEntry>(mPendingEvent);
863 dispatchDragLocked(currentTime, typedEntry);
864 done = true;
865 break;
866 }
867
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700868 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 resetPendingAppSwitchLocked(true);
873 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700874 } else if (dropReason == DropReason::NOT_DROPPED) {
875 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 }
877 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700878 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
882 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700884 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 break;
886 }
887
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700888 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700889 std::shared_ptr<MotionEntry> motionEntry =
890 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700891 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
892 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700894 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
898 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700900 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
Chris Yef59a2f42020-10-16 12:55:26 -0700903
904 case EventEntry::Type::SENSOR: {
905 std::shared_ptr<SensorEntry> sensorEntry =
906 std::static_pointer_cast<SensorEntry>(mPendingEvent);
907 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
908 dropReason = DropReason::APP_SWITCH;
909 }
910 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
911 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
912 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
913 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
914 dropReason = DropReason::STALE;
915 }
916 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
917 done = true;
918 break;
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 }
921
922 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700924 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
Michael Wright3a981722015-06-10 15:26:13 +0100926 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927
928 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
931}
932
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700933/**
934 * Return true if the events preceding this incoming motion event should be dropped
935 * Return false otherwise (the default behaviour)
936 */
937bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700938 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700939 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700940
941 // Optimize case where the current application is unresponsive and the user
942 // decides to touch a window in a different application.
943 // If the application takes too long to catch up then we drop all events preceding
944 // the touch into the other window.
945 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700946 int32_t displayId = motionEntry.displayId;
947 int32_t x = static_cast<int32_t>(
948 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
949 int32_t y = static_cast<int32_t>(
950 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
chaviw98318de2021-05-19 16:45:23 -0500951 sp<WindowInfoHandle> touchedWindowHandle =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700952 findTouchedWindowAtLocked(displayId, x, y, nullptr);
953 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700954 touchedWindowHandle->getApplicationToken() !=
955 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700956 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700957 ALOGI("Pruning input queue because user touched a different application while waiting "
958 "for %s",
959 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700960 return true;
961 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700962
963 // Alternatively, maybe there's a gesture monitor that could handle this event
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700964 for (const auto& monitor : getValueByKey(mGestureMonitorsByDisplay, displayId)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700965 sp<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -0700966 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000967 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968 // This monitor could take more input. Drop all events preceding this
969 // event, so that gesture monitor could get a chance to receive the stream
970 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
971 "responsive gesture monitor that may handle the event",
972 mAwaitedFocusedApplication->getName().c_str());
973 return true;
974 }
975 }
976 }
977
978 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
979 // yet been processed by some connections, the dispatcher will wait for these motion
980 // events to be processed before dispatching the key event. This is because these motion events
981 // may cause a new window to be launched, which the user might expect to receive focus.
982 // To prevent waiting forever for such events, just send the key to the currently focused window
983 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
984 ALOGD("Received a new pointer down event, stop waiting for events to process and "
985 "just send the pending key event to the focused window.");
986 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700987 }
988 return false;
989}
990
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700992 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700993 mInboundQueue.push_back(std::move(newEntry));
994 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 traceInboundQueueLengthLocked();
996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700997 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700998 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 // Optimize app switch latency.
1000 // If the application takes too long to catch up then we drop all events preceding
1001 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001002 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001004 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001005 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001006 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001008 if (DEBUG_APP_SWITCH) {
1009 ALOGD("App switch is pending!");
1010 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001011 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 mAppSwitchSawKeyDown = false;
1013 needWake = true;
1014 }
1015 }
1016 }
1017 break;
1018 }
1019
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001020 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001021 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1022 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001023 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001027 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001028 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1029 break;
1030 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001031 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001032 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001033 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001034 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001035 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1036 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001037 // nothing to do
1038 break;
1039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
1041
1042 return needWake;
1043}
1044
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001045void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001046 // Do not store sensor event in recent queue to avoid flooding the queue.
1047 if (entry->type != EventEntry::Type::SENSOR) {
1048 mRecentQueue.push_back(entry);
1049 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001050 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001051 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
1053}
1054
chaviw98318de2021-05-19 16:45:23 -05001055sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1056 int32_t y, TouchState* touchState,
1057 bool addOutsideTargets,
1058 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001059 if (addOutsideTargets && touchState == nullptr) {
1060 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 // Traverse windows from front to back to find touched window.
chaviw98318de2021-05-19 16:45:23 -05001063 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1064 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001065 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001066 continue;
1067 }
chaviw98318de2021-05-19 16:45:23 -05001068 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001070 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071
1072 if (windowInfo->visible) {
chaviw98318de2021-05-19 16:45:23 -05001073 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1074 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1075 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1077 // Found window.
1078 return windowHandle;
1079 }
1080 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001081
chaviw98318de2021-05-19 16:45:23 -05001082 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001083 touchState->addOrUpdateWindow(windowHandle,
1084 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1085 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001090 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091}
1092
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001093void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 const char* reason;
1095 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001097 if (DEBUG_INBOUND_EVENT_DETAILS) {
1098 ALOGD("Dropped event because policy consumed it.");
1099 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 reason = "inbound event was dropped because the policy consumed it";
1101 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001102 case DropReason::DISABLED:
1103 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 ALOGI("Dropped event because input dispatch is disabled.");
1105 }
1106 reason = "inbound event was dropped because input dispatch is disabled";
1107 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001108 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001109 ALOGI("Dropped event because of pending overdue app switch.");
1110 reason = "inbound event was dropped because of pending overdue app switch";
1111 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001112 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 ALOGI("Dropped event because the current application is not responding and the user "
1114 "has started interacting with a different application.");
1115 reason = "inbound event was dropped because the current application is not responding "
1116 "and the user has started interacting with a different application";
1117 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 ALOGI("Dropped event because it is stale.");
1120 reason = "inbound event was dropped because it is stale";
1121 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001122 case DropReason::NO_POINTER_CAPTURE:
1123 ALOGI("Dropped event because there is no window with Pointer Capture.");
1124 reason = "inbound event was dropped because there is no window with Pointer Capture";
1125 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001126 case DropReason::NOT_DROPPED: {
1127 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001132 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1135 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001138 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001139 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1140 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1142 synthesizeCancelationEventsForAllConnectionsLocked(options);
1143 } else {
1144 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1145 synthesizeCancelationEventsForAllConnectionsLocked(options);
1146 }
1147 break;
1148 }
Chris Yef59a2f42020-10-16 12:55:26 -07001149 case EventEntry::Type::SENSOR: {
1150 break;
1151 }
arthurhungb89ccb02020-12-30 16:19:01 +08001152 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1153 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001154 break;
1155 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001156 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001157 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001158 case EventEntry::Type::CONFIGURATION_CHANGED:
1159 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001160 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001161 break;
1162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 }
1164}
1165
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001166static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1168 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169}
1170
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1172 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1173 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1174 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175}
1176
1177bool InputDispatcher::isAppSwitchPendingLocked() {
1178 return mAppSwitchDueTime != LONG_LONG_MAX;
1179}
1180
1181void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1182 mAppSwitchDueTime = LONG_LONG_MAX;
1183
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001184 if (DEBUG_APP_SWITCH) {
1185 if (handled) {
1186 ALOGD("App switch has arrived.");
1187 } else {
1188 ALOGD("App switch was abandoned.");
1189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191}
1192
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001194 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195}
1196
Prabir Pradhancef936d2021-07-21 16:17:52 +00001197bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001198 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 return false;
1200 }
1201
1202 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001203 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001204 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001205 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1206 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001207 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 return true;
1209}
1210
Prabir Pradhancef936d2021-07-21 16:17:52 +00001211void InputDispatcher::postCommandLocked(Command&& command) {
1212 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213}
1214
1215void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001216 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001218 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 releaseInboundEventLocked(entry);
1220 }
1221 traceInboundQueueLengthLocked();
1222}
1223
1224void InputDispatcher::releasePendingEventLocked() {
1225 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001227 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229}
1230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001231void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001233 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001234 if (DEBUG_DISPATCH_CYCLE) {
1235 ALOGD("Injected inbound event was dropped.");
1236 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 }
1239 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001240 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 }
1242 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243}
1244
1245void InputDispatcher::resetKeyRepeatLocked() {
1246 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001247 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
1249}
1250
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1252 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253
Michael Wright2e732952014-09-24 13:26:59 -07001254 uint32_t policyFlags = entry->policyFlags &
1255 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 std::shared_ptr<KeyEntry> newEntry =
1258 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1259 entry->source, entry->displayId, policyFlags, entry->action,
1260 entry->flags, entry->keyCode, entry->scanCode,
1261 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001263 newEntry->syntheticRepeat = true;
1264 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267}
1268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001270 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001271 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1272 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274
1275 // Reset key repeating in case a keyboard device was added or removed or something.
1276 resetKeyRepeatLocked();
1277
1278 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001279 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1280 scoped_unlock unlock(mLock);
1281 mPolicy->notifyConfigurationChanged(eventTime);
1282 };
1283 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 return true;
1285}
1286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1288 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001289 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1290 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1291 entry.deviceId);
1292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
liushenxiang42232912021-05-21 20:24:09 +08001294 // Reset key repeating in case a keyboard device was disabled or enabled.
1295 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1296 resetKeyRepeatLocked();
1297 }
1298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 synthesizeCancelationEventsForAllConnectionsLocked(options);
1302 return true;
1303}
1304
Vishnu Nairad321cd2020-08-20 16:40:21 -07001305void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001306 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001307 if (mPendingEvent != nullptr) {
1308 // Move the pending event to the front of the queue. This will give the chance
1309 // for the pending event to get dispatched to the newly focused window
1310 mInboundQueue.push_front(mPendingEvent);
1311 mPendingEvent = nullptr;
1312 }
1313
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314 std::unique_ptr<FocusEntry> focusEntry =
1315 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1316 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001317
1318 // This event should go to the front of the queue, but behind all other focus events
1319 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001320 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001321 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001322 [](const std::shared_ptr<EventEntry>& event) {
1323 return event->type == EventEntry::Type::FOCUS;
1324 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001325
1326 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001327 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001328}
1329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001330void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001331 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001332 if (channel == nullptr) {
1333 return; // Window has gone away
1334 }
1335 InputTarget target;
1336 target.inputChannel = channel;
1337 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1338 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001339 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1340 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001341 std::string reason = std::string("reason=").append(entry->reason);
1342 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001343 dispatchEventLocked(currentTime, entry, {target});
1344}
1345
Prabir Pradhan99987712020-11-10 18:43:05 -08001346void InputDispatcher::dispatchPointerCaptureChangedLocked(
1347 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1348 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001349 dropReason = DropReason::NOT_DROPPED;
1350
Prabir Pradhan99987712020-11-10 18:43:05 -08001351 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001352 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001353
1354 if (entry->pointerCaptureRequest.enable) {
1355 // Enable Pointer Capture.
1356 if (haveWindowWithPointerCapture &&
1357 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1358 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1359 "to the window.");
1360 }
1361 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001362 // This can happen if a window requests capture and immediately releases capture.
1363 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001364 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001365 return;
1366 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001367 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1368 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1369 return;
1370 }
1371
Vishnu Nairc519ff72021-01-21 08:23:08 -08001372 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001373 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1374 mWindowTokenWithPointerCapture = token;
1375 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001376 // Disable Pointer Capture.
1377 // We do not check if the sequence number matches for requests to disable Pointer Capture
1378 // for two reasons:
1379 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1380 // to disable capture with the same sequence number: one generated by
1381 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1382 // Capture being disabled in InputReader.
1383 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1384 // actual Pointer Capture state that affects events being generated by input devices is
1385 // in InputReader.
1386 if (!haveWindowWithPointerCapture) {
1387 // Pointer capture was already forcefully disabled because of focus change.
1388 dropReason = DropReason::NOT_DROPPED;
1389 return;
1390 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 token = mWindowTokenWithPointerCapture;
1392 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001394 setPointerCaptureLocked(false);
1395 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001396 }
1397
1398 auto channel = getInputChannelLocked(token);
1399 if (channel == nullptr) {
1400 // Window has gone away, clean up Pointer Capture state.
1401 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001402 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001403 setPointerCaptureLocked(false);
1404 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001405 return;
1406 }
1407 InputTarget target;
1408 target.inputChannel = channel;
1409 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1410 entry->dispatchInProgress = true;
1411 dispatchEventLocked(currentTime, entry, {target});
1412
1413 dropReason = DropReason::NOT_DROPPED;
1414}
1415
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001416void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1417 const std::shared_ptr<TouchModeEntry>& entry) {
1418 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1419 getWindowHandlesLocked(mFocusedDisplayId);
1420 if (windowHandles.empty()) {
1421 return;
1422 }
1423 const std::vector<InputTarget> inputTargets =
1424 getInputTargetsFromWindowHandlesLocked(windowHandles);
1425 if (inputTargets.empty()) {
1426 return;
1427 }
1428 entry->dispatchInProgress = true;
1429 dispatchEventLocked(currentTime, entry, inputTargets);
1430}
1431
1432std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1433 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1434 std::vector<InputTarget> inputTargets;
1435 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1436 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1437 const sp<IBinder>& token = handle->getToken();
1438 if (token == nullptr) {
1439 continue;
1440 }
1441 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1442 if (channel == nullptr) {
1443 continue; // Window has gone away
1444 }
1445 InputTarget target;
1446 target.inputChannel = channel;
1447 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1448 inputTargets.push_back(target);
1449 }
1450 return inputTargets;
1451}
1452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001454 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 if (!entry->dispatchInProgress) {
1457 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1458 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1459 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1460 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001461 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 // We have seen two identical key downs in a row which indicates that the device
1463 // driver is automatically generating key repeats itself. We take note of the
1464 // repeat here, but we disable our own next key repeat timer since it is clear that
1465 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001466 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1467 // Make sure we don't get key down from a different device. If a different
1468 // device Id has same key pressed down, the new device Id will replace the
1469 // current one to hold the key repeat with repeat count reset.
1470 // In the future when got a KEY_UP on the device id, drop it and do not
1471 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1473 resetKeyRepeatLocked();
1474 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1475 } else {
1476 // Not a repeat. Save key down state in case we do see a repeat later.
1477 resetKeyRepeatLocked();
1478 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1479 }
1480 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001481 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1482 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001484 if (DEBUG_INBOUND_EVENT_DETAILS) {
1485 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1486 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001487 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 resetKeyRepeatLocked();
1489 }
1490
1491 if (entry->repeatCount == 1) {
1492 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1493 } else {
1494 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1495 }
1496
1497 entry->dispatchInProgress = true;
1498
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001499 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 }
1501
1502 // Handle case where the policy asked us to try again later last time.
1503 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1504 if (currentTime < entry->interceptKeyWakeupTime) {
1505 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1506 *nextWakeupTime = entry->interceptKeyWakeupTime;
1507 }
1508 return false; // wait until next wakeup
1509 }
1510 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1511 entry->interceptKeyWakeupTime = 0;
1512 }
1513
1514 // Give the policy a chance to intercept the key.
1515 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1516 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001517 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001518 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001519
1520 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1521 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1522 };
1523 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 return false; // wait for the command to run
1525 } else {
1526 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1527 }
1528 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001529 if (*dropReason == DropReason::NOT_DROPPED) {
1530 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532 }
1533
1534 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001535 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001536 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001537 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1538 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001539 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 return true;
1541 }
1542
1543 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001544 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001545 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001546 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 return false;
1549 }
1550
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001551 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001552 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 return true;
1554 }
1555
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001556 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001557 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558
1559 // Dispatch the key.
1560 dispatchEventLocked(currentTime, entry, inputTargets);
1561 return true;
1562}
1563
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001564void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1566 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1567 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1568 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1569 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1570 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1571 entry.metaState, entry.repeatCount, entry.downTime);
1572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573}
1574
Prabir Pradhancef936d2021-07-21 16:17:52 +00001575void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1576 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001577 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001578 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1579 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1580 "source=0x%x, sensorType=%s",
1581 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001582 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001583 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001584 auto command = [this, entry]() REQUIRES(mLock) {
1585 scoped_unlock unlock(mLock);
1586
1587 if (entry->accuracyChanged) {
1588 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1589 }
1590 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1591 entry->hwTimestamp, entry->values);
1592 };
1593 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001594}
1595
1596bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001597 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1598 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001599 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 }
Chris Yef59a2f42020-10-16 12:55:26 -07001601 { // acquire lock
1602 std::scoped_lock _l(mLock);
1603
1604 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1605 std::shared_ptr<EventEntry> entry = *it;
1606 if (entry->type == EventEntry::Type::SENSOR) {
1607 it = mInboundQueue.erase(it);
1608 releaseInboundEventLocked(entry);
1609 }
1610 }
1611 }
1612 return true;
1613}
1614
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001615bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001616 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001617 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001619 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 entry->dispatchInProgress = true;
1621
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001622 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 }
1624
1625 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001626 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001627 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001628 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1629 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 return true;
1631 }
1632
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001633 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634
1635 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001636 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637
1638 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001639 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 if (isPointerEvent) {
1641 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001643 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 } else {
1646 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001650 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 return false;
1652 }
1653
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001654 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001655 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001656 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1657 return true;
1658 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001659 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001660 CancelationOptions::Mode mode(isPointerEvent
1661 ? CancelationOptions::CANCEL_POINTER_EVENTS
1662 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1663 CancelationOptions options(mode, "input event injection failed");
1664 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 return true;
1666 }
1667
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001668 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001669 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670
1671 // Dispatch the motion.
1672 if (conflictingPointerActions) {
1673 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 synthesizeCancelationEventsForAllConnectionsLocked(options);
1676 }
1677 dispatchEventLocked(currentTime, entry, inputTargets);
1678 return true;
1679}
1680
chaviw98318de2021-05-19 16:45:23 -05001681void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001682 bool isExiting, const MotionEntry& motionEntry) {
1683 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1684 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1685 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1686 PointerCoords pointerCoords;
1687 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1688 pointerCoords.transform(windowHandle->getInfo()->transform);
1689
1690 std::unique_ptr<DragEntry> dragEntry =
1691 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1692 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1693 pointerCoords.getY());
1694
1695 enqueueInboundEventLocked(std::move(dragEntry));
1696}
1697
1698void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1699 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1700 if (channel == nullptr) {
1701 return; // Window has gone away
1702 }
1703 InputTarget target;
1704 target.inputChannel = channel;
1705 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1706 entry->dispatchInProgress = true;
1707 dispatchEventLocked(currentTime, entry, {target});
1708}
1709
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001710void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001711 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1712 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1713 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001714 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001715 "metaState=0x%x, buttonState=0x%x,"
1716 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1717 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001718 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1719 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1720 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001722 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1723 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1724 "x=%f, y=%f, pressure=%f, size=%f, "
1725 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1726 "orientation=%f",
1727 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1728 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1729 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1730 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1731 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1732 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1733 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1734 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1735 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1736 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739}
1740
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001741void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1742 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001743 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001744 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001745 if (DEBUG_DISPATCH_CYCLE) {
1746 ALOGD("dispatchEventToCurrentInputTargets");
1747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001749 updateInteractionTokensLocked(*eventEntry, inputTargets);
1750
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1752
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001753 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001755 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001756 sp<Connection> connection =
1757 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001758 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001759 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001761 if (DEBUG_FOCUS) {
1762 ALOGD("Dropping event delivery to target with channel '%s' because it "
1763 "is no longer registered with the input dispatcher.",
1764 inputTarget.inputChannel->getName().c_str());
1765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 }
1767 }
1768}
1769
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1771 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1772 // If the policy decides to close the app, we will get a channel removal event via
1773 // unregisterInputChannel, and will clean up the connection that way. We are already not
1774 // sending new pointers to the connection when it blocked, but focused events will continue to
1775 // pile up.
1776 ALOGW("Canceling events for %s because it is unresponsive",
1777 connection->inputChannel->getName().c_str());
1778 if (connection->status == Connection::STATUS_NORMAL) {
1779 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1780 "application not responding");
1781 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 }
1783}
1784
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001785void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001786 if (DEBUG_FOCUS) {
1787 ALOGD("Resetting ANR timeouts.");
1788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789
1790 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001791 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001792 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793}
1794
Tiger Huang721e26f2018-07-24 22:26:19 +08001795/**
1796 * Get the display id that the given event should go to. If this event specifies a valid display id,
1797 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1798 * Focused display is the display that the user most recently interacted with.
1799 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001800int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001801 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001802 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001803 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001804 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1805 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 break;
1807 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001808 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001809 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1810 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001811 break;
1812 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001813 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001814 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001815 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001816 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001817 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001818 case EventEntry::Type::SENSOR:
1819 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001820 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 return ADISPLAY_ID_NONE;
1822 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001823 }
1824 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1825}
1826
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001827bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1828 const char* focusedWindowName) {
1829 if (mAnrTracker.empty()) {
1830 // already processed all events that we waited for
1831 mKeyIsWaitingForEventsTimeout = std::nullopt;
1832 return false;
1833 }
1834
1835 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1836 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001837 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001838 mKeyIsWaitingForEventsTimeout = currentTime +
1839 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1840 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 return true;
1842 }
1843
1844 // We still have pending events, and already started the timer
1845 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1846 return true; // Still waiting
1847 }
1848
1849 // Waited too long, and some connection still hasn't processed all motions
1850 // Just send the key to the focused window
1851 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1852 focusedWindowName);
1853 mKeyIsWaitingForEventsTimeout = std::nullopt;
1854 return false;
1855}
1856
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001857InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1858 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1859 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001860 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861
Tiger Huang721e26f2018-07-24 22:26:19 +08001862 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001863 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001864 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001865 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1866
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 // If there is no currently focused window and no focused application
1868 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001869 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1870 ALOGI("Dropping %s event because there is no focused window or focused application in "
1871 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001872 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001873 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
1875
Vishnu Nair062a8672021-09-03 16:07:44 -07001876 // Drop key events if requested by input feature
1877 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1878 return InputEventInjectionResult::FAILED;
1879 }
1880
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1882 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1883 // start interacting with another application via touch (app switch). This code can be removed
1884 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1885 // an app is expected to have a focused window.
1886 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1887 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1888 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001889 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1890 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1891 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001893 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 ALOGW("Waiting because no window has focus but %s may eventually add a "
1895 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001896 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001897 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001898 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1900 // Already raised ANR. Drop the event
1901 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001902 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 } else {
1905 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 }
1908 }
1909
1910 // we have a valid, non-null focused window
1911 resetNoFocusedWindowTimeoutLocked();
1912
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001914 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001915 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 }
1917
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 if (focusedWindowHandle->getInfo()->paused) {
1919 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001920 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001921 }
1922
1923 // If the event is a key event, then we must wait for all previous events to
1924 // complete before delivering it because previous events may have the
1925 // side-effect of transferring focus to a different window and we want to
1926 // ensure that the following keys are sent to the new window.
1927 //
1928 // Suppose the user touches a button in a window then immediately presses "A".
1929 // If the button causes a pop-up window to appear then we want to ensure that
1930 // the "A" key is delivered to the new pop-up window. This is because users
1931 // often anticipate pending UI changes when typing on a keyboard.
1932 // To obtain this behavior, we must serialize key events with respect to all
1933 // prior input events.
1934 if (entry.type == EventEntry::Type::KEY) {
1935 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1936 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 }
1940
1941 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001942 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1944 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945
1946 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948}
1949
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950/**
1951 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1952 * that are currently unresponsive.
1953 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001954std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1955 const std::vector<Monitor>& monitors) const {
1956 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001957 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001958 [this](const Monitor& monitor) REQUIRES(mLock) {
1959 sp<Connection> connection =
1960 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 if (connection == nullptr) {
1962 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001963 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964 return false;
1965 }
1966 if (!connection->responsive) {
1967 ALOGW("Unresponsive monitor %s will not get the new gesture",
1968 connection->inputChannel->getName().c_str());
1969 return false;
1970 }
1971 return true;
1972 });
1973 return responsiveMonitors;
1974}
1975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001976InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1977 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1978 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001979 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 enum InjectionPermission {
1981 INJECTION_PERMISSION_UNKNOWN,
1982 INJECTION_PERMISSION_GRANTED,
1983 INJECTION_PERMISSION_DENIED
1984 };
1985
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 // For security reasons, we defer updating the touch state until we are sure that
1987 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001988 int32_t displayId = entry.displayId;
1989 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1991
1992 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001993 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001995 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1996 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001998 // Copy current touch state into tempTouchState.
1999 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2000 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002001 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002002 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07002003 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
2004 mTouchStatesByDisplay.find(displayId);
2005 if (oldStateIt != mTouchStatesByDisplay.end()) {
2006 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002007 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002008 }
2009
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002010 bool isSplit = tempTouchState.split;
2011 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2012 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2013 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2015 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2016 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2017 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2018 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002019 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 bool wrongDevice = false;
2021 if (newGesture) {
2022 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002024 ALOGI("Dropping event because a pointer for a different device is already down "
2025 "in display %" PRId32,
2026 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002027 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002028 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 switchedDevice = false;
2030 wrongDevice = true;
2031 goto Failed;
2032 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002033 tempTouchState.reset();
2034 tempTouchState.down = down;
2035 tempTouchState.deviceId = entry.deviceId;
2036 tempTouchState.source = entry.source;
2037 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002039 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002040 ALOGI("Dropping move event because a pointer for a different device is already active "
2041 "in display %" PRId32,
2042 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002043 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002044 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002045 switchedDevice = false;
2046 wrongDevice = true;
2047 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
2049
2050 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2051 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2052
Garfield Tan00f511d2019-06-12 16:55:40 -07002053 int32_t x;
2054 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002056 // Always dispatch mouse events to cursor position.
2057 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002058 x = int32_t(entry.xCursorPosition);
2059 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002060 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002061 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2062 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002063 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002064 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002065 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2066 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002067
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 if (newTouchedWindowHandle != nullptr &&
2070 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07002071 // New window supports splitting, but we should never split mouse events.
2072 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 } else if (isSplit) {
2074 // New window does not support splitting but we have already split events.
2075 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002076 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 }
2078
2079 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002080 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002081 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2082 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002084 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002085 }
2086
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002087 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2088 ALOGI("Not sending touch event to %s because it is paused",
2089 newTouchedWindowHandle->getName().c_str());
2090 newTouchedWindowHandle = nullptr;
2091 }
2092
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002093 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002094 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002095 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2096 if (!isResponsive) {
2097 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002098 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2099 newTouchedWindowHandle = nullptr;
2100 }
2101 }
2102
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002103 // Drop events that can't be trusted due to occlusion
2104 if (newTouchedWindowHandle != nullptr &&
2105 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2106 TouchOcclusionInfo occlusionInfo =
2107 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002108 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002109 if (DEBUG_TOUCH_OCCLUSION) {
2110 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2111 for (const auto& log : occlusionInfo.debugInfo) {
2112 ALOGD("%s", log.c_str());
2113 }
2114 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00002115 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002116 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2117 ALOGW("Dropping untrusted touch event due to %s/%d",
2118 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2119 newTouchedWindowHandle = nullptr;
2120 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002121 }
2122 }
2123
Vishnu Nair062a8672021-09-03 16:07:44 -07002124 // Drop touch events if requested by input feature
2125 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2126 newTouchedWindowHandle = nullptr;
2127 }
2128
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002129 const std::vector<Monitor> newGestureMonitors = isDown
2130 ? selectResponsiveMonitorsLocked(
2131 getValueByKey(mGestureMonitorsByDisplay, displayId))
2132 : std::vector<Monitor>{};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002133
Michael Wright3dd60e22019-03-27 22:06:44 +00002134 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2135 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 "(%d, %d) in display %" PRId32 ".",
2137 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002138 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 goto Failed;
2140 }
2141
2142 if (newTouchedWindowHandle != nullptr) {
2143 // Set target flags.
2144 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2145 if (isSplit) {
2146 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002148 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2149 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2150 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2151 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2152 }
2153
2154 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002155 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2156 newHoverWindowHandle = nullptr;
2157 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002158 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002159 }
2160
2161 // Update the temporary touch state.
2162 BitSet32 pointerIds;
2163 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002165 pointerIds.markBit(pointerId);
2166 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002167 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 }
2169
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002170 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 } else {
2172 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2173
2174 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002175 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002176 if (DEBUG_FOCUS) {
2177 ALOGD("Dropping event because the pointer is not down or we previously "
2178 "dropped the pointer down event in display %" PRId32,
2179 displayId);
2180 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002181 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 goto Failed;
2183 }
2184
arthurhung6d4bed92021-03-17 11:59:33 +08002185 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002186
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002188 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2191 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192
chaviw98318de2021-05-19 16:45:23 -05002193 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002194 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002195 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair062a8672021-09-03 16:07:44 -07002196
2197 // Drop touch events if requested by input feature
2198 if (newTouchedWindowHandle != nullptr &&
2199 shouldDropInput(entry, newTouchedWindowHandle)) {
2200 newTouchedWindowHandle = nullptr;
2201 }
2202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002203 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2204 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002205 if (DEBUG_FOCUS) {
2206 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2207 oldTouchedWindowHandle->getName().c_str(),
2208 newTouchedWindowHandle->getName().c_str(), displayId);
2209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002211 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2212 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2213 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214
2215 // Make a slippery entrance into the new window.
2216 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2217 isSplit = true;
2218 }
2219
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002220 int32_t targetFlags =
2221 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 if (isSplit) {
2223 targetFlags |= InputTarget::FLAG_SPLIT;
2224 }
2225 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2226 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002227 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2228 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
2231 BitSet32 pointerIds;
2232 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002233 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002235 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237 }
2238 }
2239
2240 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002241 // Let the previous window know that the hover sequence is over, unless we already did it
2242 // when dispatching it as is to newTouchedWindowHandle.
2243 if (mLastHoverWindowHandle != nullptr &&
2244 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2245 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002246 if (DEBUG_HOVER) {
2247 ALOGD("Sending hover exit event to window %s.",
2248 mLastHoverWindowHandle->getName().c_str());
2249 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2251 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
2253
Garfield Tandf26e862020-07-01 20:18:19 -07002254 // Let the new window know that the hover sequence is starting, unless we already did it
2255 // when dispatching it as is to newTouchedWindowHandle.
2256 if (newHoverWindowHandle != nullptr &&
2257 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2258 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002259 if (DEBUG_HOVER) {
2260 ALOGD("Sending hover enter event to window %s.",
2261 newHoverWindowHandle->getName().c_str());
2262 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002263 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2264 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2265 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267 }
2268
2269 // Check permission to inject into all touched foreground windows and ensure there
2270 // is at least one touched foreground window.
2271 {
2272 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002273 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2275 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002276 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002277 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 injectionPermission = INJECTION_PERMISSION_DENIED;
2279 goto Failed;
2280 }
2281 }
2282 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002285 ALOGI("Dropping event because there is no touched foreground window in display "
2286 "%" PRId32 " or gesture monitor to receive it.",
2287 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002288 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 goto Failed;
2290 }
2291
2292 // Permission granted to injection into all touched foreground windows.
2293 injectionPermission = INJECTION_PERMISSION_GRANTED;
2294 }
2295
2296 // Check whether windows listening for outside touches are owned by the same UID. If it is
2297 // set the policy flag that we will not reveal coordinate information to this window.
2298 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002299 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002300 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002301 if (foregroundWindowHandle) {
2302 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002304 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002305 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2306 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2307 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002308 InputTarget::FLAG_ZERO_COORDS,
2309 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 }
2312 }
2313 }
2314 }
2315
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 // If this is the first pointer going down and the touched window has a wallpaper
2317 // then also add the touched wallpaper windows so they are locked in for the duration
2318 // of the touch gesture.
2319 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2320 // engine only supports touch events. We would need to add a mechanism similar
2321 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2322 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002323 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002324 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002325 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
chaviw98318de2021-05-19 16:45:23 -05002326 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002327 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002328 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2329 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 if (info->displayId == displayId &&
chaviw98318de2021-05-19 16:45:23 -05002331 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002332 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 .addOrUpdateWindow(windowHandle,
2334 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2335 InputTarget::
2336 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2337 InputTarget::FLAG_DISPATCH_AS_IS,
2338 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340 }
2341 }
2342 }
2343
2344 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002345 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002347 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 }
2351
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002352 for (const auto& monitor : tempTouchState.gestureMonitors) {
2353 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002354 }
2355
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 // Drop the outside or hover touch windows since we will not care about them
2357 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002358 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
2360Failed:
2361 // Check injection permission once and for all.
2362 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002363 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 injectionPermission = INJECTION_PERMISSION_GRANTED;
2365 } else {
2366 injectionPermission = INJECTION_PERMISSION_DENIED;
2367 }
2368 }
2369
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002370 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2371 return injectionResult;
2372 }
2373
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002375 if (!wrongDevice) {
2376 if (switchedDevice) {
2377 if (DEBUG_FOCUS) {
2378 ALOGD("Conflicting pointer actions: Switched to a different device.");
2379 }
2380 *outConflictingPointerActions = true;
2381 }
2382
2383 if (isHoverAction) {
2384 // Started hovering, therefore no longer down.
2385 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002386 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002387 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2388 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 *outConflictingPointerActions = true;
2391 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002392 tempTouchState.reset();
2393 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2394 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2395 tempTouchState.deviceId = entry.deviceId;
2396 tempTouchState.source = entry.source;
2397 tempTouchState.displayId = displayId;
2398 }
2399 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2400 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2401 // All pointers up or canceled.
2402 tempTouchState.reset();
2403 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2404 // First pointer went down.
2405 if (oldState && oldState->down) {
2406 if (DEBUG_FOCUS) {
2407 ALOGD("Conflicting pointer actions: Down received while already down.");
2408 }
2409 *outConflictingPointerActions = true;
2410 }
2411 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2412 // One pointer went up.
2413 if (isSplit) {
2414 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2415 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002417 for (size_t i = 0; i < tempTouchState.windows.size();) {
2418 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2419 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2420 touchedWindow.pointerIds.clearBit(pointerId);
2421 if (touchedWindow.pointerIds.isEmpty()) {
2422 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2423 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002426 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002428 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002429 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002430
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002431 // Save changes unless the action was scroll in which case the temporary touch
2432 // state was only valid for this one action.
2433 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2434 if (tempTouchState.displayId >= 0) {
2435 mTouchStatesByDisplay[displayId] = tempTouchState;
2436 } else {
2437 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002441 // Update hover state.
2442 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
2444
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 return injectionResult;
2446}
2447
arthurhung6d4bed92021-03-17 11:59:33 +08002448void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
chaviw98318de2021-05-19 16:45:23 -05002449 const sp<WindowInfoHandle> dropWindow =
arthurhung6d4bed92021-03-17 11:59:33 +08002450 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002451 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002452 if (dropWindow) {
2453 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002454 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002455 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002456 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002457 }
2458 mDragState.reset();
2459}
2460
2461void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2462 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002463 return;
2464 }
2465
arthurhung6d4bed92021-03-17 11:59:33 +08002466 if (!mDragState->isStartDrag) {
2467 mDragState->isStartDrag = true;
2468 mDragState->isStylusButtonDownAtStart =
2469 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2470 }
2471
arthurhungb89ccb02020-12-30 16:19:01 +08002472 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2473 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2474 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2475 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002476 // Handle the special case : stylus button no longer pressed.
2477 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2478 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2479 finishDragAndDrop(entry.displayId, x, y);
2480 return;
2481 }
2482
chaviw98318de2021-05-19 16:45:23 -05002483 const sp<WindowInfoHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002484 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002485 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002486 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002487 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2488 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2489 if (mDragState->dragHoverWindowHandle != nullptr) {
2490 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2491 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002492 }
arthurhung6d4bed92021-03-17 11:59:33 +08002493 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002494 }
2495 // enqueue drag location if needed.
2496 if (hoverWindowHandle != nullptr) {
2497 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2498 }
arthurhung6d4bed92021-03-17 11:59:33 +08002499 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2500 finishDragAndDrop(entry.displayId, x, y);
2501 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002502 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002503 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002504 }
2505}
2506
chaviw98318de2021-05-19 16:45:23 -05002507void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 int32_t targetFlags, BitSet32 pointerIds,
2509 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002510 std::vector<InputTarget>::iterator it =
2511 std::find_if(inputTargets.begin(), inputTargets.end(),
2512 [&windowHandle](const InputTarget& inputTarget) {
2513 return inputTarget.inputChannel->getConnectionToken() ==
2514 windowHandle->getToken();
2515 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002516
chaviw98318de2021-05-19 16:45:23 -05002517 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002518
2519 if (it == inputTargets.end()) {
2520 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002521 std::shared_ptr<InputChannel> inputChannel =
2522 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002523 if (inputChannel == nullptr) {
2524 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2525 return;
2526 }
2527 inputTarget.inputChannel = inputChannel;
2528 inputTarget.flags = targetFlags;
2529 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002530 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2531 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002532 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002533 } else {
2534 ALOGI_IF(isPerWindowInputRotationEnabled(),
2535 "DisplayInfo not found for window on display: %d", windowInfo->displayId);
2536 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002537 inputTargets.push_back(inputTarget);
2538 it = inputTargets.end() - 1;
2539 }
2540
2541 ALOG_ASSERT(it->flags == targetFlags);
2542 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2543
chaviw1ff3d1e2020-07-01 15:53:47 -07002544 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545}
2546
Michael Wright3dd60e22019-03-27 22:06:44 +00002547void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002548 int32_t displayId) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002549 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2550 mGlobalMonitorsByDisplay.find(displayId);
2551
2552 if (it != mGlobalMonitorsByDisplay.end()) {
2553 const std::vector<Monitor>& monitors = it->second;
2554 for (const Monitor& monitor : monitors) {
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002555 addMonitoringTargetLocked(monitor, displayId, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558}
2559
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002560void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, int32_t displayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002562 InputTarget target;
2563 target.inputChannel = monitor.inputChannel;
2564 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002565 ui::Transform t;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002566 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
Prabir Pradhanb5402b22021-10-04 05:52:50 -07002567 const auto& displayTransform = it->second.transform;
2568 target.displayTransform = displayTransform;
2569 t = displayTransform;
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002570 }
chaviw1ff3d1e2020-07-01 15:53:47 -07002571 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002572 inputTargets.push_back(target);
2573}
2574
chaviw98318de2021-05-19 16:45:23 -05002575bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 const InjectionState* injectionState) {
2577 if (injectionState &&
2578 (windowHandle == nullptr ||
2579 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2580 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002581 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 "owned by uid %d",
2584 injectionState->injectorPid, injectionState->injectorUid,
2585 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 } else {
2587 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590 return false;
2591 }
2592 return true;
2593}
2594
Robert Carrc9bf1d32020-04-13 17:21:08 -07002595/**
2596 * Indicate whether one window handle should be considered as obscuring
2597 * another window handle. We only check a few preconditions. Actually
2598 * checking the bounds is left to the caller.
2599 */
chaviw98318de2021-05-19 16:45:23 -05002600static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2601 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002602 // Compare by token so cloned layers aren't counted
2603 if (haveSameToken(windowHandle, otherHandle)) {
2604 return false;
2605 }
2606 auto info = windowHandle->getInfo();
2607 auto otherInfo = otherHandle->getInfo();
2608 if (!otherInfo->visible) {
2609 return false;
chaviw98318de2021-05-19 16:45:23 -05002610 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002611 // Those act as if they were invisible, so we don't need to flag them.
2612 // We do want to potentially flag touchable windows even if they have 0
2613 // opacity, since they can consume touches and alter the effects of the
2614 // user interaction (eg. apps that rely on
2615 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2616 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2617 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002618 } else if (info->ownerUid == otherInfo->ownerUid) {
2619 // If ownerUid is the same we don't generate occlusion events as there
2620 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002621 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002622 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002623 return false;
2624 } else if (otherInfo->displayId != info->displayId) {
2625 return false;
2626 }
2627 return true;
2628}
2629
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002630/**
2631 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2632 * untrusted, one should check:
2633 *
2634 * 1. If result.hasBlockingOcclusion is true.
2635 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2636 * BLOCK_UNTRUSTED.
2637 *
2638 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2639 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2640 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2641 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2642 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2643 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2644 *
2645 * If neither of those is true, then it means the touch can be allowed.
2646 */
2647InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002648 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2649 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002650 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002651 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002652 TouchOcclusionInfo info;
2653 info.hasBlockingOcclusion = false;
2654 info.obscuringOpacity = 0;
2655 info.obscuringUid = -1;
2656 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002657 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002658 if (windowHandle == otherHandle) {
2659 break; // All future windows are below us. Exit early.
2660 }
chaviw98318de2021-05-19 16:45:23 -05002661 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002662 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2663 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002664 if (DEBUG_TOUCH_OCCLUSION) {
2665 info.debugInfo.push_back(
2666 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2667 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002668 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2669 // we perform the checks below to see if the touch can be propagated or not based on the
2670 // window's touch occlusion mode
2671 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2672 info.hasBlockingOcclusion = true;
2673 info.obscuringUid = otherInfo->ownerUid;
2674 info.obscuringPackage = otherInfo->packageName;
2675 break;
2676 }
2677 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2678 uint32_t uid = otherInfo->ownerUid;
2679 float opacity =
2680 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2681 // Given windows A and B:
2682 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2683 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2684 opacityByUid[uid] = opacity;
2685 if (opacity > info.obscuringOpacity) {
2686 info.obscuringOpacity = opacity;
2687 info.obscuringUid = uid;
2688 info.obscuringPackage = otherInfo->packageName;
2689 }
2690 }
2691 }
2692 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002693 if (DEBUG_TOUCH_OCCLUSION) {
2694 info.debugInfo.push_back(
2695 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2696 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002697 return info;
2698}
2699
chaviw98318de2021-05-19 16:45:23 -05002700std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002701 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002702 return StringPrintf(INDENT2
2703 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2704 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2705 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2706 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Dominik Laskowski75788452021-02-09 18:51:25 -08002707 isTouchedWindow ? "[TOUCHED] " : "", ftl::enum_string(info->type).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002708 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002709 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2710 info->frameTop, info->frameRight, info->frameBottom,
2711 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002712 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2713 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2714 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002715}
2716
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002717bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2718 if (occlusionInfo.hasBlockingOcclusion) {
2719 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2720 occlusionInfo.obscuringUid);
2721 return false;
2722 }
2723 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2724 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2725 "%.2f, maximum allowed = %.2f)",
2726 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2727 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2728 return false;
2729 }
2730 return true;
2731}
2732
chaviw98318de2021-05-19 16:45:23 -05002733bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002734 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002736 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2737 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002738 if (windowHandle == otherHandle) {
2739 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 }
chaviw98318de2021-05-19 16:45:23 -05002741 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002742 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002743 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 return true;
2745 }
2746 }
2747 return false;
2748}
2749
chaviw98318de2021-05-19 16:45:23 -05002750bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002751 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002752 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2753 const WindowInfo* windowInfo = windowHandle->getInfo();
2754 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002755 if (windowHandle == otherHandle) {
2756 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002757 }
chaviw98318de2021-05-19 16:45:23 -05002758 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002759 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002760 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002761 return true;
2762 }
2763 }
2764 return false;
2765}
2766
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002767std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002768 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002769 if (applicationHandle != nullptr) {
2770 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002771 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 } else {
2773 return applicationHandle->getName();
2774 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002775 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002776 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002778 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
2780}
2781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002782void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002783 if (!isUserActivityEvent(eventEntry)) {
2784 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002785 return;
2786 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002787 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002788 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002789 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002790 const WindowInfo* info = focusedWindowHandle->getInfo();
2791 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002792 if (DEBUG_DISPATCH_CYCLE) {
2793 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 return;
2796 }
2797 }
2798
2799 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002800 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002801 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002802 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2803 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 return;
2805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002807 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 eventType = USER_ACTIVITY_EVENT_TOUCH;
2809 }
2810 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002812 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002813 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2814 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 return;
2816 }
2817 eventType = USER_ACTIVITY_EVENT_BUTTON;
2818 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002820 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002821 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002822 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002823 break;
2824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
2826
Prabir Pradhancef936d2021-07-21 16:17:52 +00002827 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2828 REQUIRES(mLock) {
2829 scoped_unlock unlock(mLock);
2830 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2831 };
2832 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833}
2834
2835void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002837 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002838 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002839 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002841 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002842 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002843 ATRACE_NAME(message.c_str());
2844 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002845 if (DEBUG_DISPATCH_CYCLE) {
2846 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2847 "globalScaleFactor=%f, pointerIds=0x%x %s",
2848 connection->getInputChannelName().c_str(), inputTarget.flags,
2849 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2850 inputTarget.getPointerInfoString().c_str());
2851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852
2853 // Skip this event if the connection status is not normal.
2854 // We don't want to enqueue additional outbound events if the connection is broken.
2855 if (connection->status != Connection::STATUS_NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002856 if (DEBUG_DISPATCH_CYCLE) {
2857 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2858 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 return;
2861 }
2862
2863 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002864 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2865 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2866 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002867 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002869 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002870 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002871 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002872 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 if (!splitMotionEntry) {
2874 return; // split event was dropped
2875 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002876 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2877 std::string reason = std::string("reason=pointer cancel on split window");
2878 android_log_event_list(LOGTAG_INPUT_CANCEL)
2879 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2880 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002881 if (DEBUG_FOCUS) {
2882 ALOGD("channel '%s' ~ Split motion event.",
2883 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002885 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002886 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2887 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 return;
2889 }
2890 }
2891
2892 // Not splitting. Enqueue dispatch entries for the event as is.
2893 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2894}
2895
2896void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002898 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002899 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002900 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002902 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002903 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002904 ATRACE_NAME(message.c_str());
2905 }
2906
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002907 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
2909 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002910 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002912 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002914 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002916 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002918 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002920 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
2923 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002924 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 startDispatchCycleLocked(currentTime, connection);
2926 }
2927}
2928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002931 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002933 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2935 connection->getInputChannelName().c_str(),
2936 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002937 ATRACE_NAME(message.c_str());
2938 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002939 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 if (!(inputTargetFlags & dispatchMode)) {
2941 return;
2942 }
2943 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2944
2945 // This is a new event.
2946 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002947 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002948 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002950 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2951 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002955 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002956 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002957 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 dispatchEntry->resolvedAction = keyEntry.action;
2959 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2962 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002963 if (DEBUG_DISPATCH_CYCLE) {
2964 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2965 "event",
2966 connection->getInputChannelName().c_str());
2967 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 return; // skip the inconsistent event
2969 }
2970 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002973 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002974 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002975 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2976 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2977 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2978 static_cast<int32_t>(IdGenerator::Source::OTHER);
2979 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2981 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2982 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2984 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2985 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2986 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2987 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2988 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2989 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2990 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002991 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002992 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 }
2994 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2996 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002997 if (DEBUG_DISPATCH_CYCLE) {
2998 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
2999 "enter event",
3000 connection->getInputChannelName().c_str());
3001 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003002 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3003 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003007 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3009 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3010 }
3011 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3012 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3016 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003017 if (DEBUG_DISPATCH_CYCLE) {
3018 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3019 "event",
3020 connection->getInputChannelName().c_str());
3021 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003022 return; // skip the inconsistent event
3023 }
3024
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003025 dispatchEntry->resolvedEventId =
3026 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3027 ? mIdGenerator.nextId()
3028 : motionEntry.id;
3029 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3030 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3031 ") to MotionEvent(id=0x%" PRIx32 ").",
3032 motionEntry.id, dispatchEntry->resolvedEventId);
3033 ATRACE_NAME(message.c_str());
3034 }
3035
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003036 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3037 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3038 // Skip reporting pointer down outside focus to the policy.
3039 break;
3040 }
3041
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003043 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044
3045 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003047 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003048 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003049 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3050 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003051 break;
3052 }
Chris Yef59a2f42020-10-16 12:55:26 -07003053 case EventEntry::Type::SENSOR: {
3054 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3055 break;
3056 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003057 case EventEntry::Type::CONFIGURATION_CHANGED:
3058 case EventEntry::Type::DEVICE_RESET: {
3059 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003060 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003061 break;
3062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 }
3064
3065 // Remember that we are waiting for this dispatch to complete.
3066 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003067 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069
3070 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003071 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003072 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003073}
3074
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003075/**
3076 * This function is purely for debugging. It helps us understand where the user interaction
3077 * was taking place. For example, if user is touching launcher, we will see a log that user
3078 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3079 * We will see both launcher and wallpaper in that list.
3080 * Once the interaction with a particular set of connections starts, no new logs will be printed
3081 * until the set of interacted connections changes.
3082 *
3083 * The following items are skipped, to reduce the logspam:
3084 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3085 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3086 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3087 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3088 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003089 */
3090void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3091 const std::vector<InputTarget>& targets) {
3092 // Skip ACTION_UP events, and all events other than keys and motions
3093 if (entry.type == EventEntry::Type::KEY) {
3094 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3095 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3096 return;
3097 }
3098 } else if (entry.type == EventEntry::Type::MOTION) {
3099 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3100 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3101 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3102 return;
3103 }
3104 } else {
3105 return; // Not a key or a motion
3106 }
3107
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003108 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003109 std::vector<sp<Connection>> newConnections;
3110 for (const InputTarget& target : targets) {
3111 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3112 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3113 continue; // Skip windows that receive ACTION_OUTSIDE
3114 }
3115
3116 sp<IBinder> token = target.inputChannel->getConnectionToken();
3117 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003118 if (connection == nullptr) {
3119 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003120 }
3121 newConnectionTokens.insert(std::move(token));
3122 newConnections.emplace_back(connection);
3123 }
3124 if (newConnectionTokens == mInteractionConnectionTokens) {
3125 return; // no change
3126 }
3127 mInteractionConnectionTokens = newConnectionTokens;
3128
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003129 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003130 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003131 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003132 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003133 std::string message = "Interaction with: " + targetList;
3134 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003135 message += "<none>";
3136 }
3137 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3138}
3139
chaviwfd6d3512019-03-25 13:23:49 -07003140void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003141 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003142 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003143 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3144 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003145 return;
3146 }
3147
Vishnu Nairc519ff72021-01-21 08:23:08 -08003148 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003149 if (focusedToken == token) {
3150 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003151 return;
3152 }
3153
Prabir Pradhancef936d2021-07-21 16:17:52 +00003154 auto command = [this, token]() REQUIRES(mLock) {
3155 scoped_unlock unlock(mLock);
3156 mPolicy->onPointerDownOutsideFocus(token);
3157 };
3158 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159}
3160
3161void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003163 if (ATRACE_ENABLED()) {
3164 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003166 ATRACE_NAME(message.c_str());
3167 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003168 if (DEBUG_DISPATCH_CYCLE) {
3169 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003172 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3173 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003175 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003176 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003177 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
3179 // Publish the event.
3180 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003183 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003184 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3185 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003188 status = connection->inputPublisher
3189 .publishKeyEvent(dispatchEntry->seq,
3190 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3191 keyEntry.source, keyEntry.displayId,
3192 std::move(hmac), dispatchEntry->resolvedAction,
3193 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3194 keyEntry.scanCode, keyEntry.metaState,
3195 keyEntry.repeatCount, keyEntry.downTime,
3196 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003200 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003201 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003204 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205
chaviw82357092020-01-28 13:13:06 -08003206 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003207 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3209 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003210 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003211 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3212 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003213 // Don't apply window scale here since we don't want scale to affect raw
3214 // coordinates. The scale will be sent back to the client and applied
3215 // later when requesting relative coordinates.
3216 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3217 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 }
3219 usingCoords = scaledCoords;
3220 }
3221 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 // We don't want the dispatch target to know.
3223 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003224 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 scaledCoords[i].clear();
3226 }
3227 usingCoords = scaledCoords;
3228 }
3229 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003231 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232
3233 // Publish the motion event.
3234 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003235 .publishMotionEvent(dispatchEntry->seq,
3236 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003237 motionEntry.deviceId, motionEntry.source,
3238 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003239 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003240 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003242 motionEntry.edgeFlags, motionEntry.metaState,
3243 motionEntry.buttonState,
3244 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003245 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003246 motionEntry.xPrecision, motionEntry.yPrecision,
3247 motionEntry.xCursorPosition,
3248 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003249 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 motionEntry.downTime, motionEntry.eventTime,
3251 motionEntry.pointerCount,
3252 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 break;
3254 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003255
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003256 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003258 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003259 focusEntry.id,
3260 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003261 mInTouchMode);
3262 break;
3263 }
3264
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003265 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3266 const TouchModeEntry& touchModeEntry =
3267 static_cast<const TouchModeEntry&>(eventEntry);
3268 status = connection->inputPublisher
3269 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3270 touchModeEntry.inTouchMode);
3271
3272 break;
3273 }
3274
Prabir Pradhan99987712020-11-10 18:43:05 -08003275 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3276 const auto& captureEntry =
3277 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3278 status = connection->inputPublisher
3279 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003280 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003281 break;
3282 }
3283
arthurhungb89ccb02020-12-30 16:19:01 +08003284 case EventEntry::Type::DRAG: {
3285 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3286 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3287 dragEntry.id, dragEntry.x,
3288 dragEntry.y,
3289 dragEntry.isExiting);
3290 break;
3291 }
3292
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003293 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003294 case EventEntry::Type::DEVICE_RESET:
3295 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003296 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003297 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 }
3301
3302 // Check the result.
3303 if (status) {
3304 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003305 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 "This is unexpected because the wait queue is empty, so the pipe "
3308 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003309 "event to it, status=%s(%d)",
3310 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3311 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3313 } else {
3314 // Pipe is full and we are waiting for the app to finish process some events
3315 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003316 if (DEBUG_DISPATCH_CYCLE) {
3317 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3318 "waiting for the application to catch up",
3319 connection->getInputChannelName().c_str());
3320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
3322 } else {
3323 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003324 "status=%s(%d)",
3325 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3326 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3328 }
3329 return;
3330 }
3331
3332 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3334 connection->outboundQueue.end(),
3335 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003336 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003337 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003338 if (connection->responsive) {
3339 mAnrTracker.insert(dispatchEntry->timeoutTime,
3340 connection->inputChannel->getConnectionToken());
3341 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003342 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
3344}
3345
chaviw09c8d2d2020-08-24 15:48:26 -07003346std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3347 size_t size;
3348 switch (event.type) {
3349 case VerifiedInputEvent::Type::KEY: {
3350 size = sizeof(VerifiedKeyEvent);
3351 break;
3352 }
3353 case VerifiedInputEvent::Type::MOTION: {
3354 size = sizeof(VerifiedMotionEvent);
3355 break;
3356 }
3357 }
3358 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3359 return mHmacKeyManager.sign(start, size);
3360}
3361
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003362const std::array<uint8_t, 32> InputDispatcher::getSignature(
3363 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003364 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3365 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003366 // Only sign events up and down events as the purely move events
3367 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003368 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003369 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003370
3371 VerifiedMotionEvent verifiedEvent =
3372 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3373 verifiedEvent.actionMasked = actionMasked;
3374 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3375 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003376}
3377
3378const std::array<uint8_t, 32> InputDispatcher::getSignature(
3379 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3380 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3381 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3382 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003383 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003384}
3385
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003388 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003389 if (DEBUG_DISPATCH_CYCLE) {
3390 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3391 connection->getInputChannelName().c_str(), seq, toString(handled));
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394 if (connection->status == Connection::STATUS_BROKEN ||
3395 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 return;
3397 }
3398
3399 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003400 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3401 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3402 };
3403 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404}
3405
3406void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 const sp<Connection>& connection,
3408 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003409 if (DEBUG_DISPATCH_CYCLE) {
3410 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3411 connection->getInputChannelName().c_str(), toString(notify));
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
3414 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003417 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003418 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
3420 // The connection appears to be unrecoverably broken.
3421 // Ignore already broken or zombie connections.
3422 if (connection->status == Connection::STATUS_NORMAL) {
3423 connection->status = Connection::STATUS_BROKEN;
3424
3425 if (notify) {
3426 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003427 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3428 connection->getInputChannelName().c_str());
3429
3430 auto command = [this, connection]() REQUIRES(mLock) {
3431 if (connection->status == Connection::STATUS_ZOMBIE) return;
3432 scoped_unlock unlock(mLock);
3433 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3434 };
3435 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 }
3437 }
3438}
3439
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003440void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3441 while (!queue.empty()) {
3442 DispatchEntry* dispatchEntry = queue.front();
3443 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003444 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 }
3446}
3447
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003448void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003450 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452 delete dispatchEntry;
3453}
3454
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003455int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3456 std::scoped_lock _l(mLock);
3457 sp<Connection> connection = getConnectionLocked(connectionToken);
3458 if (connection == nullptr) {
3459 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3460 connectionToken.get(), events);
3461 return 0; // remove the callback
3462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003464 bool notify;
3465 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3466 if (!(events & ALOOPER_EVENT_INPUT)) {
3467 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3468 "events=0x%x",
3469 connection->getInputChannelName().c_str(), events);
3470 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003473 nsecs_t currentTime = now();
3474 bool gotOne = false;
3475 status_t status = OK;
3476 for (;;) {
3477 Result<InputPublisher::ConsumerResponse> result =
3478 connection->inputPublisher.receiveConsumerResponse();
3479 if (!result.ok()) {
3480 status = result.error().code();
3481 break;
3482 }
3483
3484 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3485 const InputPublisher::Finished& finish =
3486 std::get<InputPublisher::Finished>(*result);
3487 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3488 finish.consumeTime);
3489 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003490 if (shouldReportMetricsForConnection(*connection)) {
3491 const InputPublisher::Timeline& timeline =
3492 std::get<InputPublisher::Timeline>(*result);
3493 mLatencyTracker
3494 .trackGraphicsLatency(timeline.inputEventId,
3495 connection->inputChannel->getConnectionToken(),
3496 std::move(timeline.graphicsTimeline));
3497 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003498 }
3499 gotOne = true;
3500 }
3501 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003502 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003503 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 return 1;
3505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
3507
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003508 notify = status != DEAD_OBJECT || !connection->monitor;
3509 if (notify) {
3510 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3511 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3512 status);
3513 }
3514 } else {
3515 // Monitor channels are never explicitly unregistered.
3516 // We do it automatically when the remote endpoint is closed so don't warn about them.
3517 const bool stillHaveWindowHandle =
3518 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3519 notify = !connection->monitor && stillHaveWindowHandle;
3520 if (notify) {
3521 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3522 connection->getInputChannelName().c_str(), events);
3523 }
3524 }
3525
3526 // Remove the channel.
3527 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3528 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529}
3530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003531void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003533 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003534 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536}
3537
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003538void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003539 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003540 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3541 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3542}
3543
3544void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3545 const CancelationOptions& options,
3546 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3547 for (const auto& it : monitorsByDisplay) {
3548 const std::vector<Monitor>& monitors = it.second;
3549 for (const Monitor& monitor : monitors) {
3550 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003551 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003552 }
3553}
3554
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003556 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003557 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003558 if (connection == nullptr) {
3559 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003561
3562 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563}
3564
3565void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3566 const sp<Connection>& connection, const CancelationOptions& options) {
3567 if (connection->status == Connection::STATUS_BROKEN) {
3568 return;
3569 }
3570
3571 nsecs_t currentTime = now();
3572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003573 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003574 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003576 if (cancelationEvents.empty()) {
3577 return;
3578 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003579 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3580 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3581 "with reality: %s, mode=%d.",
3582 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3583 options.mode);
3584 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003585
Arthur Hungb3307ee2021-10-14 10:57:37 +00003586 std::string reason = std::string("reason=").append(options.reason);
3587 android_log_event_list(LOGTAG_INPUT_CANCEL)
3588 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3589
Svet Ganov5d3bc372020-01-26 23:11:07 -08003590 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003591 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003592 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3593 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003594 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003595 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003596 target.globalScaleFactor = windowInfo->globalScaleFactor;
3597 }
3598 target.inputChannel = connection->inputChannel;
3599 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3600
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003601 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003602 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003603 switch (cancelationEventEntry->type) {
3604 case EventEntry::Type::KEY: {
3605 logOutboundKeyDetails("cancel - ",
3606 static_cast<const KeyEntry&>(*cancelationEventEntry));
3607 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003609 case EventEntry::Type::MOTION: {
3610 logOutboundMotionDetails("cancel - ",
3611 static_cast<const MotionEntry&>(*cancelationEventEntry));
3612 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003614 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003615 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003616 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3617 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003618 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003619 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003620 break;
3621 }
3622 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003623 case EventEntry::Type::DEVICE_RESET:
3624 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003625 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003626 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003627 break;
3628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
3630
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003631 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3632 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003634
3635 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636}
3637
Svet Ganov5d3bc372020-01-26 23:11:07 -08003638void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3639 const sp<Connection>& connection) {
3640 if (connection->status == Connection::STATUS_BROKEN) {
3641 return;
3642 }
3643
3644 nsecs_t currentTime = now();
3645
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003646 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003647 connection->inputState.synthesizePointerDownEvents(currentTime);
3648
3649 if (downEvents.empty()) {
3650 return;
3651 }
3652
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003653 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3655 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003656 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003657
3658 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003659 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003660 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3661 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003662 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003663 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664 target.globalScaleFactor = windowInfo->globalScaleFactor;
3665 }
3666 target.inputChannel = connection->inputChannel;
3667 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3668
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003669 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 switch (downEventEntry->type) {
3671 case EventEntry::Type::MOTION: {
3672 logOutboundMotionDetails("down - ",
3673 static_cast<const MotionEntry&>(*downEventEntry));
3674 break;
3675 }
3676
3677 case EventEntry::Type::KEY:
3678 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003679 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003680 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003681 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003682 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003683 case EventEntry::Type::SENSOR:
3684 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003685 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003686 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003687 break;
3688 }
3689 }
3690
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003691 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3692 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003693 }
3694
3695 startDispatchCycleLocked(currentTime, connection);
3696}
3697
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003698std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3699 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 ALOG_ASSERT(pointerIds.value != 0);
3701
3702 uint32_t splitPointerIndexMap[MAX_POINTERS];
3703 PointerProperties splitPointerProperties[MAX_POINTERS];
3704 PointerCoords splitPointerCoords[MAX_POINTERS];
3705
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003706 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 uint32_t splitPointerCount = 0;
3708
3709 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003710 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003712 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 uint32_t pointerId = uint32_t(pointerProperties.id);
3714 if (pointerIds.hasBit(pointerId)) {
3715 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3716 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3717 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003718 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 splitPointerCount += 1;
3720 }
3721 }
3722
3723 if (splitPointerCount != pointerIds.count()) {
3724 // This is bad. We are missing some of the pointers that we expected to deliver.
3725 // Most likely this indicates that we received an ACTION_MOVE events that has
3726 // different pointer ids than we expected based on the previous ACTION_DOWN
3727 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3728 // in this way.
3729 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003730 "we expected there to be %d pointers. This probably means we received "
3731 "a broken sequence of pointer ids from the input device.",
3732 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003733 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 }
3735
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003736 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003738 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3739 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3741 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003742 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 uint32_t pointerId = uint32_t(pointerProperties.id);
3744 if (pointerIds.hasBit(pointerId)) {
3745 if (pointerIds.count() == 1) {
3746 // The first/last pointer went down/up.
3747 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003748 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003749 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3750 ? AMOTION_EVENT_ACTION_CANCEL
3751 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 } else {
3753 // A secondary pointer went down/up.
3754 uint32_t splitPointerIndex = 0;
3755 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3756 splitPointerIndex += 1;
3757 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003758 action = maskedAction |
3759 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761 } else {
3762 // An unrelated pointer changed.
3763 action = AMOTION_EVENT_ACTION_MOVE;
3764 }
3765 }
3766
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003767 int32_t newId = mIdGenerator.nextId();
3768 if (ATRACE_ENABLED()) {
3769 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3770 ") to MotionEvent(id=0x%" PRIx32 ").",
3771 originalMotionEntry.id, newId);
3772 ATRACE_NAME(message.c_str());
3773 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003774 std::unique_ptr<MotionEntry> splitMotionEntry =
3775 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3776 originalMotionEntry.deviceId, originalMotionEntry.source,
3777 originalMotionEntry.displayId,
3778 originalMotionEntry.policyFlags, action,
3779 originalMotionEntry.actionButton,
3780 originalMotionEntry.flags, originalMotionEntry.metaState,
3781 originalMotionEntry.buttonState,
3782 originalMotionEntry.classification,
3783 originalMotionEntry.edgeFlags,
3784 originalMotionEntry.xPrecision,
3785 originalMotionEntry.yPrecision,
3786 originalMotionEntry.xCursorPosition,
3787 originalMotionEntry.yCursorPosition,
3788 originalMotionEntry.downTime, splitPointerCount,
3789 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003791 if (originalMotionEntry.injectionState) {
3792 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 splitMotionEntry->injectionState->refCount += 1;
3794 }
3795
3796 return splitMotionEntry;
3797}
3798
3799void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003800 if (DEBUG_INBOUND_EVENT_DETAILS) {
3801 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
Antonio Kantekf16f2832021-09-28 04:39:20 +00003804 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003806 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003808 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3809 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3810 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 } // release lock
3812
3813 if (needWake) {
3814 mLooper->wake();
3815 }
3816}
3817
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003818/**
3819 * If one of the meta shortcuts is detected, process them here:
3820 * Meta + Backspace -> generate BACK
3821 * Meta + Enter -> generate HOME
3822 * This will potentially overwrite keyCode and metaState.
3823 */
3824void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003826 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3827 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3828 if (keyCode == AKEYCODE_DEL) {
3829 newKeyCode = AKEYCODE_BACK;
3830 } else if (keyCode == AKEYCODE_ENTER) {
3831 newKeyCode = AKEYCODE_HOME;
3832 }
3833 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003834 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003835 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003836 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003837 keyCode = newKeyCode;
3838 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3839 }
3840 } else if (action == AKEY_EVENT_ACTION_UP) {
3841 // In order to maintain a consistent stream of up and down events, check to see if the key
3842 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3843 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003844 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003845 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003846 auto replacementIt = mReplacedKeys.find(replacement);
3847 if (replacementIt != mReplacedKeys.end()) {
3848 keyCode = replacementIt->second;
3849 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003850 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3851 }
3852 }
3853}
3854
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003856 if (DEBUG_INBOUND_EVENT_DETAILS) {
3857 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3858 "policyFlags=0x%x, action=0x%x, "
3859 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3860 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3861 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3862 args->downTime);
3863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 if (!validateKeyEvent(args->action)) {
3865 return;
3866 }
3867
3868 uint32_t policyFlags = args->policyFlags;
3869 int32_t flags = args->flags;
3870 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003871 // InputDispatcher tracks and generates key repeats on behalf of
3872 // whatever notifies it, so repeatCount should always be set to 0
3873 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3875 policyFlags |= POLICY_FLAG_VIRTUAL;
3876 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 if (policyFlags & POLICY_FLAG_FUNCTION) {
3879 metaState |= AMETA_FUNCTION_ON;
3880 }
3881
3882 policyFlags |= POLICY_FLAG_TRUSTED;
3883
Michael Wright78f24442014-08-06 15:55:28 -07003884 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003885 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003886
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003888 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003889 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3890 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Michael Wright2b3c3302018-03-02 17:19:13 +00003892 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003894 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3895 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
Antonio Kantekf16f2832021-09-28 04:39:20 +00003899 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 { // acquire lock
3901 mLock.lock();
3902
3903 if (shouldSendKeyToInputFilterLocked(args)) {
3904 mLock.unlock();
3905
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003906 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3908 return; // event was consumed by the filter
3909 }
3910
3911 mLock.lock();
3912 }
3913
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003914 std::unique_ptr<KeyEntry> newEntry =
3915 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3916 args->displayId, policyFlags, args->action, flags,
3917 keyCode, args->scanCode, metaState, repeatCount,
3918 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003920 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 mLock.unlock();
3922 } // release lock
3923
3924 if (needWake) {
3925 mLooper->wake();
3926 }
3927}
3928
3929bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3930 return mInputFilterEnabled;
3931}
3932
3933void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003934 if (DEBUG_INBOUND_EVENT_DETAILS) {
3935 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3936 "displayId=%" PRId32 ", policyFlags=0x%x, "
3937 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3938 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3939 "yCursorPosition=%f, downTime=%" PRId64,
3940 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3941 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3942 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3943 args->xCursorPosition, args->yCursorPosition, args->downTime);
3944 for (uint32_t i = 0; i < args->pointerCount; i++) {
3945 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3946 "x=%f, y=%f, pressure=%f, size=%f, "
3947 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3948 "orientation=%f",
3949 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3950 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3951 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3952 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3953 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3954 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3955 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3956 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3957 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3958 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3962 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 return;
3964 }
3965
3966 uint32_t policyFlags = args->policyFlags;
3967 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003968
3969 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003970 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003971 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3972 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Antonio Kantekf16f2832021-09-28 04:39:20 +00003976 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 { // acquire lock
3978 mLock.lock();
3979
3980 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003981 ui::Transform displayTransform;
3982 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3983 displayTransform = it->second.transform;
3984 }
3985
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 mLock.unlock();
3987
3988 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003989 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3990 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003991 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003992 displayTransform, args->xPrecision, args->yPrecision,
3993 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003994 args->downTime, args->eventTime, args->pointerCount,
3995 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996
3997 policyFlags |= POLICY_FLAG_FILTERED;
3998 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3999 return; // event was consumed by the filter
4000 }
4001
4002 mLock.lock();
4003 }
4004
4005 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004006 std::unique_ptr<MotionEntry> newEntry =
4007 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4008 args->source, args->displayId, policyFlags,
4009 args->action, args->actionButton, args->flags,
4010 args->metaState, args->buttonState,
4011 args->classification, args->edgeFlags,
4012 args->xPrecision, args->yPrecision,
4013 args->xCursorPosition, args->yCursorPosition,
4014 args->downTime, args->pointerCount,
4015 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004017 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4018 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4019 !mInputFilterEnabled) {
4020 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4021 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4022 }
4023
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004024 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 mLock.unlock();
4026 } // release lock
4027
4028 if (needWake) {
4029 mLooper->wake();
4030 }
4031}
4032
Chris Yef59a2f42020-10-16 12:55:26 -07004033void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 if (DEBUG_INBOUND_EVENT_DETAILS) {
4035 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4036 " sensorType=%s",
4037 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004038 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 }
Chris Yef59a2f42020-10-16 12:55:26 -07004040
Antonio Kantekf16f2832021-09-28 04:39:20 +00004041 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004042 { // acquire lock
4043 mLock.lock();
4044
4045 // Just enqueue a new sensor event.
4046 std::unique_ptr<SensorEntry> newEntry =
4047 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4048 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4049 args->sensorType, args->accuracy,
4050 args->accuracyChanged, args->values);
4051
4052 needWake = enqueueInboundEventLocked(std::move(newEntry));
4053 mLock.unlock();
4054 } // release lock
4055
4056 if (needWake) {
4057 mLooper->wake();
4058 }
4059}
4060
Chris Yefb552902021-02-03 17:18:37 -08004061void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004062 if (DEBUG_INBOUND_EVENT_DETAILS) {
4063 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4064 args->deviceId, args->isOn);
4065 }
Chris Yefb552902021-02-03 17:18:37 -08004066 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4067}
4068
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004070 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071}
4072
4073void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004074 if (DEBUG_INBOUND_EVENT_DETAILS) {
4075 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4076 "switchMask=0x%08x",
4077 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
4080 uint32_t policyFlags = args->policyFlags;
4081 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083}
4084
4085void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 if (DEBUG_INBOUND_EVENT_DETAILS) {
4087 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4088 args->deviceId);
4089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090
Antonio Kantekf16f2832021-09-28 04:39:20 +00004091 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004093 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004095 std::unique_ptr<DeviceResetEntry> newEntry =
4096 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4097 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 } // release lock
4099
4100 if (needWake) {
4101 mLooper->wake();
4102 }
4103}
4104
Prabir Pradhan7e186182020-11-10 13:56:45 -08004105void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004106 if (DEBUG_INBOUND_EVENT_DETAILS) {
4107 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004108 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004109 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004110
Antonio Kantekf16f2832021-09-28 04:39:20 +00004111 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004112 { // acquire lock
4113 std::scoped_lock _l(mLock);
4114 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004115 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004116 needWake = enqueueInboundEventLocked(std::move(entry));
4117 } // release lock
4118
4119 if (needWake) {
4120 mLooper->wake();
4121 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004122}
4123
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004124InputEventInjectionResult InputDispatcher::injectInputEvent(
4125 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4126 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004127 if (DEBUG_INBOUND_EVENT_DETAILS) {
4128 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4129 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4130 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4131 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004132 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
4134 policyFlags |= POLICY_FLAG_INJECTED;
4135 if (hasInjectionPermission(injectorPid, injectorUid)) {
4136 policyFlags |= POLICY_FLAG_TRUSTED;
4137 }
4138
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004139 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004140 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4141 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4142 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4143 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4144 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004145 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004146 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004147 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004148 }
4149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004153 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4154 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004159 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004160 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4161 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4162 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004163 int32_t keyCode = incomingKey.getKeyCode();
4164 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004165 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004167 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004168 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004169 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4170 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4171 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4174 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004175 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176
4177 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4178 android::base::Timer t;
4179 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4180 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4181 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4182 std::to_string(t.duration().count()).c_str());
4183 }
4184 }
4185
4186 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004187 std::unique_ptr<KeyEntry> injectedEntry =
4188 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004189 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004190 incomingKey.getDisplayId(), policyFlags, action,
4191 flags, keyCode, incomingKey.getScanCode(), metaState,
4192 incomingKey.getRepeatCount(),
4193 incomingKey.getDownTime());
4194 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 }
4197
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004198 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004200 const int32_t action = motionEvent.getAction();
4201 const bool isPointerEvent =
4202 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4203 // If a pointer event has no displayId specified, inject it to the default display.
4204 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4205 ? ADISPLAY_ID_DEFAULT
4206 : event->getDisplayId();
4207 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004208 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004209 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004210 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004212 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 }
4214
4215 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004216 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 android::base::Timer t;
4218 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4219 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4220 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4221 std::to_string(t.duration().count()).c_str());
4222 }
4223 }
4224
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004225 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4226 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4227 }
4228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4231 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004232 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4234 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004235 displayId, policyFlags, action, actionButton,
4236 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 motionEvent.getButtonState(),
4238 motionEvent.getClassification(),
4239 motionEvent.getEdgeFlags(),
4240 motionEvent.getXPrecision(),
4241 motionEvent.getYPrecision(),
4242 motionEvent.getRawXCursorPosition(),
4243 motionEvent.getRawYCursorPosition(),
4244 motionEvent.getDownTime(), uint32_t(pointerCount),
4245 pointerProperties, samplePointerCoords,
4246 motionEvent.getXOffset(),
4247 motionEvent.getYOffset());
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004248 transformMotionEntryForInjectionLocked(*injectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004249 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004250 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 sampleEventTimes += 1;
4252 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004253 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004254 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4255 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004256 displayId, policyFlags, action, actionButton,
4257 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004258 motionEvent.getButtonState(),
4259 motionEvent.getClassification(),
4260 motionEvent.getEdgeFlags(),
4261 motionEvent.getXPrecision(),
4262 motionEvent.getYPrecision(),
4263 motionEvent.getRawXCursorPosition(),
4264 motionEvent.getRawYCursorPosition(),
4265 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004266 uint32_t(pointerCount), pointerProperties,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004267 samplePointerCoords, motionEvent.getXOffset(),
4268 motionEvent.getYOffset());
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004269 transformMotionEntryForInjectionLocked(*nextInjectedEntry);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004270 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 }
4272 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004275 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004276 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004277 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279
4280 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004281 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 injectionState->injectionIsAsync = true;
4283 }
4284
4285 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004286 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287
4288 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004289 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004290 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004291 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 }
4293
4294 mLock.unlock();
4295
4296 if (needWake) {
4297 mLooper->wake();
4298 }
4299
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004300 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004302 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004304 if (syncMode == InputEventInjectionSync::NONE) {
4305 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 } else {
4307 for (;;) {
4308 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 break;
4311 }
4312
4313 nsecs_t remainingTimeout = endTime - now();
4314 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004315 if (DEBUG_INJECTION) {
4316 ALOGD("injectInputEvent - Timed out waiting for injection result "
4317 "to become available.");
4318 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004319 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 break;
4321 }
4322
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004323 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4327 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004329 if (DEBUG_INJECTION) {
4330 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4331 injectionState->pendingForegroundDispatches);
4332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 nsecs_t remainingTimeout = endTime - now();
4334 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004335 if (DEBUG_INJECTION) {
4336 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4337 "dispatches to finish.");
4338 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004339 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 break;
4341 }
4342
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004343 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 }
4345 }
4346 }
4347
4348 injectionState->release();
4349 } // release lock
4350
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004351 if (DEBUG_INJECTION) {
4352 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4353 injectionResult, injectorPid, injectorUid);
4354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355
4356 return injectionResult;
4357}
4358
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004359std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004360 std::array<uint8_t, 32> calculatedHmac;
4361 std::unique_ptr<VerifiedInputEvent> result;
4362 switch (event.getType()) {
4363 case AINPUT_EVENT_TYPE_KEY: {
4364 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4365 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4366 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004367 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004368 break;
4369 }
4370 case AINPUT_EVENT_TYPE_MOTION: {
4371 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4372 VerifiedMotionEvent verifiedMotionEvent =
4373 verifiedMotionEventFromMotionEvent(motionEvent);
4374 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004375 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004376 break;
4377 }
4378 default: {
4379 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4380 return nullptr;
4381 }
4382 }
4383 if (calculatedHmac == INVALID_HMAC) {
4384 return nullptr;
4385 }
4386 if (calculatedHmac != event.getHmac()) {
4387 return nullptr;
4388 }
4389 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004390}
4391
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 return injectorUid == 0 ||
4394 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395}
4396
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004397void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004398 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004399 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004401 if (DEBUG_INJECTION) {
4402 ALOGD("Setting input event injection result to %d. "
4403 "injectorPid=%d, injectorUid=%d",
4404 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004407 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 // Log the outcome since the injector did not wait for the injection result.
4409 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004410 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 ALOGV("Asynchronous input event injection succeeded.");
4412 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 ALOGW("Asynchronous input event injection failed.");
4415 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 ALOGW("Asynchronous input event injection permission denied.");
4418 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 ALOGW("Asynchronous input event injection timed out.");
4421 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004422 case InputEventInjectionResult::PENDING:
4423 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4424 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 }
4426 }
4427
4428 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004429 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 }
4431}
4432
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004433void InputDispatcher::transformMotionEntryForInjectionLocked(MotionEntry& entry) const {
4434 const bool isRelativeMouseEvent = isFromSource(entry.source, AINPUT_SOURCE_MOUSE_RELATIVE);
4435 if (!isRelativeMouseEvent && !isFromSource(entry.source, AINPUT_SOURCE_CLASS_POINTER)) {
4436 return;
4437 }
4438
4439 // Input injection works in the logical display coordinate space, but the input pipeline works
4440 // display space, so we need to transform the injected events accordingly.
4441 const auto it = mDisplayInfos.find(entry.displayId);
4442 if (it == mDisplayInfos.end()) return;
4443 const auto& transformToDisplay = it->second.transform.inverse();
4444
4445 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4446 PointerCoords& pc = entry.pointerCoords[i];
4447 const auto xy = isRelativeMouseEvent
4448 ? transformWithoutTranslation(transformToDisplay, pc.getX(), pc.getY())
4449 : transformToDisplay.transform(pc.getXYValue());
4450 pc.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
4451 pc.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
4452
4453 // Axes with relative values never represent points on a screen, so they should never have
4454 // translation applied. If a device does not report relative values, these values are always
4455 // 0, and will remain unaffected by the following operation.
4456 const auto rel =
4457 transformWithoutTranslation(transformToDisplay,
4458 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
4459 pc.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4460 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, rel.x);
4461 pc.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, rel.y);
4462 }
4463}
4464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004465void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4466 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 if (injectionState) {
4468 injectionState->pendingForegroundDispatches += 1;
4469 }
4470}
4471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004472void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4473 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 if (injectionState) {
4475 injectionState->pendingForegroundDispatches -= 1;
4476
4477 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004478 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 }
4480 }
4481}
4482
chaviw98318de2021-05-19 16:45:23 -05004483const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004484 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004485 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004486 auto it = mWindowHandlesByDisplay.find(displayId);
4487 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004488}
4489
chaviw98318de2021-05-19 16:45:23 -05004490sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004491 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004492 if (windowHandleToken == nullptr) {
4493 return nullptr;
4494 }
4495
Arthur Hungb92218b2018-08-14 12:00:21 +08004496 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004497 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4498 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004499 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004500 return windowHandle;
4501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 }
4503 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004504 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505}
4506
chaviw98318de2021-05-19 16:45:23 -05004507sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4508 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004509 if (windowHandleToken == nullptr) {
4510 return nullptr;
4511 }
4512
chaviw98318de2021-05-19 16:45:23 -05004513 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004514 if (windowHandle->getToken() == windowHandleToken) {
4515 return windowHandle;
4516 }
4517 }
4518 return nullptr;
4519}
4520
chaviw98318de2021-05-19 16:45:23 -05004521sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4522 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004523 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004524 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4525 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004526 if (handle->getId() == windowHandle->getId() &&
4527 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004528 if (windowHandle->getInfo()->displayId != it.first) {
4529 ALOGE("Found window %s in display %" PRId32
4530 ", but it should belong to display %" PRId32,
4531 windowHandle->getName().c_str(), it.first,
4532 windowHandle->getInfo()->displayId);
4533 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004534 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 }
4537 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004538 return nullptr;
4539}
4540
chaviw98318de2021-05-19 16:45:23 -05004541sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004542 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4543 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544}
4545
chaviw98318de2021-05-19 16:45:23 -05004546bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004547 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4548 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004549 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004550 if (connection != nullptr && noInputChannel) {
4551 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4552 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4553 return false;
4554 }
4555
4556 if (connection == nullptr) {
4557 if (!noInputChannel) {
4558 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4559 }
4560 return false;
4561 }
4562 if (!connection->responsive) {
4563 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4564 return false;
4565 }
4566 return true;
4567}
4568
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004569std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4570 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004571 auto connectionIt = mConnectionsByToken.find(token);
4572 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004573 return nullptr;
4574 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004575 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004576}
4577
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004578void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004579 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4580 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004581 // Remove all handles on a display if there are no windows left.
4582 mWindowHandlesByDisplay.erase(displayId);
4583 return;
4584 }
4585
4586 // Since we compare the pointer of input window handles across window updates, we need
4587 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004588 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4589 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4590 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004591 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004592 }
4593
chaviw98318de2021-05-19 16:45:23 -05004594 std::vector<sp<WindowInfoHandle>> newHandles;
4595 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004596 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004597 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004598 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004599 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4600 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4601 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004602 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004603 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004604 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004605 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004606 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004607 }
4608
4609 if (info->displayId != displayId) {
4610 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4611 handle->getName().c_str(), displayId, info->displayId);
4612 continue;
4613 }
4614
Robert Carredd13602020-04-13 17:24:34 -07004615 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4616 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004617 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004618 oldHandle->updateFrom(handle);
4619 newHandles.push_back(oldHandle);
4620 } else {
4621 newHandles.push_back(handle);
4622 }
4623 }
4624
4625 // Insert or replace
4626 mWindowHandlesByDisplay[displayId] = newHandles;
4627}
4628
Arthur Hung72d8dc32020-03-28 00:48:39 +00004629void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004630 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004631 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004632 { // acquire lock
4633 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004634 for (const auto& [displayId, handles] : handlesPerDisplay) {
4635 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004636 }
4637 }
4638 // Wake up poll loop since it may need to make new input dispatching choices.
4639 mLooper->wake();
4640}
4641
Arthur Hungb92218b2018-08-14 12:00:21 +08004642/**
4643 * Called from InputManagerService, update window handle list by displayId that can receive input.
4644 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4645 * If set an empty list, remove all handles from the specific display.
4646 * For focused handle, check if need to change and send a cancel event to previous one.
4647 * For removed handle, check if need to send a cancel event if already in touch.
4648 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004649void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004650 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004651 if (DEBUG_FOCUS) {
4652 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004653 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004654 windowList += iwh->getName() + " ";
4655 }
4656 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004659 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
chaviw98318de2021-05-19 16:45:23 -05004660 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004661 const bool noInputWindow =
chaviw98318de2021-05-19 16:45:23 -05004662 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004663 if (noInputWindow && window->getToken() != nullptr) {
4664 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4665 window->getName().c_str());
4666 window->releaseChannel();
4667 }
4668 }
4669
Arthur Hung72d8dc32020-03-28 00:48:39 +00004670 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004671 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004673 // Save the old windows' orientation by ID before it gets updated.
4674 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004675 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004676 oldWindowOrientations.emplace(handle->getId(),
4677 handle->getInfo()->transform.getOrientation());
4678 }
4679
chaviw98318de2021-05-19 16:45:23 -05004680 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004681
chaviw98318de2021-05-19 16:45:23 -05004682 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004683 if (mLastHoverWindowHandle &&
4684 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4685 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004686 mLastHoverWindowHandle = nullptr;
4687 }
4688
Vishnu Nairc519ff72021-01-21 08:23:08 -08004689 std::optional<FocusResolver::FocusChanges> changes =
4690 mFocusResolver.setInputWindows(displayId, windowHandles);
4691 if (changes) {
4692 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004695 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4696 mTouchStatesByDisplay.find(displayId);
4697 if (stateIt != mTouchStatesByDisplay.end()) {
4698 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004699 for (size_t i = 0; i < state.windows.size();) {
4700 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004701 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004702 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004703 ALOGD("Touched window was removed: %s in display %" PRId32,
4704 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004705 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004706 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004707 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4708 if (touchedInputChannel != nullptr) {
4709 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4710 "touched window was removed");
4711 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004712 // Since we are about to drop the touch, cancel the events for the wallpaper as
4713 // well.
4714 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
4715 touchedWindow.windowHandle->getInfo()->hasWallpaper) {
4716 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4717 if (wallpaper != nullptr) {
4718 sp<Connection> wallpaperConnection =
4719 getConnectionLocked(wallpaper->getToken());
4720 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4721 options);
4722 }
4723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004725 state.windows.erase(state.windows.begin() + i);
4726 } else {
4727 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729 }
arthurhungb89ccb02020-12-30 16:19:01 +08004730
arthurhung6d4bed92021-03-17 11:59:33 +08004731 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004732 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004733 if (mDragState &&
4734 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004735 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004736 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004737 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004738 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004739
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004740 if (isPerWindowInputRotationEnabled()) {
4741 // Determine if the orientation of any of the input windows have changed, and cancel all
4742 // pointer events if necessary.
chaviw98318de2021-05-19 16:45:23 -05004743 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4744 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004745 if (newWindowHandle != nullptr &&
4746 newWindowHandle->getInfo()->transform.getOrientation() !=
4747 oldWindowOrientations[oldWindowHandle->getId()]) {
4748 std::shared_ptr<InputChannel> inputChannel =
4749 getInputChannelLocked(newWindowHandle->getToken());
4750 if (inputChannel != nullptr) {
4751 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4752 "touched window's orientation changed");
4753 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4754 }
4755 }
4756 }
4757 }
4758
Arthur Hung72d8dc32020-03-28 00:48:39 +00004759 // Release information for windows that are no longer present.
4760 // This ensures that unused input channels are released promptly.
4761 // Otherwise, they might stick around until the window handle is destroyed
4762 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004763 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004764 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004765 if (DEBUG_FOCUS) {
4766 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004767 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004768 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004769 // To avoid making too many calls into the compat framework, only
4770 // check for window flags when windows are going away.
4771 // TODO(b/157929241) : delete this. This is only needed temporarily
4772 // in order to gather some data about the flag usage
chaviw98318de2021-05-19 16:45:23 -05004773 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004774 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4775 oldWindowHandle->getName().c_str());
4776 if (mCompatService != nullptr) {
4777 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4778 oldWindowHandle->getInfo()->ownerUid);
4779 }
4780 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004781 }
chaviw291d88a2019-02-14 10:33:58 -08004782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783}
4784
4785void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004786 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004787 if (DEBUG_FOCUS) {
4788 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4789 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4790 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004791 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004792 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004793 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 } // release lock
4795
4796 // Wake up poll loop since it may need to make new input dispatching choices.
4797 mLooper->wake();
4798}
4799
Vishnu Nair599f1412021-06-21 10:39:58 -07004800void InputDispatcher::setFocusedApplicationLocked(
4801 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4802 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4803 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4804
4805 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4806 return; // This application is already focused. No need to wake up or change anything.
4807 }
4808
4809 // Set the new application handle.
4810 if (inputApplicationHandle != nullptr) {
4811 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4812 } else {
4813 mFocusedApplicationHandlesByDisplay.erase(displayId);
4814 }
4815
4816 // No matter what the old focused application was, stop waiting on it because it is
4817 // no longer focused.
4818 resetNoFocusedWindowTimeoutLocked();
4819}
4820
Tiger Huang721e26f2018-07-24 22:26:19 +08004821/**
4822 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4823 * the display not specified.
4824 *
4825 * We track any unreleased events for each window. If a window loses the ability to receive the
4826 * released event, we will send a cancel event to it. So when the focused display is changed, we
4827 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4828 * display. The display-specified events won't be affected.
4829 */
4830void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004831 if (DEBUG_FOCUS) {
4832 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4833 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004834 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004835 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004836
4837 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004838 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004839 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004840 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004841 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004842 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004843 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 CancelationOptions
4845 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4846 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004847 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004848 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4849 }
4850 }
4851 mFocusedDisplayId = displayId;
4852
Chris Ye3c2d6f52020-08-09 10:39:48 -07004853 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004854 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004855 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004856
Vishnu Nairad321cd2020-08-20 16:40:21 -07004857 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004858 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004859 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004860 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004861 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004862 }
4863 }
4864 }
4865
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004866 if (DEBUG_FOCUS) {
4867 logDispatchStateLocked();
4868 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004869 } // release lock
4870
4871 // Wake up poll loop since it may need to make new input dispatching choices.
4872 mLooper->wake();
4873}
4874
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004876 if (DEBUG_FOCUS) {
4877 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879
4880 bool changed;
4881 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004882 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883
4884 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4885 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004886 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 }
4888
4889 if (mDispatchEnabled && !enabled) {
4890 resetAndDropEverythingLocked("dispatcher is being disabled");
4891 }
4892
4893 mDispatchEnabled = enabled;
4894 mDispatchFrozen = frozen;
4895 changed = true;
4896 } else {
4897 changed = false;
4898 }
4899
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004900 if (DEBUG_FOCUS) {
4901 logDispatchStateLocked();
4902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 } // release lock
4904
4905 if (changed) {
4906 // Wake up poll loop since it may need to make new input dispatching choices.
4907 mLooper->wake();
4908 }
4909}
4910
4911void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004912 if (DEBUG_FOCUS) {
4913 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
4916 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004917 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918
4919 if (mInputFilterEnabled == enabled) {
4920 return;
4921 }
4922
4923 mInputFilterEnabled = enabled;
4924 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4925 } // release lock
4926
4927 // Wake up poll loop since there might be work to do to drop everything.
4928 mLooper->wake();
4929}
4930
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004931void InputDispatcher::setInTouchMode(bool inTouchMode) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004932 bool needWake = false;
4933 {
4934 std::scoped_lock lock(mLock);
4935 if (mInTouchMode == inTouchMode) {
4936 return;
4937 }
4938 if (DEBUG_TOUCH_MODE) {
4939 ALOGD("Request to change touch mode from %s to %s", toString(mInTouchMode),
4940 toString(inTouchMode));
4941 // TODO(b/198487159): Also print the current last interacted apps.
4942 }
4943
4944 // TODO(b/198499018): Store touch mode per display.
4945 mInTouchMode = inTouchMode;
4946
4947 // TODO(b/198487159): Enforce that only last interacted apps can change touch mode.
4948 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4949 needWake = enqueueInboundEventLocked(std::move(entry));
4950 } // release lock
4951
4952 if (needWake) {
4953 mLooper->wake();
4954 }
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004955}
4956
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004957void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4958 if (opacity < 0 || opacity > 1) {
4959 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4960 return;
4961 }
4962
4963 std::scoped_lock lock(mLock);
4964 mMaximumObscuringOpacityForTouch = opacity;
4965}
4966
4967void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4968 std::scoped_lock lock(mLock);
4969 mBlockUntrustedTouchesMode = mode;
4970}
4971
Arthur Hungabbb9d82021-09-01 14:52:30 +00004972std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4973 const sp<IBinder>& token) {
4974 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4975 for (TouchedWindow& w : state.windows) {
4976 if (w.windowHandle->getToken() == token) {
4977 return std::make_pair(&state, &w);
4978 }
4979 }
4980 }
4981 return std::make_pair(nullptr, nullptr);
4982}
4983
arthurhungb89ccb02020-12-30 16:19:01 +08004984bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4985 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004986 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004987 if (DEBUG_FOCUS) {
4988 ALOGD("Trivial transfer to same window.");
4989 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004990 return true;
4991 }
4992
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004994 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995
Arthur Hungabbb9d82021-09-01 14:52:30 +00004996 // Find the target touch state and touched window by fromToken.
4997 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4998 if (state == nullptr || touchedWindow == nullptr) {
4999 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 return false;
5001 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005002
5003 const int32_t displayId = state->displayId;
5004 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5005 if (toWindowHandle == nullptr) {
5006 ALOGW("Cannot transfer focus because to window not found.");
5007 return false;
5008 }
5009
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005010 if (DEBUG_FOCUS) {
5011 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005012 touchedWindow->windowHandle->getName().c_str(),
5013 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015
Arthur Hungabbb9d82021-09-01 14:52:30 +00005016 // Erase old window.
5017 int32_t oldTargetFlags = touchedWindow->targetFlags;
5018 BitSet32 pointerIds = touchedWindow->pointerIds;
5019 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020
Arthur Hungabbb9d82021-09-01 14:52:30 +00005021 // Add new window.
5022 int32_t newTargetFlags = oldTargetFlags &
5023 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5024 InputTarget::FLAG_DISPATCH_AS_IS);
5025 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026
Arthur Hungabbb9d82021-09-01 14:52:30 +00005027 // Store the dragging window.
5028 if (isDragDrop) {
5029 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 }
5031
Arthur Hungabbb9d82021-09-01 14:52:30 +00005032 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005033 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5034 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005035 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005036 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005037 CancelationOptions
5038 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5039 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005041 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042 }
5043
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005044 if (DEBUG_FOCUS) {
5045 logDispatchStateLocked();
5046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 } // release lock
5048
5049 // Wake up poll loop since it may need to make new input dispatching choices.
5050 mLooper->wake();
5051 return true;
5052}
5053
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005054// Binder call
5055bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5056 sp<IBinder> fromToken;
5057 { // acquire lock
5058 std::scoped_lock _l(mLock);
5059
Arthur Hungabbb9d82021-09-01 14:52:30 +00005060 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5061 [](const auto& pair) { return pair.second.windows.size() == 1; });
5062 if (it == mTouchStatesByDisplay.end()) {
5063 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5064 return false;
5065 }
5066 const int32_t displayId = it->first;
5067 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005068 if (toWindowHandle == nullptr) {
5069 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5070 return false;
5071 }
5072
Arthur Hungabbb9d82021-09-01 14:52:30 +00005073 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005074 const TouchedWindow& touchedWindow = state.windows[0];
5075 fromToken = touchedWindow.windowHandle->getToken();
5076 } // release lock
5077
5078 return transferTouchFocus(fromToken, destChannelToken);
5079}
5080
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005082 if (DEBUG_FOCUS) {
5083 ALOGD("Resetting and dropping all events (%s).", reason);
5084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085
5086 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5087 synthesizeCancelationEventsForAllConnectionsLocked(options);
5088
5089 resetKeyRepeatLocked();
5090 releasePendingEventLocked();
5091 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005092 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005095 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005097 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098}
5099
5100void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005101 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 dumpDispatchStateLocked(dump);
5103
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005104 std::istringstream stream(dump);
5105 std::string line;
5106
5107 while (std::getline(stream, line, '\n')) {
5108 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 }
5110}
5111
Prabir Pradhan99987712020-11-10 18:43:05 -08005112std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5113 std::string dump;
5114
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005115 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5116 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005117
5118 std::string windowName = "None";
5119 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005120 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005121 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5122 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5123 : "token has capture without window";
5124 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005125 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005126
5127 return dump;
5128}
5129
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005130void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005131 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5132 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5133 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005134 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135
Tiger Huang721e26f2018-07-24 22:26:19 +08005136 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5137 dump += StringPrintf(INDENT "FocusedApplications:\n");
5138 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5139 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005140 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005141 const std::chrono::duration timeout =
5142 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005143 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005144 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005145 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005148 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005150
Vishnu Nairc519ff72021-01-21 08:23:08 -08005151 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005152 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005154 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005155 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005156 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5157 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005158 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005159 state.displayId, toString(state.down), toString(state.split),
5160 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005161 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005162 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005163 for (size_t i = 0; i < state.windows.size(); i++) {
5164 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005165 dump += StringPrintf(INDENT4
5166 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5167 i, touchedWindow.windowHandle->getName().c_str(),
5168 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005169 }
5170 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005171 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 }
5174 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005175 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 }
5177
arthurhung6d4bed92021-03-17 11:59:33 +08005178 if (mDragState) {
5179 dump += StringPrintf(INDENT "DragState:\n");
5180 mDragState->dump(dump, INDENT2);
5181 }
5182
Arthur Hungb92218b2018-08-14 12:00:21 +08005183 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005184 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5185 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5186 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5187 const auto& displayInfo = it->second;
5188 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5189 displayInfo.logicalHeight);
5190 displayInfo.transform.dump(dump, "transform", INDENT4);
5191 } else {
5192 dump += INDENT2 "No DisplayInfo found!\n";
5193 }
5194
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005195 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005196 dump += INDENT2 "Windows:\n";
5197 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005198 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5199 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005201 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005202 "paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005203 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005204 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005205 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005206 "applicationInfo.name=%s, "
5207 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005208 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005209 i, windowInfo->name.c_str(), windowInfo->id,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005210 windowInfo->displayId, toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07005211 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005212 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005213 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01005214 windowInfo->flags.string().c_str(),
Dominik Laskowski75788452021-02-09 18:51:25 -08005215 ftl::enum_string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01005216 windowInfo->frameLeft, windowInfo->frameTop,
5217 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005218 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005219 windowInfo->applicationInfo.name.c_str(),
5220 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005221 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005222 dump += StringPrintf(", inputFeatures=%s",
5223 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005224 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005225 "ms, trustedOverlay=%s, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005226 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005227 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005228 millis(windowInfo->dispatchingTimeout),
5229 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005230 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005231 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005232 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005233 }
5234 } else {
5235 dump += INDENT2 "Windows: <none>\n";
5236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 }
5238 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005239 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 }
5241
Michael Wright3dd60e22019-03-27 22:06:44 +00005242 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005243 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005244 const std::vector<Monitor>& monitors = it.second;
5245 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5246 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005247 }
5248 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005249 const std::vector<Monitor>& monitors = it.second;
5250 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5251 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005254 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 }
5256
5257 nsecs_t currentTime = now();
5258
5259 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005260 if (!mRecentQueue.empty()) {
5261 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005262 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005263 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005264 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005265 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 }
5267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005268 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 }
5270
5271 // Dump event currently being dispatched.
5272 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005273 dump += INDENT "PendingEvent:\n";
5274 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005275 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005276 dump += StringPrintf(", age=%" PRId64 "ms\n",
5277 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005279 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 }
5281
5282 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005283 if (!mInboundQueue.empty()) {
5284 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005285 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
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 "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 }
5293
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005294 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005295 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005296 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5297 const KeyReplacement& replacement = pair.first;
5298 int32_t newKeyCode = pair.second;
5299 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005300 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005301 }
5302 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005303 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005304 }
5305
Prabir Pradhancef936d2021-07-21 16:17:52 +00005306 if (!mCommandQueue.empty()) {
5307 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5308 } else {
5309 dump += INDENT "CommandQueue: <empty>\n";
5310 }
5311
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005312 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005313 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005314 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005315 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005316 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005317 connection->inputChannel->getFd().get(),
5318 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005319 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005322 if (!connection->outboundQueue.empty()) {
5323 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5324 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005325 dump += dumpQueue(connection->outboundQueue, currentTime);
5326
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005328 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 }
5330
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005331 if (!connection->waitQueue.empty()) {
5332 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5333 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005334 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005336 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 }
5338 }
5339 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005340 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 }
5342
5343 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005344 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5345 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005347 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 }
5349
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005350 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005351 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5352 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5353 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005354 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005355 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356}
5357
Michael Wright3dd60e22019-03-27 22:06:44 +00005358void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5359 const size_t numMonitors = monitors.size();
5360 for (size_t i = 0; i < numMonitors; i++) {
5361 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005362 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005363 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5364 dump += "\n";
5365 }
5366}
5367
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005368class LooperEventCallback : public LooperCallback {
5369public:
5370 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5371 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5372
5373private:
5374 std::function<int(int events)> mCallback;
5375};
5376
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005377Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005378 if (DEBUG_CHANNEL_CREATION) {
5379 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005382 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005383 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005384 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005385
5386 if (result) {
5387 return base::Error(result) << "Failed to open input channel pair with name " << name;
5388 }
5389
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005391 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005392 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005393 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005394 sp<Connection> connection =
5395 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005397 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5398 ALOGE("Created a new connection, but the token %p is already known", token.get());
5399 }
5400 mConnectionsByToken.emplace(token, connection);
5401
5402 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5403 this, std::placeholders::_1, token);
5404
5405 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 } // release lock
5407
5408 // Wake the looper because some connections have changed.
5409 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005410 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411}
5412
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005413Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5414 bool isGestureMonitor,
5415 const std::string& name,
5416 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005417 std::shared_ptr<InputChannel> serverChannel;
5418 std::unique_ptr<InputChannel> clientChannel;
5419 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5420 if (result) {
5421 return base::Error(result) << "Failed to open input channel pair with name " << name;
5422 }
5423
Michael Wright3dd60e22019-03-27 22:06:44 +00005424 { // acquire lock
5425 std::scoped_lock _l(mLock);
5426
5427 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005428 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5429 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005430 }
5431
Garfield Tan15601662020-09-22 15:32:38 -07005432 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005433 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005434 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005435
5436 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5437 ALOGE("Created a new connection, but the token %p is already known", token.get());
5438 }
5439 mConnectionsByToken.emplace(token, connection);
5440 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5441 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005442
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005443 auto& monitorsByDisplay =
5444 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005445 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005446
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005447 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Siarhei Vishniakouc961c742021-05-19 19:16:59 +00005448 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5449 displayId, toString(isGestureMonitor), pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005450 }
Garfield Tan15601662020-09-22 15:32:38 -07005451
Michael Wright3dd60e22019-03-27 22:06:44 +00005452 // Wake the looper because some connections have changed.
5453 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005454 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005455}
5456
Garfield Tan15601662020-09-22 15:32:38 -07005457status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005459 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460
Garfield Tan15601662020-09-22 15:32:38 -07005461 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 if (status) {
5463 return status;
5464 }
5465 } // release lock
5466
5467 // Wake the poll loop because removing the connection may have changed the current
5468 // synchronization state.
5469 mLooper->wake();
5470 return OK;
5471}
5472
Garfield Tan15601662020-09-22 15:32:38 -07005473status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5474 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005475 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005476 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005477 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 return BAD_VALUE;
5479 }
5480
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005481 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005482
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005484 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 }
5486
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005487 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
5489 nsecs_t currentTime = now();
5490 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5491
5492 connection->status = Connection::STATUS_ZOMBIE;
5493 return OK;
5494}
5495
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005496void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5497 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5498 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005499}
5500
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005501void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005502 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005503 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005504 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005505 std::vector<Monitor>& monitors = it->second;
5506 const size_t numMonitors = monitors.size();
5507 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005508 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005509 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5510 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005511 monitors.erase(monitors.begin() + i);
5512 break;
5513 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005514 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005515 if (monitors.empty()) {
5516 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005517 } else {
5518 ++it;
5519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 }
5521}
5522
Michael Wright3dd60e22019-03-27 22:06:44 +00005523status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5524 { // acquire lock
5525 std::scoped_lock _l(mLock);
5526 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5527
5528 if (!foundDisplayId) {
5529 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5530 return BAD_VALUE;
5531 }
5532 int32_t displayId = foundDisplayId.value();
5533
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005534 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5535 mTouchStatesByDisplay.find(displayId);
5536 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005537 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5538 return BAD_VALUE;
5539 }
5540
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005541 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005542 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005543 std::optional<int32_t> foundDeviceId;
Prabir Pradhan0a99c922021-09-03 08:27:53 -07005544 for (const auto& monitor : state.gestureMonitors) {
5545 if (monitor.inputChannel->getConnectionToken() == token) {
5546 requestingChannel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005547 foundDeviceId = state.deviceId;
5548 }
5549 }
5550 if (!foundDeviceId || !state.down) {
5551 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005552 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005553 return BAD_VALUE;
5554 }
5555 int32_t deviceId = foundDeviceId.value();
5556
5557 // Send cancel events to all the input channels we're stealing from.
5558 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005559 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005560 options.deviceId = deviceId;
5561 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005562 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005563 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005564 std::shared_ptr<InputChannel> channel =
5565 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005566 if (channel != nullptr) {
5567 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005568 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005569 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005570 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005571 canceledWindows += "]";
5572 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5573 canceledWindows.c_str());
5574
Michael Wright3dd60e22019-03-27 22:06:44 +00005575 // Then clear the current touch state so we stop dispatching to them as well.
5576 state.filterNonMonitors();
5577 }
5578 return OK;
5579}
5580
Prabir Pradhan99987712020-11-10 18:43:05 -08005581void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5582 { // acquire lock
5583 std::scoped_lock _l(mLock);
5584 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005585 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005586 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5587 windowHandle != nullptr ? windowHandle->getName().c_str()
5588 : "token without window");
5589 }
5590
Vishnu Nairc519ff72021-01-21 08:23:08 -08005591 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005592 if (focusedToken != windowToken) {
5593 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5594 enabled ? "enable" : "disable");
5595 return;
5596 }
5597
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005598 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005599 ALOGW("Ignoring request to %s Pointer Capture: "
5600 "window has %s requested pointer capture.",
5601 enabled ? "enable" : "disable", enabled ? "already" : "not");
5602 return;
5603 }
5604
Prabir Pradhan99987712020-11-10 18:43:05 -08005605 setPointerCaptureLocked(enabled);
5606 } // release lock
5607
5608 // Wake the thread to process command entries.
5609 mLooper->wake();
5610}
5611
Michael Wright3dd60e22019-03-27 22:06:44 +00005612std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5613 const sp<IBinder>& token) {
5614 for (const auto& it : mGestureMonitorsByDisplay) {
5615 const std::vector<Monitor>& monitors = it.second;
5616 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005617 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005618 return it.first;
5619 }
5620 }
5621 }
5622 return std::nullopt;
5623}
5624
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005625std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5626 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5627 if (gesturePid.has_value()) {
5628 return gesturePid;
5629 }
5630 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5631}
5632
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005633sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005634 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005635 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005636 }
5637
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005638 for (const auto& [token, connection] : mConnectionsByToken) {
5639 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005640 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 }
5642 }
Robert Carr4e670e52018-08-15 13:26:12 -07005643
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005644 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645}
5646
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005647std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5648 sp<Connection> connection = getConnectionLocked(connectionToken);
5649 if (connection == nullptr) {
5650 return "<nullptr>";
5651 }
5652 return connection->getInputChannelName();
5653}
5654
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005655void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005656 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005657 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005658}
5659
Prabir Pradhancef936d2021-07-21 16:17:52 +00005660void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5661 const sp<Connection>& connection, uint32_t seq,
5662 bool handled, nsecs_t consumeTime) {
5663 // Handle post-event policy actions.
5664 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5665 if (dispatchEntryIt == connection->waitQueue.end()) {
5666 return;
5667 }
5668 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5669 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5670 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5671 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5672 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5673 }
5674 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5675 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5676 connection->inputChannel->getConnectionToken(),
5677 dispatchEntry->deliveryTime, consumeTime, finishTime);
5678 }
5679
5680 bool restartEvent;
5681 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5682 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5683 restartEvent =
5684 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5685 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5686 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5687 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5688 handled);
5689 } else {
5690 restartEvent = false;
5691 }
5692
5693 // Dequeue the event and start the next cycle.
5694 // Because the lock might have been released, it is possible that the
5695 // contents of the wait queue to have been drained, so we need to double-check
5696 // a few things.
5697 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5698 if (dispatchEntryIt != connection->waitQueue.end()) {
5699 dispatchEntry = *dispatchEntryIt;
5700 connection->waitQueue.erase(dispatchEntryIt);
5701 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5702 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5703 if (!connection->responsive) {
5704 connection->responsive = isConnectionResponsive(*connection);
5705 if (connection->responsive) {
5706 // The connection was unresponsive, and now it's responsive.
5707 processConnectionResponsiveLocked(*connection);
5708 }
5709 }
5710 traceWaitQueueLength(*connection);
5711 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5712 connection->outboundQueue.push_front(dispatchEntry);
5713 traceOutboundQueueLength(*connection);
5714 } else {
5715 releaseDispatchEntry(dispatchEntry);
5716 }
5717 }
5718
5719 // Start the next dispatch cycle for this connection.
5720 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721}
5722
Prabir Pradhancef936d2021-07-21 16:17:52 +00005723void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5724 const sp<IBinder>& newToken) {
5725 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5726 scoped_unlock unlock(mLock);
5727 mPolicy->notifyFocusChanged(oldToken, newToken);
5728 };
5729 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730}
5731
Prabir Pradhancef936d2021-07-21 16:17:52 +00005732void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5733 auto command = [this, token, x, y]() REQUIRES(mLock) {
5734 scoped_unlock unlock(mLock);
5735 mPolicy->notifyDropWindow(token, x, y);
5736 };
5737 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005738}
5739
Prabir Pradhancef936d2021-07-21 16:17:52 +00005740void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5741 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5742 scoped_unlock unlock(mLock);
5743 mPolicy->notifyUntrustedTouch(obscuringPackage);
5744 };
5745 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005746}
5747
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005748void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5749 if (connection == nullptr) {
5750 LOG_ALWAYS_FATAL("Caller must check for nullness");
5751 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005752 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5753 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005754 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005755 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005756 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005757 return;
5758 }
5759 /**
5760 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5761 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5762 * has changed. This could cause newer entries to time out before the already dispatched
5763 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5764 * processes the events linearly. So providing information about the oldest entry seems to be
5765 * most useful.
5766 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005767 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005768 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5769 std::string reason =
5770 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005771 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005772 ns2ms(currentWait),
5773 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005774 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005775 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005776
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005777 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5778
5779 // Stop waking up for events on this connection, it is already unresponsive
5780 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005781}
5782
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005783void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5784 std::string reason =
5785 StringPrintf("%s does not have a focused window", application->getName().c_str());
5786 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005787
Prabir Pradhancef936d2021-07-21 16:17:52 +00005788 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5789 scoped_unlock unlock(mLock);
5790 mPolicy->notifyNoFocusedWindowAnr(application);
5791 };
5792 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005793}
5794
chaviw98318de2021-05-19 16:45:23 -05005795void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005796 const std::string& reason) {
5797 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5798 updateLastAnrStateLocked(windowLabel, reason);
5799}
5800
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005801void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5802 const std::string& reason) {
5803 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005804 updateLastAnrStateLocked(windowLabel, reason);
5805}
5806
5807void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5808 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005810 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 struct tm tm;
5812 localtime_r(&t, &tm);
5813 char timestr[64];
5814 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005815 mLastAnrState.clear();
5816 mLastAnrState += INDENT "ANR:\n";
5817 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005818 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5819 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005820 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821}
5822
Prabir Pradhancef936d2021-07-21 16:17:52 +00005823void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5824 KeyEntry& entry) {
5825 const KeyEvent event = createKeyEvent(entry);
5826 nsecs_t delay = 0;
5827 { // release lock
5828 scoped_unlock unlock(mLock);
5829 android::base::Timer t;
5830 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5831 entry.policyFlags);
5832 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5833 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5834 std::to_string(t.duration().count()).c_str());
5835 }
5836 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837
5838 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005839 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005840 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005841 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005843 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5844 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846}
5847
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005848void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005849 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5850 scoped_unlock unlock(mLock);
5851 mPolicy->notifyMonitorUnresponsive(pid, reason);
5852 };
5853 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005854}
5855
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005857 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005858 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5859 scoped_unlock unlock(mLock);
5860 mPolicy->notifyWindowUnresponsive(token, reason);
5861 };
5862 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005863}
5864
5865void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005866 auto command = [this, pid]() REQUIRES(mLock) {
5867 scoped_unlock unlock(mLock);
5868 mPolicy->notifyMonitorResponsive(pid);
5869 };
5870 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005871}
5872
Prabir Pradhancef936d2021-07-21 16:17:52 +00005873void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5874 auto command = [this, connectionToken]() REQUIRES(mLock) {
5875 scoped_unlock unlock(mLock);
5876 mPolicy->notifyWindowResponsive(connectionToken);
5877 };
5878 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005879}
5880
5881/**
5882 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5883 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5884 * command entry to the command queue.
5885 */
5886void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5887 std::string reason) {
5888 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5889 if (connection.monitor) {
5890 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5891 reason.c_str());
5892 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5893 if (!pid.has_value()) {
5894 ALOGE("Could not find unresponsive monitor for connection %s",
5895 connection.inputChannel->getName().c_str());
5896 return;
5897 }
5898 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5899 return;
5900 }
5901 // If not a monitor, must be a window
5902 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5903 reason.c_str());
5904 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5905}
5906
5907/**
5908 * Tell the policy that a connection has become responsive so that it can stop ANR.
5909 */
5910void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5911 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5912 if (connection.monitor) {
5913 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5914 if (!pid.has_value()) {
5915 ALOGE("Could not find responsive monitor for connection %s",
5916 connection.inputChannel->getName().c_str());
5917 return;
5918 }
5919 sendMonitorResponsiveCommandLocked(pid.value());
5920 return;
5921 }
5922 // If not a monitor, must be a window
5923 sendWindowResponsiveCommandLocked(connectionToken);
5924}
5925
Prabir Pradhancef936d2021-07-21 16:17:52 +00005926bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005927 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005928 KeyEntry& keyEntry, bool handled) {
5929 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005930 if (!handled) {
5931 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005933 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005934 return false;
5935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005937 // Get the fallback key state.
5938 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005939 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005941 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005942 connection->inputState.removeFallbackKey(originalKeyCode);
5943 }
5944
5945 if (handled || !dispatchEntry->hasForegroundTarget()) {
5946 // If the application handles the original key for which we previously
5947 // generated a fallback or if the window is not a foreground window,
5948 // then cancel the associated fallback key, if any.
5949 if (fallbackKeyCode != -1) {
5950 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005951 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5952 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5953 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5954 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5955 keyEntry.policyFlags);
5956 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005958 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
5960 mLock.unlock();
5961
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005962 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005963 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964
5965 mLock.lock();
5966
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005967 // Cancel the fallback key.
5968 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005970 "application handled the original non-fallback key "
5971 "or is no longer a foreground target, "
5972 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 options.keyCode = fallbackKeyCode;
5974 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005976 connection->inputState.removeFallbackKey(originalKeyCode);
5977 }
5978 } else {
5979 // If the application did not handle a non-fallback key, first check
5980 // that we are in a good state to perform unhandled key event processing
5981 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005982 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005984 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5985 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5986 "since this is not an initial down. "
5987 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5988 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5989 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005990 return false;
5991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005993 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005994 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5995 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5996 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5997 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5998 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005999 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006000
6001 mLock.unlock();
6002
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006003 bool fallback =
6004 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006005 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006006
6007 mLock.lock();
6008
6009 if (connection->status != Connection::STATUS_NORMAL) {
6010 connection->inputState.removeFallbackKey(originalKeyCode);
6011 return false;
6012 }
6013
6014 // Latch the fallback keycode for this key on an initial down.
6015 // The fallback keycode cannot change at any other point in the lifecycle.
6016 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018 fallbackKeyCode = event.getKeyCode();
6019 } else {
6020 fallbackKeyCode = AKEYCODE_UNKNOWN;
6021 }
6022 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6023 }
6024
6025 ALOG_ASSERT(fallbackKeyCode != -1);
6026
6027 // Cancel the fallback key if the policy decides not to send it anymore.
6028 // We will continue to dispatch the key to the policy but we will no
6029 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006030 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6031 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006032 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6033 if (fallback) {
6034 ALOGD("Unhandled key event: Policy requested to send key %d"
6035 "as a fallback for %d, but on the DOWN it had requested "
6036 "to send %d instead. Fallback canceled.",
6037 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6038 } else {
6039 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6040 "but on the DOWN it had requested to send %d. "
6041 "Fallback canceled.",
6042 originalKeyCode, fallbackKeyCode);
6043 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045
6046 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6047 "canceling fallback, policy no longer desires it");
6048 options.keyCode = fallbackKeyCode;
6049 synthesizeCancelationEventsForConnectionLocked(connection, options);
6050
6051 fallback = false;
6052 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006053 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006054 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055 }
6056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006058 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6059 {
6060 std::string msg;
6061 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6062 connection->inputState.getFallbackKeys();
6063 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6064 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6065 }
6066 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6067 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070
6071 if (fallback) {
6072 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006073 keyEntry.eventTime = event.getEventTime();
6074 keyEntry.deviceId = event.getDeviceId();
6075 keyEntry.source = event.getSource();
6076 keyEntry.displayId = event.getDisplayId();
6077 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6078 keyEntry.keyCode = fallbackKeyCode;
6079 keyEntry.scanCode = event.getScanCode();
6080 keyEntry.metaState = event.getMetaState();
6081 keyEntry.repeatCount = event.getRepeatCount();
6082 keyEntry.downTime = event.getDownTime();
6083 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006084
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006085 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6086 ALOGD("Unhandled key event: Dispatching fallback key. "
6087 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6088 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6089 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 return true; // restart the event
6091 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006092 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6093 ALOGD("Unhandled key event: No fallback key.");
6094 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006095
6096 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006097 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 }
6099 }
6100 return false;
6101}
6102
Prabir Pradhancef936d2021-07-21 16:17:52 +00006103bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006104 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106 return false;
6107}
6108
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109void InputDispatcher::traceInboundQueueLengthLocked() {
6110 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006111 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112 }
6113}
6114
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006115void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006116 if (ATRACE_ENABLED()) {
6117 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006118 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6119 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 }
6121}
6122
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006123void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006124 if (ATRACE_ENABLED()) {
6125 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006126 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6127 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 }
6129}
6130
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006131void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006132 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006134 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006135 dumpDispatchStateLocked(dump);
6136
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006137 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006138 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006139 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140 }
6141}
6142
6143void InputDispatcher::monitor() {
6144 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006145 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006147 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148}
6149
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006150/**
6151 * Wake up the dispatcher and wait until it processes all events and commands.
6152 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6153 * this method can be safely called from any thread, as long as you've ensured that
6154 * the work you are interested in completing has already been queued.
6155 */
6156bool InputDispatcher::waitForIdle() {
6157 /**
6158 * Timeout should represent the longest possible time that a device might spend processing
6159 * events and commands.
6160 */
6161 constexpr std::chrono::duration TIMEOUT = 100ms;
6162 std::unique_lock lock(mLock);
6163 mLooper->wake();
6164 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6165 return result == std::cv_status::no_timeout;
6166}
6167
Vishnu Naire798b472020-07-23 13:52:21 -07006168/**
6169 * Sets focus to the window identified by the token. This must be called
6170 * after updating any input window handles.
6171 *
6172 * Params:
6173 * request.token - input channel token used to identify the window that should gain focus.
6174 * request.focusedToken - the token that the caller expects currently to be focused. If the
6175 * specified token does not match the currently focused window, this request will be dropped.
6176 * If the specified focused token matches the currently focused window, the call will succeed.
6177 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6178 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6179 * when requesting the focus change. This determines which request gets
6180 * precedence if there is a focus change request from another source such as pointer down.
6181 */
Vishnu Nair958da932020-08-21 17:12:37 -07006182void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6183 { // acquire lock
6184 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006185 std::optional<FocusResolver::FocusChanges> changes =
6186 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6187 if (changes) {
6188 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006189 }
6190 } // release lock
6191 // Wake up poll loop since it may need to make new input dispatching choices.
6192 mLooper->wake();
6193}
6194
Vishnu Nairc519ff72021-01-21 08:23:08 -08006195void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6196 if (changes.oldFocus) {
6197 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006198 if (focusedInputChannel) {
6199 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6200 "focus left window");
6201 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006202 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006203 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006204 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006205 if (changes.newFocus) {
6206 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006207 }
6208
Prabir Pradhan99987712020-11-10 18:43:05 -08006209 // If a window has pointer capture, then it must have focus. We need to ensure that this
6210 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6211 // If the window loses focus before it loses pointer capture, then the window can be in a state
6212 // where it has pointer capture but not focus, violating the contract. Therefore we must
6213 // dispatch the pointer capture event before the focus event. Since focus events are added to
6214 // the front of the queue (above), we add the pointer capture event to the front of the queue
6215 // after the focus events are added. This ensures the pointer capture event ends up at the
6216 // front.
6217 disablePointerCaptureForcedLocked();
6218
Vishnu Nairc519ff72021-01-21 08:23:08 -08006219 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006220 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006221 }
6222}
Vishnu Nair958da932020-08-21 17:12:37 -07006223
Prabir Pradhan99987712020-11-10 18:43:05 -08006224void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006225 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006226 return;
6227 }
6228
6229 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6230
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006231 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006232 setPointerCaptureLocked(false);
6233 }
6234
6235 if (!mWindowTokenWithPointerCapture) {
6236 // No need to send capture changes because no window has capture.
6237 return;
6238 }
6239
6240 if (mPendingEvent != nullptr) {
6241 // Move the pending event to the front of the queue. This will give the chance
6242 // for the pending event to be dropped if it is a captured event.
6243 mInboundQueue.push_front(mPendingEvent);
6244 mPendingEvent = nullptr;
6245 }
6246
6247 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006248 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006249 mInboundQueue.push_front(std::move(entry));
6250}
6251
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006252void InputDispatcher::setPointerCaptureLocked(bool enable) {
6253 mCurrentPointerCaptureRequest.enable = enable;
6254 mCurrentPointerCaptureRequest.seq++;
6255 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006256 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006257 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258 };
6259 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006260}
6261
Vishnu Nair599f1412021-06-21 10:39:58 -07006262void InputDispatcher::displayRemoved(int32_t displayId) {
6263 { // acquire lock
6264 std::scoped_lock _l(mLock);
6265 // Set an empty list to remove all handles from the specific display.
6266 setInputWindowsLocked(/* window handles */ {}, displayId);
6267 setFocusedApplicationLocked(displayId, nullptr);
6268 // Call focus resolver to clean up stale requests. This must be called after input windows
6269 // have been removed for the removed display.
6270 mFocusResolver.displayRemoved(displayId);
6271 } // release lock
6272
6273 // Wake up poll loop since it may need to make new input dispatching choices.
6274 mLooper->wake();
6275}
6276
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006277void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6278 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006279 // The listener sends the windows as a flattened array. Separate the windows by display for
6280 // more convenient parsing.
6281 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006282 for (const auto& info : windowInfos) {
6283 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6284 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6285 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006286
6287 { // acquire lock
6288 std::scoped_lock _l(mLock);
6289 mDisplayInfos.clear();
6290 for (const auto& displayInfo : displayInfos) {
6291 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6292 }
6293
6294 for (const auto& [displayId, handles] : handlesPerDisplay) {
6295 setInputWindowsLocked(handles, displayId);
6296 }
6297 }
6298 // Wake up poll loop since it may need to make new input dispatching choices.
6299 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006300}
6301
Vishnu Nair062a8672021-09-03 16:07:44 -07006302bool InputDispatcher::shouldDropInput(
6303 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6304 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6305 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6306 isWindowObscuredLocked(windowHandle))) {
6307 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6308 "%" PRId32 ".",
6309 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6310 windowHandle->getInfo()->inputFeatures.string().c_str(),
6311 windowHandle->getInfo()->displayId);
6312 return true;
6313 }
6314 return false;
6315}
6316
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006317void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6318 const std::vector<gui::WindowInfo>& windowInfos,
6319 const std::vector<DisplayInfo>& displayInfos) {
6320 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6321}
6322
Garfield Tane84e6f92019-08-29 17:28:41 -07006323} // namespace android::inputdispatcher