blob: 83a203e220fc31d7632ca05171a966e8116f54e0 [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
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080081using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000082using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080083using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100085using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080086using android::os::InputEventInjectionResult;
87using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100088using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080089
Garfield Tane84e6f92019-08-29 17:28:41 -070090namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Default input dispatching timeout if there is no focused application or paused window
93// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080094const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
95 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
96 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Amount of time to allow for all pending events to be processed when an app switch
99// key is on the way. This is used to preempt input dispatch and drop input events
100// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000101constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
103// Amount of time to allow for an event to be dispatched (measured since its eventTime)
104// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// 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 +0000108constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
109
110// Log a warning when an interception call takes longer than this to process.
111constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700113// Additional key latency in case a connection is still processing some motion events.
114// This will help with the case when a user touched a button that opens a new window,
115// and gives us the chance to dispatch the key to this new window.
116constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
120
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000121// Event log tags. See EventLogTags.logtags for reference
122constexpr int LOGTAG_INPUT_INTERACTION = 62000;
123constexpr int LOGTAG_INPUT_FOCUS = 62001;
124
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125static inline nsecs_t now() {
126 return systemTime(SYSTEM_TIME_MONOTONIC);
127}
128
129static inline const char* toString(bool value) {
130 return value ? "true" : "false";
131}
132
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000133static inline const std::string toString(sp<IBinder> binder) {
134 if (binder == nullptr) {
135 return "<null>";
136 }
137 return StringPrintf("%p", binder.get());
138}
139
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700141 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
142 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143}
144
145static bool isValidKeyAction(int32_t action) {
146 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 case AKEY_EVENT_ACTION_DOWN:
148 case AKEY_EVENT_ACTION_UP:
149 return true;
150 default:
151 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152 }
153}
154
155static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 ALOGE("Key event has invalid action code 0x%x", action);
158 return false;
159 }
160 return true;
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_DOWN:
166 case AMOTION_EVENT_ACTION_UP:
167 case AMOTION_EVENT_ACTION_CANCEL:
168 case AMOTION_EVENT_ACTION_MOVE:
169 case AMOTION_EVENT_ACTION_OUTSIDE:
170 case AMOTION_EVENT_ACTION_HOVER_ENTER:
171 case AMOTION_EVENT_ACTION_HOVER_MOVE:
172 case AMOTION_EVENT_ACTION_HOVER_EXIT:
173 case AMOTION_EVENT_ACTION_SCROLL:
174 return true;
175 case AMOTION_EVENT_ACTION_POINTER_DOWN:
176 case AMOTION_EVENT_ACTION_POINTER_UP: {
177 int32_t index = getMotionEventActionPointerIndex(action);
178 return index >= 0 && index < pointerCount;
179 }
180 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
181 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
182 return actionButton != 0;
183 default:
184 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 }
186}
187
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500188static int64_t millis(std::chrono::nanoseconds t) {
189 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
190}
191
Michael Wright7b159c92015-05-14 14:48:03 +0100192static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 const PointerProperties* pointerProperties) {
194 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 ALOGE("Motion event has invalid action code 0x%x", action);
196 return false;
197 }
198 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000199 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 return false;
202 }
203 BitSet32 pointerIdBits;
204 for (size_t i = 0; i < pointerCount; i++) {
205 int32_t id = pointerProperties[i].id;
206 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700207 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
208 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return false;
210 }
211 if (pointerIdBits.hasBit(id)) {
212 ALOGE("Motion event has duplicate pointer id %d", id);
213 return false;
214 }
215 pointerIdBits.markBit(id);
216 }
217 return true;
218}
219
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000220static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
224
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000225 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 bool first = true;
227 Region::const_iterator cur = region.begin();
228 Region::const_iterator const tail = region.end();
229 while (cur != tail) {
230 if (first) {
231 first = false;
232 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800235 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 cur++;
237 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000238 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239}
240
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500241static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
242 constexpr size_t maxEntries = 50; // max events to print
243 constexpr size_t skipBegin = maxEntries / 2;
244 const size_t skipEnd = queue.size() - maxEntries / 2;
245 // skip from maxEntries / 2 ... size() - maxEntries/2
246 // only print from 0 .. skipBegin and then from skipEnd .. size()
247
248 std::string dump;
249 for (size_t i = 0; i < queue.size(); i++) {
250 const DispatchEntry& entry = *queue[i];
251 if (i >= skipBegin && i < skipEnd) {
252 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
253 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
254 continue;
255 }
256 dump.append(INDENT4);
257 dump += entry.eventEntry->getDescription();
258 dump += StringPrintf(", seq=%" PRIu32
259 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
260 entry.seq, entry.targetFlags, entry.resolvedAction,
261 ns2ms(currentTime - entry.eventEntry->eventTime));
262 if (entry.deliveryTime != 0) {
263 // This entry was delivered, so add information on how long we've been waiting
264 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
265 }
266 dump.append("\n");
267 }
268 return dump;
269}
270
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271/**
272 * Find the entry in std::unordered_map by key, and return it.
273 * If the entry is not found, return a default constructed entry.
274 *
275 * Useful when the entries are vectors, since an empty vector will be returned
276 * if the entry is not found.
277 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
278 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700279template <typename K, typename V>
280static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700281 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700282 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800283}
284
chaviwaf87b3e2019-10-01 16:59:28 -0700285static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
286 if (first == second) {
287 return true;
288 }
289
290 if (first == nullptr || second == nullptr) {
291 return false;
292 }
293
294 return first->getToken() == second->getToken();
295}
296
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000297static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
298 if (first == nullptr || second == nullptr) {
299 return false;
300 }
301 return first->applicationInfo.token != nullptr &&
302 first->applicationInfo.token == second->applicationInfo.token;
303}
304
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800305static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
306 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
307}
308
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000309static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700310 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000311 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900312 if (eventEntry->type == EventEntry::Type::MOTION) {
313 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Prabir Pradhanbd527712021-03-09 19:17:09 -0800314 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) == 0) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900315 const ui::Transform identityTransform;
Prabir Pradhanbd527712021-03-09 19:17:09 -0800316 // Use identity transform for events that are not pointer events because their axes
317 // values do not represent on-screen coordinates, so they should not have any window
318 // transformations applied to them.
yunho.shinf4a80b82020-11-16 21:13:57 +0900319 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700320 1.0f /*globalScaleFactor*/,
321 inputTarget.displaySize);
yunho.shinf4a80b82020-11-16 21:13:57 +0900322 }
323 }
324
chaviw1ff3d1e2020-07-01 15:53:47 -0700325 if (inputTarget.useDefaultPointerTransform()) {
326 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700327 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Evan Rosky84f07f02021-04-16 10:42:42 -0700328 inputTarget.globalScaleFactor,
329 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000330 }
331
332 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
333 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
334
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700335 std::vector<PointerCoords> pointerCoords;
336 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000337
338 // Use the first pointer information to normalize all other pointers. This could be any pointer
339 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700340 // uses the transform for the normalized pointer.
341 const ui::Transform& firstPointerTransform =
342 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
343 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344
345 // Iterate through all pointers in the event to normalize against the first.
346 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
347 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
348 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700349 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000350
351 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700352 // First, apply the current pointer's transform to update the coordinates into
353 // window space.
354 pointerCoords[pointerIndex].transform(currTransform);
355 // Next, apply the inverse transform of the normalized coordinates so the
356 // current coordinates are transformed into the normalized coordinate space.
357 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358 }
359
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700360 std::unique_ptr<MotionEntry> combinedMotionEntry =
361 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
362 motionEntry.deviceId, motionEntry.source,
363 motionEntry.displayId, motionEntry.policyFlags,
364 motionEntry.action, motionEntry.actionButton,
365 motionEntry.flags, motionEntry.metaState,
366 motionEntry.buttonState, motionEntry.classification,
367 motionEntry.edgeFlags, motionEntry.xPrecision,
368 motionEntry.yPrecision, motionEntry.xCursorPosition,
369 motionEntry.yCursorPosition, motionEntry.downTime,
370 motionEntry.pointerCount, motionEntry.pointerProperties,
371 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000372
373 if (motionEntry.injectionState) {
374 combinedMotionEntry->injectionState = motionEntry.injectionState;
375 combinedMotionEntry->injectionState->refCount += 1;
376 }
377
378 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700379 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Evan Rosky84f07f02021-04-16 10:42:42 -0700380 firstPointerTransform, inputTarget.globalScaleFactor,
381 inputTarget.displaySize);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382 return dispatchEntry;
383}
384
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700385static void addGestureMonitors(const std::vector<Monitor>& monitors,
386 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
387 float yOffset = 0) {
388 if (monitors.empty()) {
389 return;
390 }
391 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
392 for (const Monitor& monitor : monitors) {
393 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
394 }
395}
396
Garfield Tan15601662020-09-22 15:32:38 -0700397static status_t openInputChannelPair(const std::string& name,
398 std::shared_ptr<InputChannel>& serverChannel,
399 std::unique_ptr<InputChannel>& clientChannel) {
400 std::unique_ptr<InputChannel> uniqueServerChannel;
401 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
402
403 serverChannel = std::move(uniqueServerChannel);
404 return result;
405}
406
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500407template <typename T>
408static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
409 if (lhs == nullptr && rhs == nullptr) {
410 return true;
411 }
412 if (lhs == nullptr || rhs == nullptr) {
413 return false;
414 }
415 return *lhs == *rhs;
416}
417
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000418static sp<IPlatformCompatNative> getCompatService() {
419 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
420 if (service == nullptr) {
421 ALOGE("Failed to link to compat service");
422 return nullptr;
423 }
424 return interface_cast<IPlatformCompatNative>(service);
425}
426
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000427static KeyEvent createKeyEvent(const KeyEntry& entry) {
428 KeyEvent event;
429 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
430 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
431 entry.repeatCount, entry.downTime, entry.eventTime);
432 return event;
433}
434
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000435static std::optional<int32_t> findMonitorPidByToken(
436 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
437 const sp<IBinder>& token) {
438 for (const auto& it : monitorsByDisplay) {
439 const std::vector<Monitor>& monitors = it.second;
440 for (const Monitor& monitor : monitors) {
441 if (monitor.inputChannel->getConnectionToken() == token) {
442 return monitor.pid;
443 }
444 }
445 }
446 return std::nullopt;
447}
448
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000449static bool shouldReportMetricsForConnection(const Connection& connection) {
450 // Do not keep track of gesture monitors. They receive every event and would disproportionately
451 // affect the statistics.
452 if (connection.monitor) {
453 return false;
454 }
455 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
456 if (!connection.responsive) {
457 return false;
458 }
459 return true;
460}
461
462static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
463 const Connection& connection) {
464 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
465 const int32_t& inputEventId = eventEntry.id;
466 if (inputEventId != dispatchEntry.resolvedEventId) {
467 // Event was transmuted
468 return false;
469 }
470 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
471 return false;
472 }
473 // Only track latency for events that originated from hardware
474 if (eventEntry.isSynthesized()) {
475 return false;
476 }
477 const EventEntry::Type& inputEventEntryType = eventEntry.type;
478 if (inputEventEntryType == EventEntry::Type::KEY) {
479 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
480 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
481 return false;
482 }
483 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
484 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
485 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
486 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
487 return false;
488 }
489 } else {
490 // Not a key or a motion
491 return false;
492 }
493 if (!shouldReportMetricsForConnection(connection)) {
494 return false;
495 }
496 return true;
497}
498
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499// --- InputDispatcher ---
500
Garfield Tan00f511d2019-06-12 16:55:40 -0700501InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
502 : mPolicy(policy),
503 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700504 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800505 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700506 mAppSwitchSawKeyDown(false),
507 mAppSwitchDueTime(LONG_LONG_MAX),
508 mNextUnblockedEvent(nullptr),
509 mDispatchEnabled(false),
510 mDispatchFrozen(false),
511 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800512 // mInTouchMode will be initialized by the WindowManager to the default device config.
513 // To avoid leaking stack in case that call never comes, and for tests,
514 // initialize it here anyways.
515 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100516 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000517 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800518 mFocusedWindowRequestedPointerCapture(false),
519 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000520 mLatencyAggregator(),
521 mLatencyTracker(&mLatencyAggregator),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000522 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800524 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525
Yi Kong9b14ac62018-07-17 13:48:38 -0700526 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527
528 policy->getDispatcherConfiguration(&mConfig);
529}
530
531InputDispatcher::~InputDispatcher() {
532 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800533 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 resetKeyRepeatLocked();
536 releasePendingEventLocked();
537 drainInboundQueueLocked();
538 }
539
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000540 while (!mConnectionsByToken.empty()) {
541 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700542 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544}
545
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700546status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700547 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700548 return ALREADY_EXISTS;
549 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700550 mThread = std::make_unique<InputThread>(
551 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
552 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700553}
554
555status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700556 if (mThread && mThread->isCallingThread()) {
557 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700558 return INVALID_OPERATION;
559 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700560 mThread.reset();
561 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700562}
563
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564void InputDispatcher::dispatchOnce() {
565 nsecs_t nextWakeupTime = LONG_LONG_MAX;
566 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800567 std::scoped_lock _l(mLock);
568 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569
570 // Run a dispatch loop if there are no pending commands.
571 // The dispatch loop might enqueue commands to run afterwards.
572 if (!haveCommandsLocked()) {
573 dispatchOnceInnerLocked(&nextWakeupTime);
574 }
575
576 // Run all pending commands if there are any.
577 // If any commands were run then force the next poll to wake up immediately.
578 if (runCommandsLockedInterruptible()) {
579 nextWakeupTime = LONG_LONG_MIN;
580 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800581
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700582 // If we are still waiting for ack on some events,
583 // we might have to wake up earlier to check if an app is anr'ing.
584 const nsecs_t nextAnrCheck = processAnrsLocked();
585 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
586
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800587 // We are about to enter an infinitely long sleep, because we have no commands or
588 // pending or queued events
589 if (nextWakeupTime == LONG_LONG_MAX) {
590 mDispatcherEnteredIdle.notify_all();
591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 } // release lock
593
594 // Wait for callback or timeout or wake. (make sure we round up, not down)
595 nsecs_t currentTime = now();
596 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
597 mLooper->pollOnce(timeoutMillis);
598}
599
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700600/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500601 * Raise ANR if there is no focused window.
602 * Before the ANR is raised, do a final state check:
603 * 1. The currently focused application must be the same one we are waiting for.
604 * 2. Ensure we still don't have a focused window.
605 */
606void InputDispatcher::processNoFocusedWindowAnrLocked() {
607 // Check if the application that we are waiting for is still focused.
608 std::shared_ptr<InputApplicationHandle> focusedApplication =
609 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
610 if (focusedApplication == nullptr ||
611 focusedApplication->getApplicationToken() !=
612 mAwaitedFocusedApplication->getApplicationToken()) {
613 // Unexpected because we should have reset the ANR timer when focused application changed
614 ALOGE("Waited for a focused window, but focused application has already changed to %s",
615 focusedApplication->getName().c_str());
616 return; // The focused application has changed.
617 }
618
619 const sp<InputWindowHandle>& focusedWindowHandle =
620 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
621 if (focusedWindowHandle != nullptr) {
622 return; // We now have a focused window. No need for ANR.
623 }
624 onAnrLocked(mAwaitedFocusedApplication);
625}
626
627/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700628 * Check if any of the connections' wait queues have events that are too old.
629 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
630 * Return the time at which we should wake up next.
631 */
632nsecs_t InputDispatcher::processAnrsLocked() {
633 const nsecs_t currentTime = now();
634 nsecs_t nextAnrCheck = LONG_LONG_MAX;
635 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
636 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
637 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500638 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700639 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500640 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700641 return LONG_LONG_MIN;
642 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500643 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700644 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
645 }
646 }
647
648 // Check if any connection ANRs are due
649 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
650 if (currentTime < nextAnrCheck) { // most likely scenario
651 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
652 }
653
654 // If we reached here, we have an unresponsive connection.
655 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
656 if (connection == nullptr) {
657 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
658 return nextAnrCheck;
659 }
660 connection->responsive = false;
661 // Stop waking up for this unresponsive connection
662 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000663 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700664 return LONG_LONG_MIN;
665}
666
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500667std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700668 sp<InputWindowHandle> window = getWindowHandleLocked(token);
669 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500670 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500672 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673}
674
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
676 nsecs_t currentTime = now();
677
Jeff Browndc5992e2014-04-11 01:27:26 -0700678 // Reset the key repeat timer whenever normal dispatch is suspended while the
679 // device is in a non-interactive state. This is to ensure that we abort a key
680 // repeat if the device is just coming out of sleep.
681 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 resetKeyRepeatLocked();
683 }
684
685 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
686 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100687 if (DEBUG_FOCUS) {
688 ALOGD("Dispatch frozen. Waiting some more.");
689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 return;
691 }
692
693 // Optimize latency of app switches.
694 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
695 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
696 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
697 if (mAppSwitchDueTime < *nextWakeupTime) {
698 *nextWakeupTime = mAppSwitchDueTime;
699 }
700
701 // Ready to start a new event.
702 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700704 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 if (isAppSwitchDue) {
706 // The inbound queue is empty so the app switch key we were waiting
707 // for will never arrive. Stop waiting for it.
708 resetPendingAppSwitchLocked(false);
709 isAppSwitchDue = false;
710 }
711
712 // Synthesize a key repeat if appropriate.
713 if (mKeyRepeatState.lastKeyEntry) {
714 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
715 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
716 } else {
717 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
718 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
719 }
720 }
721 }
722
723 // Nothing to do if there is no pending event.
724 if (!mPendingEvent) {
725 return;
726 }
727 } else {
728 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700729 mPendingEvent = mInboundQueue.front();
730 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 traceInboundQueueLengthLocked();
732 }
733
734 // Poke user activity for this event.
735 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700736 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 }
739
740 // Now we have an event to dispatch.
741 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700742 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700744 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700746 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700748 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 }
750
751 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700752 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 }
754
755 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700756 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 const ConfigurationChangedEntry& typedEntry =
758 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700760 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 break;
762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700764 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700765 const DeviceResetEntry& typedEntry =
766 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700768 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 break;
770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100772 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700773 std::shared_ptr<FocusEntry> typedEntry =
774 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100775 dispatchFocusLocked(currentTime, typedEntry);
776 done = true;
777 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
778 break;
779 }
780
Prabir Pradhan99987712020-11-10 18:43:05 -0800781 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
782 const auto typedEntry =
783 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
784 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
785 done = true;
786 break;
787 }
788
arthurhungb89ccb02020-12-30 16:19:01 +0800789 case EventEntry::Type::DRAG: {
790 std::shared_ptr<DragEntry> typedEntry =
791 std::static_pointer_cast<DragEntry>(mPendingEvent);
792 dispatchDragLocked(currentTime, typedEntry);
793 done = true;
794 break;
795 }
796
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700797 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700798 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700800 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 resetPendingAppSwitchLocked(true);
802 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 } else if (dropReason == DropReason::NOT_DROPPED) {
804 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 }
806 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700808 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
811 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700813 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 break;
815 }
816
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700817 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700818 std::shared_ptr<MotionEntry> motionEntry =
819 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
821 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700824 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700826 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
827 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700829 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 }
Chris Yef59a2f42020-10-16 12:55:26 -0700832
833 case EventEntry::Type::SENSOR: {
834 std::shared_ptr<SensorEntry> sensorEntry =
835 std::static_pointer_cast<SensorEntry>(mPendingEvent);
836 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
837 dropReason = DropReason::APP_SWITCH;
838 }
839 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
840 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
841 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
842 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
843 dropReason = DropReason::STALE;
844 }
845 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
846 done = true;
847 break;
848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
850
851 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700852 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700853 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 }
Michael Wright3a981722015-06-10 15:26:13 +0100855 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856
857 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 }
860}
861
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700862/**
863 * Return true if the events preceding this incoming motion event should be dropped
864 * Return false otherwise (the default behaviour)
865 */
866bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700867 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700868 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700869
870 // Optimize case where the current application is unresponsive and the user
871 // decides to touch a window in a different application.
872 // If the application takes too long to catch up then we drop all events preceding
873 // the touch into the other window.
874 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875 int32_t displayId = motionEntry.displayId;
876 int32_t x = static_cast<int32_t>(
877 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
878 int32_t y = static_cast<int32_t>(
879 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
880 sp<InputWindowHandle> touchedWindowHandle =
881 findTouchedWindowAtLocked(displayId, x, y, nullptr);
882 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700883 touchedWindowHandle->getApplicationToken() !=
884 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700885 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 ALOGI("Pruning input queue because user touched a different application while waiting "
887 "for %s",
888 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700889 return true;
890 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700891
892 // Alternatively, maybe there's a gesture monitor that could handle this event
893 std::vector<TouchedMonitor> gestureMonitors =
894 findTouchedGestureMonitorsLocked(displayId, {});
895 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
896 sp<Connection> connection =
897 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000898 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700899 // This monitor could take more input. Drop all events preceding this
900 // event, so that gesture monitor could get a chance to receive the stream
901 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
902 "responsive gesture monitor that may handle the event",
903 mAwaitedFocusedApplication->getName().c_str());
904 return true;
905 }
906 }
907 }
908
909 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
910 // yet been processed by some connections, the dispatcher will wait for these motion
911 // events to be processed before dispatching the key event. This is because these motion events
912 // may cause a new window to be launched, which the user might expect to receive focus.
913 // To prevent waiting forever for such events, just send the key to the currently focused window
914 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
915 ALOGD("Received a new pointer down event, stop waiting for events to process and "
916 "just send the pending key event to the focused window.");
917 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700918 }
919 return false;
920}
921
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700922bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700923 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700924 mInboundQueue.push_back(std::move(newEntry));
925 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 traceInboundQueueLengthLocked();
927
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700928 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700929 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 // Optimize app switch latency.
931 // If the application takes too long to catch up then we drop all events preceding
932 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700933 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700935 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700936 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700937 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700942 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 mAppSwitchSawKeyDown = false;
944 needWake = true;
945 }
946 }
947 }
948 break;
949 }
950
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700951 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700952 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
953 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700954 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100958 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700959 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
960 break;
961 }
962 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800963 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700964 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800965 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
966 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700967 // nothing to do
968 break;
969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
971
972 return needWake;
973}
974
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700976 // Do not store sensor event in recent queue to avoid flooding the queue.
977 if (entry->type != EventEntry::Type::SENSOR) {
978 mRecentQueue.push_back(entry);
979 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700980 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983}
984
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700986 int32_t y, TouchState* touchState,
987 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800988 bool addPortalWindows,
989 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700990 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
991 LOG_ALWAYS_FATAL(
992 "Must provide a valid touch state if adding portal windows or outside targets");
993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700995 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800996 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +0800997 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +0800998 continue;
999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1001 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001002 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003
1004 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001005 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1006 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1007 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001009 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1011 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001012 if (addPortalWindows) {
1013 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001014 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001015 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001016 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 // Found window.
1020 return windowHandle;
1021 }
1022 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001023
Michael Wright44753b12020-07-08 13:48:11 +01001024 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001025 touchState->addOrUpdateWindow(windowHandle,
1026 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1027 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
1031 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001032 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033}
1034
Garfield Tane84e6f92019-08-29 17:28:41 -07001035std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001036 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001037 std::vector<TouchedMonitor> touchedMonitors;
1038
1039 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1040 addGestureMonitors(monitors, touchedMonitors);
1041 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1042 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1043 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001044 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1045 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001046 }
1047 return touchedMonitors;
1048}
1049
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001050void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 const char* reason;
1052 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001053 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 reason = "inbound event was dropped because the policy consumed it";
1058 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001059 case DropReason::DISABLED:
1060 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 ALOGI("Dropped event because input dispatch is disabled.");
1062 }
1063 reason = "inbound event was dropped because input dispatch is disabled";
1064 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001065 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001066 ALOGI("Dropped event because of pending overdue app switch.");
1067 reason = "inbound event was dropped because of pending overdue app switch";
1068 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 ALOGI("Dropped event because the current application is not responding and the user "
1071 "has started interacting with a different application.");
1072 reason = "inbound event was dropped because the current application is not responding "
1073 "and the user has started interacting with a different application";
1074 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001075 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 ALOGI("Dropped event because it is stale.");
1077 reason = "inbound event was dropped because it is stale";
1078 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001079 case DropReason::NO_POINTER_CAPTURE:
1080 ALOGI("Dropped event because there is no window with Pointer Capture.");
1081 reason = "inbound event was dropped because there is no window with Pointer Capture";
1082 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 case DropReason::NOT_DROPPED: {
1084 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 }
1088
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001089 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001090 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1092 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001095 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001096 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1097 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1099 synthesizeCancelationEventsForAllConnectionsLocked(options);
1100 } else {
1101 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1102 synthesizeCancelationEventsForAllConnectionsLocked(options);
1103 }
1104 break;
1105 }
Chris Yef59a2f42020-10-16 12:55:26 -07001106 case EventEntry::Type::SENSOR: {
1107 break;
1108 }
arthurhungb89ccb02020-12-30 16:19:01 +08001109 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1110 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001111 break;
1112 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001113 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001114 case EventEntry::Type::CONFIGURATION_CHANGED:
1115 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001116 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001117 break;
1118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 }
1120}
1121
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001122static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1124 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125}
1126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001127bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1128 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1129 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1130 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131}
1132
1133bool InputDispatcher::isAppSwitchPendingLocked() {
1134 return mAppSwitchDueTime != LONG_LONG_MAX;
1135}
1136
1137void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1138 mAppSwitchDueTime = LONG_LONG_MAX;
1139
1140#if DEBUG_APP_SWITCH
1141 if (handled) {
1142 ALOGD("App switch has arrived.");
1143 } else {
1144 ALOGD("App switch was abandoned.");
1145 }
1146#endif
1147}
1148
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001150 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151}
1152
1153bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001154 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 return false;
1156 }
1157
1158 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001159 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001160 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001162 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163
1164 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001165 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 return true;
1167}
1168
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001169void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1170 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171}
1172
1173void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001174 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001175 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001176 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 releaseInboundEventLocked(entry);
1178 }
1179 traceInboundQueueLengthLocked();
1180}
1181
1182void InputDispatcher::releasePendingEventLocked() {
1183 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001185 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 }
1187}
1188
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001189void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001191 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192#if DEBUG_DISPATCH_CYCLE
1193 ALOGD("Injected inbound event was dropped.");
1194#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001198 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 }
1200 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201}
1202
1203void InputDispatcher::resetKeyRepeatLocked() {
1204 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001205 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207}
1208
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1210 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211
Michael Wright2e732952014-09-24 13:26:59 -07001212 uint32_t policyFlags = entry->policyFlags &
1213 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 std::shared_ptr<KeyEntry> newEntry =
1216 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1217 entry->source, entry->displayId, policyFlags, entry->action,
1218 entry->flags, entry->keyCode, entry->scanCode,
1219 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001221 newEntry->syntheticRepeat = true;
1222 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001224 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225}
1226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231#endif
1232
1233 // Reset key repeating in case a keyboard device was added or removed or something.
1234 resetKeyRepeatLocked();
1235
1236 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001237 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1238 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001239 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001240 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 return true;
1242}
1243
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1245 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1248 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249#endif
1250
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001252 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 synthesizeCancelationEventsForAllConnectionsLocked(options);
1254 return true;
1255}
1256
Vishnu Nairad321cd2020-08-20 16:40:21 -07001257void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001258 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001259 if (mPendingEvent != nullptr) {
1260 // Move the pending event to the front of the queue. This will give the chance
1261 // for the pending event to get dispatched to the newly focused window
1262 mInboundQueue.push_front(mPendingEvent);
1263 mPendingEvent = nullptr;
1264 }
1265
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001266 std::unique_ptr<FocusEntry> focusEntry =
1267 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1268 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001269
1270 // This event should go to the front of the queue, but behind all other focus events
1271 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001272 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001273 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 [](const std::shared_ptr<EventEntry>& event) {
1275 return event->type == EventEntry::Type::FOCUS;
1276 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001277
1278 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001280}
1281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001283 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001284 if (channel == nullptr) {
1285 return; // Window has gone away
1286 }
1287 InputTarget target;
1288 target.inputChannel = channel;
1289 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1290 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001291 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1292 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001293 std::string reason = std::string("reason=").append(entry->reason);
1294 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001295 dispatchEventLocked(currentTime, entry, {target});
1296}
1297
Prabir Pradhan99987712020-11-10 18:43:05 -08001298void InputDispatcher::dispatchPointerCaptureChangedLocked(
1299 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1300 DropReason& dropReason) {
1301 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001302 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1303 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1304 }
1305 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001306 // Pointer capture was already forcefully disabled because of focus change.
1307 dropReason = DropReason::NOT_DROPPED;
1308 return;
1309 }
1310
1311 // Set drop reason for early returns
1312 dropReason = DropReason::NO_POINTER_CAPTURE;
1313
1314 sp<IBinder> token;
1315 if (entry->pointerCaptureEnabled) {
1316 // Enable Pointer Capture
1317 if (!mFocusedWindowRequestedPointerCapture) {
1318 // This can happen if a window requests capture and immediately releases capture.
1319 ALOGW("No window requested Pointer Capture.");
1320 return;
1321 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001322 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001323 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1324 mWindowTokenWithPointerCapture = token;
1325 } else {
1326 // Disable Pointer Capture
1327 token = mWindowTokenWithPointerCapture;
1328 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001329 if (mFocusedWindowRequestedPointerCapture) {
1330 mFocusedWindowRequestedPointerCapture = false;
1331 setPointerCaptureLocked(false);
1332 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001333 }
1334
1335 auto channel = getInputChannelLocked(token);
1336 if (channel == nullptr) {
1337 // Window has gone away, clean up Pointer Capture state.
1338 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001339 if (mFocusedWindowRequestedPointerCapture) {
1340 mFocusedWindowRequestedPointerCapture = false;
1341 setPointerCaptureLocked(false);
1342 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001343 return;
1344 }
1345 InputTarget target;
1346 target.inputChannel = channel;
1347 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1348 entry->dispatchInProgress = true;
1349 dispatchEventLocked(currentTime, entry, {target});
1350
1351 dropReason = DropReason::NOT_DROPPED;
1352}
1353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001355 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001357 if (!entry->dispatchInProgress) {
1358 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1359 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1360 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1361 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001362 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 // We have seen two identical key downs in a row which indicates that the device
1364 // driver is automatically generating key repeats itself. We take note of the
1365 // repeat here, but we disable our own next key repeat timer since it is clear that
1366 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001367 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1368 // Make sure we don't get key down from a different device. If a different
1369 // device Id has same key pressed down, the new device Id will replace the
1370 // current one to hold the key repeat with repeat count reset.
1371 // In the future when got a KEY_UP on the device id, drop it and do not
1372 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1374 resetKeyRepeatLocked();
1375 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1376 } else {
1377 // Not a repeat. Save key down state in case we do see a repeat later.
1378 resetKeyRepeatLocked();
1379 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1380 }
1381 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001382 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1383 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001384 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001385#if DEBUG_INBOUND_EVENT_DETAILS
1386 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1387#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 resetKeyRepeatLocked();
1390 }
1391
1392 if (entry->repeatCount == 1) {
1393 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1394 } else {
1395 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1396 }
1397
1398 entry->dispatchInProgress = true;
1399
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 }
1402
1403 // Handle case where the policy asked us to try again later last time.
1404 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1405 if (currentTime < entry->interceptKeyWakeupTime) {
1406 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1407 *nextWakeupTime = entry->interceptKeyWakeupTime;
1408 }
1409 return false; // wait until next wakeup
1410 }
1411 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1412 entry->interceptKeyWakeupTime = 0;
1413 }
1414
1415 // Give the policy a chance to intercept the key.
1416 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1417 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001418 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001419 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001420 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001421 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001422 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001424 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 return false; // wait for the command to run
1426 } else {
1427 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1428 }
1429 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001430 if (*dropReason == DropReason::NOT_DROPPED) {
1431 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 }
1433 }
1434
1435 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001436 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001437 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001438 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1439 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001440 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 return true;
1442 }
1443
1444 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001445 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001446 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001447 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001448 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 return false;
1450 }
1451
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001453 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 return true;
1455 }
1456
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001457 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001458 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459
1460 // Dispatch the key.
1461 dispatchEventLocked(currentTime, entry, inputTargets);
1462 return true;
1463}
1464
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001465void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001467 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1469 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001470 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1471 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1472 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473#endif
1474}
1475
Chris Yef59a2f42020-10-16 12:55:26 -07001476void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1477 mLock.unlock();
1478
1479 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1480 if (entry->accuracyChanged) {
1481 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1482 }
1483 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1484 entry->hwTimestamp, entry->values);
1485 mLock.lock();
1486}
1487
1488void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1489 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1490#if DEBUG_OUTBOUND_EVENT_DETAILS
1491 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1492 "source=0x%x, sensorType=%s",
1493 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001494 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001495#endif
1496 std::unique_ptr<CommandEntry> commandEntry =
1497 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1498 commandEntry->sensorEntry = entry;
1499 postCommandLocked(std::move(commandEntry));
1500}
1501
1502bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1503#if DEBUG_OUTBOUND_EVENT_DETAILS
1504 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1505 NamedEnum::string(sensorType).c_str());
1506#endif
1507 { // acquire lock
1508 std::scoped_lock _l(mLock);
1509
1510 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1511 std::shared_ptr<EventEntry> entry = *it;
1512 if (entry->type == EventEntry::Type::SENSOR) {
1513 it = mInboundQueue.erase(it);
1514 releaseInboundEventLocked(entry);
1515 }
1516 }
1517 }
1518 return true;
1519}
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001523 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001525 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 entry->dispatchInProgress = true;
1527
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001528 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530
1531 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001532 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001533 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001534 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1535 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 return true;
1537 }
1538
1539 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1540
1541 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001542 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543
1544 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001545 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 if (isPointerEvent) {
1547 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 } else {
1552 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001553 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001554 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 return false;
1558 }
1559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001561 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001562 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1563 return true;
1564 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001566 CancelationOptions::Mode mode(isPointerEvent
1567 ? CancelationOptions::CANCEL_POINTER_EVENTS
1568 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1569 CancelationOptions options(mode, "input event injection failed");
1570 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 return true;
1572 }
1573
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001574 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001577 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001578 std::unordered_map<int32_t, TouchState>::iterator it =
1579 mTouchStatesByDisplay.find(entry->displayId);
1580 if (it != mTouchStatesByDisplay.end()) {
1581 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001582 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001583 // The event has gone through these portal windows, so we add monitoring targets of
1584 // the corresponding displays as well.
1585 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001586 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001587 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001588 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001589 }
1590 }
1591 }
1592 }
1593
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 // Dispatch the motion.
1595 if (conflictingPointerActions) {
1596 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 synthesizeCancelationEventsForAllConnectionsLocked(options);
1599 }
1600 dispatchEventLocked(currentTime, entry, inputTargets);
1601 return true;
1602}
1603
arthurhungb89ccb02020-12-30 16:19:01 +08001604void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1605 bool isExiting, const MotionEntry& motionEntry) {
1606 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1607 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1608 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1609 PointerCoords pointerCoords;
1610 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1611 pointerCoords.transform(windowHandle->getInfo()->transform);
1612
1613 std::unique_ptr<DragEntry> dragEntry =
1614 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1615 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1616 pointerCoords.getY());
1617
1618 enqueueInboundEventLocked(std::move(dragEntry));
1619}
1620
1621void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1622 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1623 if (channel == nullptr) {
1624 return; // Window has gone away
1625 }
1626 InputTarget target;
1627 target.inputChannel = channel;
1628 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1629 entry->dispatchInProgress = true;
1630 dispatchEventLocked(currentTime, entry, {target});
1631}
1632
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001635 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001636 ", policyFlags=0x%x, "
1637 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1638 "metaState=0x%x, buttonState=0x%x,"
1639 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1641 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1642 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 "x=%f, y=%f, pressure=%f, size=%f, "
1647 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1648 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1650 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1651 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1652 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1653 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1654 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1655 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1656 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1657 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1658 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 }
1660#endif
1661}
1662
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001663void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1664 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001666 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667#if DEBUG_DISPATCH_CYCLE
1668 ALOGD("dispatchEventToCurrentInputTargets");
1669#endif
1670
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001671 updateInteractionTokensLocked(*eventEntry, inputTargets);
1672
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1674
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001677 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001678 sp<Connection> connection =
1679 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001680 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001681 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001683 if (DEBUG_FOCUS) {
1684 ALOGD("Dropping event delivery to target with channel '%s' because it "
1685 "is no longer registered with the input dispatcher.",
1686 inputTarget.inputChannel->getName().c_str());
1687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 }
1689 }
1690}
1691
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001692void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1693 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1694 // If the policy decides to close the app, we will get a channel removal event via
1695 // unregisterInputChannel, and will clean up the connection that way. We are already not
1696 // sending new pointers to the connection when it blocked, but focused events will continue to
1697 // pile up.
1698 ALOGW("Canceling events for %s because it is unresponsive",
1699 connection->inputChannel->getName().c_str());
1700 if (connection->status == Connection::STATUS_NORMAL) {
1701 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1702 "application not responding");
1703 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 }
1705}
1706
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001707void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001708 if (DEBUG_FOCUS) {
1709 ALOGD("Resetting ANR timeouts.");
1710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711
1712 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001714 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715}
1716
Tiger Huang721e26f2018-07-24 22:26:19 +08001717/**
1718 * Get the display id that the given event should go to. If this event specifies a valid display id,
1719 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1720 * Focused display is the display that the user most recently interacted with.
1721 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001722int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001723 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001724 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001725 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001726 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1727 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 break;
1729 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001730 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001731 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1732 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001733 break;
1734 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001735 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001736 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001737 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001738 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001739 case EventEntry::Type::SENSOR:
1740 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001741 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001742 return ADISPLAY_ID_NONE;
1743 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001744 }
1745 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1746}
1747
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001748bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1749 const char* focusedWindowName) {
1750 if (mAnrTracker.empty()) {
1751 // already processed all events that we waited for
1752 mKeyIsWaitingForEventsTimeout = std::nullopt;
1753 return false;
1754 }
1755
1756 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1757 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001758 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001759 mKeyIsWaitingForEventsTimeout = currentTime +
1760 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1761 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001762 return true;
1763 }
1764
1765 // We still have pending events, and already started the timer
1766 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1767 return true; // Still waiting
1768 }
1769
1770 // Waited too long, and some connection still hasn't processed all motions
1771 // Just send the key to the focused window
1772 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1773 focusedWindowName);
1774 mKeyIsWaitingForEventsTimeout = std::nullopt;
1775 return false;
1776}
1777
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001778InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1779 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1780 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001781 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
Tiger Huang721e26f2018-07-24 22:26:19 +08001783 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001784 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001785 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001786 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1787
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 // If there is no currently focused window and no focused application
1789 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001790 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1791 ALOGI("Dropping %s event because there is no focused window or focused application in "
1792 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001793 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001794 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
1796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1798 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1799 // start interacting with another application via touch (app switch). This code can be removed
1800 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1801 // an app is expected to have a focused window.
1802 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1803 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1804 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001805 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1806 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1807 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001808 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001809 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001810 ALOGW("Waiting because no window has focus but %s may eventually add a "
1811 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001812 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001813 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001814 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001815 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1816 // Already raised ANR. Drop the event
1817 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001818 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001819 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001820 } else {
1821 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001823 }
1824 }
1825
1826 // we have a valid, non-null focused window
1827 resetNoFocusedWindowTimeoutLocked();
1828
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 }
1833
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001834 if (focusedWindowHandle->getInfo()->paused) {
1835 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001836 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001837 }
1838
1839 // If the event is a key event, then we must wait for all previous events to
1840 // complete before delivering it because previous events may have the
1841 // side-effect of transferring focus to a different window and we want to
1842 // ensure that the following keys are sent to the new window.
1843 //
1844 // Suppose the user touches a button in a window then immediately presses "A".
1845 // If the button causes a pop-up window to appear then we want to ensure that
1846 // the "A" key is delivered to the new pop-up window. This is because users
1847 // often anticipate pending UI changes when typing on a keyboard.
1848 // To obtain this behavior, we must serialize key events with respect to all
1849 // prior input events.
1850 if (entry.type == EventEntry::Type::KEY) {
1851 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1852 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001853 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 }
1856
1857 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001858 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001859 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1860 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861
1862 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864}
1865
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001866/**
1867 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1868 * that are currently unresponsive.
1869 */
1870std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1871 const std::vector<TouchedMonitor>& monitors) const {
1872 std::vector<TouchedMonitor> responsiveMonitors;
1873 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1874 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1875 sp<Connection> connection = getConnectionLocked(
1876 monitor.monitor.inputChannel->getConnectionToken());
1877 if (connection == nullptr) {
1878 ALOGE("Could not find connection for monitor %s",
1879 monitor.monitor.inputChannel->getName().c_str());
1880 return false;
1881 }
1882 if (!connection->responsive) {
1883 ALOGW("Unresponsive monitor %s will not get the new gesture",
1884 connection->inputChannel->getName().c_str());
1885 return false;
1886 }
1887 return true;
1888 });
1889 return responsiveMonitors;
1890}
1891
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1893 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1894 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001895 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 enum InjectionPermission {
1897 INJECTION_PERMISSION_UNKNOWN,
1898 INJECTION_PERMISSION_GRANTED,
1899 INJECTION_PERMISSION_DENIED
1900 };
1901
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 // For security reasons, we defer updating the touch state until we are sure that
1903 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001904 int32_t displayId = entry.displayId;
1905 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1907
1908 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001911 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1912 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001914 // Copy current touch state into tempTouchState.
1915 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1916 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001917 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001918 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001919 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1920 mTouchStatesByDisplay.find(displayId);
1921 if (oldStateIt != mTouchStatesByDisplay.end()) {
1922 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001923 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001924 }
1925
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001926 bool isSplit = tempTouchState.split;
1927 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1928 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1929 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001930 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1931 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1932 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1933 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1934 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001935 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 bool wrongDevice = false;
1937 if (newGesture) {
1938 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001940 ALOGI("Dropping event because a pointer for a different device is already down "
1941 "in display %" PRId32,
1942 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001943 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001944 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 switchedDevice = false;
1946 wrongDevice = true;
1947 goto Failed;
1948 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001949 tempTouchState.reset();
1950 tempTouchState.down = down;
1951 tempTouchState.deviceId = entry.deviceId;
1952 tempTouchState.source = entry.source;
1953 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001955 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001956 ALOGI("Dropping move event because a pointer for a different device is already active "
1957 "in display %" PRId32,
1958 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001959 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001960 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001961 switchedDevice = false;
1962 wrongDevice = true;
1963 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965
1966 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1967 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1968
Garfield Tan00f511d2019-06-12 16:55:40 -07001969 int32_t x;
1970 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001972 // Always dispatch mouse events to cursor position.
1973 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001974 x = int32_t(entry.xCursorPosition);
1975 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001976 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001977 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1978 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001979 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001980 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001981 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001982 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1983 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001984
1985 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001987 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001990 if (newTouchedWindowHandle != nullptr &&
1991 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001992 // New window supports splitting, but we should never split mouse events.
1993 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 } else if (isSplit) {
1995 // New window does not support splitting but we have already split events.
1996 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001997 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
1999
2000 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002001 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002004 }
2005
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002006 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2007 ALOGI("Not sending touch event to %s because it is paused",
2008 newTouchedWindowHandle->getName().c_str());
2009 newTouchedWindowHandle = nullptr;
2010 }
2011
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002012 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002014 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2015 if (!isResponsive) {
2016 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2018 newTouchedWindowHandle = nullptr;
2019 }
2020 }
2021
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002022 // Drop events that can't be trusted due to occlusion
2023 if (newTouchedWindowHandle != nullptr &&
2024 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2025 TouchOcclusionInfo occlusionInfo =
2026 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002027 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002028 if (DEBUG_TOUCH_OCCLUSION) {
2029 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2030 for (const auto& log : occlusionInfo.debugInfo) {
2031 ALOGD("%s", log.c_str());
2032 }
2033 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002034 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2035 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2036 ALOGW("Dropping untrusted touch event due to %s/%d",
2037 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2038 newTouchedWindowHandle = nullptr;
2039 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002040 }
2041 }
2042
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002043 // Also don't send the new touch event to unresponsive gesture monitors
2044 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2045
Michael Wright3dd60e22019-03-27 22:06:44 +00002046 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2047 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002048 "(%d, %d) in display %" PRId32 ".",
2049 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002050 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002051 goto Failed;
2052 }
2053
2054 if (newTouchedWindowHandle != nullptr) {
2055 // Set target flags.
2056 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2057 if (isSplit) {
2058 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002060 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2061 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2062 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2063 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2064 }
2065
2066 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002067 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2068 newHoverWindowHandle = nullptr;
2069 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002070 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002071 }
2072
2073 // Update the temporary touch state.
2074 BitSet32 pointerIds;
2075 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002076 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002077 pointerIds.markBit(pointerId);
2078 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002079 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002082 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 } else {
2084 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2085
2086 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002088 if (DEBUG_FOCUS) {
2089 ALOGD("Dropping event because the pointer is not down or we previously "
2090 "dropped the pointer down event in display %" PRId32,
2091 displayId);
2092 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002093 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 goto Failed;
2095 }
2096
arthurhung6d4bed92021-03-17 11:59:33 +08002097 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002098
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002100 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002101 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002102 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2103 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104
2105 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002106 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002107 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002108 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2109 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002110 if (DEBUG_FOCUS) {
2111 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2112 oldTouchedWindowHandle->getName().c_str(),
2113 newTouchedWindowHandle->getName().c_str(), displayId);
2114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002116 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2117 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2118 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119
2120 // Make a slippery entrance into the new window.
2121 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2122 isSplit = true;
2123 }
2124
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002125 int32_t targetFlags =
2126 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 if (isSplit) {
2128 targetFlags |= InputTarget::FLAG_SPLIT;
2129 }
2130 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2131 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002132 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2133 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 }
2135
2136 BitSet32 pointerIds;
2137 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002138 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002140 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 }
2142 }
2143 }
2144
2145 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002146 // Let the previous window know that the hover sequence is over, unless we already did it
2147 // when dispatching it as is to newTouchedWindowHandle.
2148 if (mLastHoverWindowHandle != nullptr &&
2149 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2150 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151#if DEBUG_HOVER
2152 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2156 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
2158
Garfield Tandf26e862020-07-01 20:18:19 -07002159 // Let the new window know that the hover sequence is starting, unless we already did it
2160 // when dispatching it as is to newTouchedWindowHandle.
2161 if (newHoverWindowHandle != nullptr &&
2162 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2163 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164#if DEBUG_HOVER
2165 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2169 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2170 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 }
2172 }
2173
2174 // Check permission to inject into all touched foreground windows and ensure there
2175 // is at least one touched foreground window.
2176 {
2177 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2180 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002181 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002182 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 injectionPermission = INJECTION_PERMISSION_DENIED;
2184 goto Failed;
2185 }
2186 }
2187 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002189 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002190 ALOGI("Dropping event because there is no touched foreground window in display "
2191 "%" PRId32 " or gesture monitor to receive it.",
2192 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002193 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 goto Failed;
2195 }
2196
2197 // Permission granted to injection into all touched foreground windows.
2198 injectionPermission = INJECTION_PERMISSION_GRANTED;
2199 }
2200
2201 // Check whether windows listening for outside touches are owned by the same UID. If it is
2202 // set the policy flag that we will not reveal coordinate information to this window.
2203 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2204 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002205 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002206 if (foregroundWindowHandle) {
2207 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002208 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002209 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2210 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2211 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2213 InputTarget::FLAG_ZERO_COORDS,
2214 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217 }
2218 }
2219 }
2220
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 // If this is the first pointer going down and the touched window has a wallpaper
2222 // then also add the touched wallpaper windows so they are locked in for the duration
2223 // of the touch gesture.
2224 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2225 // engine only supports touch events. We would need to add a mechanism similar
2226 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2227 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2228 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002229 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002230 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002231 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002232 getWindowHandlesLocked(displayId);
2233 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002235 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002236 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002238 .addOrUpdateWindow(windowHandle,
2239 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2240 InputTarget::
2241 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2242 InputTarget::FLAG_DISPATCH_AS_IS,
2243 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
2245 }
2246 }
2247 }
2248
2249 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002250 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 }
2256
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002257 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002258 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 }
2261
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 // Drop the outside or hover touch windows since we will not care about them
2263 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002264 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265
2266Failed:
2267 // Check injection permission once and for all.
2268 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002269 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 injectionPermission = INJECTION_PERMISSION_GRANTED;
2271 } else {
2272 injectionPermission = INJECTION_PERMISSION_DENIED;
2273 }
2274 }
2275
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002276 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2277 return injectionResult;
2278 }
2279
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002281 if (!wrongDevice) {
2282 if (switchedDevice) {
2283 if (DEBUG_FOCUS) {
2284 ALOGD("Conflicting pointer actions: Switched to a different device.");
2285 }
2286 *outConflictingPointerActions = true;
2287 }
2288
2289 if (isHoverAction) {
2290 // Started hovering, therefore no longer down.
2291 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002292 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002293 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2294 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 *outConflictingPointerActions = true;
2297 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002298 tempTouchState.reset();
2299 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2300 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2301 tempTouchState.deviceId = entry.deviceId;
2302 tempTouchState.source = entry.source;
2303 tempTouchState.displayId = displayId;
2304 }
2305 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2306 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2307 // All pointers up or canceled.
2308 tempTouchState.reset();
2309 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2310 // First pointer went down.
2311 if (oldState && oldState->down) {
2312 if (DEBUG_FOCUS) {
2313 ALOGD("Conflicting pointer actions: Down received while already down.");
2314 }
2315 *outConflictingPointerActions = true;
2316 }
2317 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2318 // One pointer went up.
2319 if (isSplit) {
2320 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2321 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002323 for (size_t i = 0; i < tempTouchState.windows.size();) {
2324 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2325 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2326 touchedWindow.pointerIds.clearBit(pointerId);
2327 if (touchedWindow.pointerIds.isEmpty()) {
2328 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2329 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002332 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002334 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002335 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002336
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002337 // Save changes unless the action was scroll in which case the temporary touch
2338 // state was only valid for this one action.
2339 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2340 if (tempTouchState.displayId >= 0) {
2341 mTouchStatesByDisplay[displayId] = tempTouchState;
2342 } else {
2343 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002347 // Update hover state.
2348 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 }
2350
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 return injectionResult;
2352}
2353
arthurhung6d4bed92021-03-17 11:59:33 +08002354void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2355 const sp<InputWindowHandle> dropWindow =
2356 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2357 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2358 true /*ignoreDragWindow*/);
2359 if (dropWindow) {
2360 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2361 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002362 } else {
2363 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002364 }
2365 mDragState.reset();
2366}
2367
2368void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2369 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002370 return;
2371 }
2372
arthurhung6d4bed92021-03-17 11:59:33 +08002373 if (!mDragState->isStartDrag) {
2374 mDragState->isStartDrag = true;
2375 mDragState->isStylusButtonDownAtStart =
2376 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2377 }
2378
arthurhungb89ccb02020-12-30 16:19:01 +08002379 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2380 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2381 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2382 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002383 // Handle the special case : stylus button no longer pressed.
2384 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2385 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2386 finishDragAndDrop(entry.displayId, x, y);
2387 return;
2388 }
2389
arthurhungb89ccb02020-12-30 16:19:01 +08002390 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002391 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002392 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2393 true /*ignoreDragWindow*/);
2394 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002395 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2396 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2397 if (mDragState->dragHoverWindowHandle != nullptr) {
2398 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2399 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002400 }
arthurhung6d4bed92021-03-17 11:59:33 +08002401 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002402 }
2403 // enqueue drag location if needed.
2404 if (hoverWindowHandle != nullptr) {
2405 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2406 }
arthurhung6d4bed92021-03-17 11:59:33 +08002407 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2408 finishDragAndDrop(entry.displayId, x, y);
2409 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002410 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002411 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002412 }
2413}
2414
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002416 int32_t targetFlags, BitSet32 pointerIds,
2417 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002418 std::vector<InputTarget>::iterator it =
2419 std::find_if(inputTargets.begin(), inputTargets.end(),
2420 [&windowHandle](const InputTarget& inputTarget) {
2421 return inputTarget.inputChannel->getConnectionToken() ==
2422 windowHandle->getToken();
2423 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002424
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002425 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002426
2427 if (it == inputTargets.end()) {
2428 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002429 std::shared_ptr<InputChannel> inputChannel =
2430 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002431 if (inputChannel == nullptr) {
2432 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2433 return;
2434 }
2435 inputTarget.inputChannel = inputChannel;
2436 inputTarget.flags = targetFlags;
2437 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002438 inputTarget.displaySize =
2439 vec2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002440 inputTargets.push_back(inputTarget);
2441 it = inputTargets.end() - 1;
2442 }
2443
2444 ALOG_ASSERT(it->flags == targetFlags);
2445 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2446
chaviw1ff3d1e2020-07-01 15:53:47 -07002447 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448}
2449
Michael Wright3dd60e22019-03-27 22:06:44 +00002450void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002451 int32_t displayId, float xOffset,
2452 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002453 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2454 mGlobalMonitorsByDisplay.find(displayId);
2455
2456 if (it != mGlobalMonitorsByDisplay.end()) {
2457 const std::vector<Monitor>& monitors = it->second;
2458 for (const Monitor& monitor : monitors) {
2459 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 }
2462}
2463
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002464void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2465 float yOffset,
2466 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002467 InputTarget target;
2468 target.inputChannel = monitor.inputChannel;
2469 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002470 ui::Transform t;
2471 t.set(xOffset, yOffset);
2472 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002473 inputTargets.push_back(target);
2474}
2475
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002477 const InjectionState* injectionState) {
2478 if (injectionState &&
2479 (windowHandle == nullptr ||
2480 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2481 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002482 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002484 "owned by uid %d",
2485 injectionState->injectorPid, injectionState->injectorUid,
2486 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 } else {
2488 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
2491 return false;
2492 }
2493 return true;
2494}
2495
Robert Carrc9bf1d32020-04-13 17:21:08 -07002496/**
2497 * Indicate whether one window handle should be considered as obscuring
2498 * another window handle. We only check a few preconditions. Actually
2499 * checking the bounds is left to the caller.
2500 */
2501static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2502 const sp<InputWindowHandle>& otherHandle) {
2503 // Compare by token so cloned layers aren't counted
2504 if (haveSameToken(windowHandle, otherHandle)) {
2505 return false;
2506 }
2507 auto info = windowHandle->getInfo();
2508 auto otherInfo = otherHandle->getInfo();
2509 if (!otherInfo->visible) {
2510 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002511 } else if (otherInfo->alpha == 0 &&
2512 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2513 // Those act as if they were invisible, so we don't need to flag them.
2514 // We do want to potentially flag touchable windows even if they have 0
2515 // opacity, since they can consume touches and alter the effects of the
2516 // user interaction (eg. apps that rely on
2517 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2518 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2519 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002520 } else if (info->ownerUid == otherInfo->ownerUid) {
2521 // If ownerUid is the same we don't generate occlusion events as there
2522 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002523 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002524 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002525 return false;
2526 } else if (otherInfo->displayId != info->displayId) {
2527 return false;
2528 }
2529 return true;
2530}
2531
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002532/**
2533 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2534 * untrusted, one should check:
2535 *
2536 * 1. If result.hasBlockingOcclusion is true.
2537 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2538 * BLOCK_UNTRUSTED.
2539 *
2540 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2541 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2542 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2543 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2544 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2545 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2546 *
2547 * If neither of those is true, then it means the touch can be allowed.
2548 */
2549InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2550 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002551 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2552 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002553 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2554 TouchOcclusionInfo info;
2555 info.hasBlockingOcclusion = false;
2556 info.obscuringOpacity = 0;
2557 info.obscuringUid = -1;
2558 std::map<int32_t, float> opacityByUid;
2559 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2560 if (windowHandle == otherHandle) {
2561 break; // All future windows are below us. Exit early.
2562 }
2563 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002564 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2565 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002566 if (DEBUG_TOUCH_OCCLUSION) {
2567 info.debugInfo.push_back(
2568 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2569 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002570 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2571 // we perform the checks below to see if the touch can be propagated or not based on the
2572 // window's touch occlusion mode
2573 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2574 info.hasBlockingOcclusion = true;
2575 info.obscuringUid = otherInfo->ownerUid;
2576 info.obscuringPackage = otherInfo->packageName;
2577 break;
2578 }
2579 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2580 uint32_t uid = otherInfo->ownerUid;
2581 float opacity =
2582 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2583 // Given windows A and B:
2584 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2585 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2586 opacityByUid[uid] = opacity;
2587 if (opacity > info.obscuringOpacity) {
2588 info.obscuringOpacity = opacity;
2589 info.obscuringUid = uid;
2590 info.obscuringPackage = otherInfo->packageName;
2591 }
2592 }
2593 }
2594 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002595 if (DEBUG_TOUCH_OCCLUSION) {
2596 info.debugInfo.push_back(
2597 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2598 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002599 return info;
2600}
2601
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002602std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2603 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002604 return StringPrintf(INDENT2
2605 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2606 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2607 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2608 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002609 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002610 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002611 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002612 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2613 info->frameTop, info->frameRight, info->frameBottom,
2614 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002615 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2616 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2617 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002618}
2619
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002620bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2621 if (occlusionInfo.hasBlockingOcclusion) {
2622 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2623 occlusionInfo.obscuringUid);
2624 return false;
2625 }
2626 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2627 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2628 "%.2f, maximum allowed = %.2f)",
2629 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2630 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2631 return false;
2632 }
2633 return true;
2634}
2635
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002636bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2637 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002639 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002640 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002641 if (windowHandle == otherHandle) {
2642 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002645 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002646 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 return true;
2648 }
2649 }
2650 return false;
2651}
2652
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002653bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2654 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002655 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002656 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002657 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002658 if (windowHandle == otherHandle) {
2659 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002660 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002661 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002662 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002663 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002664 return true;
2665 }
2666 }
2667 return false;
2668}
2669
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002670std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002671 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002673 if (applicationHandle != nullptr) {
2674 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002675 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 } else {
2677 return applicationHandle->getName();
2678 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002679 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002680 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002682 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 }
2684}
2685
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002686void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002687 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002688 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2689 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002690 // Focus or pointer capture changed events are passed to apps, but do not represent user
2691 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002692 return;
2693 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002694 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002695 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002696 if (focusedWindowHandle != nullptr) {
2697 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002698 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002700 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701#endif
2702 return;
2703 }
2704 }
2705
2706 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002707 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002708 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002709 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2710 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 return;
2712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002714 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 eventType = USER_ACTIVITY_EVENT_TOUCH;
2716 }
2717 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002719 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002720 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2721 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 return;
2723 }
2724 eventType = USER_ACTIVITY_EVENT_BUTTON;
2725 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002727 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002728 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002729 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002730 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002731 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2732 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002733 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002734 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002735 break;
2736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 }
2738
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002739 std::unique_ptr<CommandEntry> commandEntry =
2740 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002741 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002743 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002744 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745}
2746
2747void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002748 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002749 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002750 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002751 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002753 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002754 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002755 ATRACE_NAME(message.c_str());
2756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757#if DEBUG_DISPATCH_CYCLE
2758 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002759 "globalScaleFactor=%f, pointerIds=0x%x %s",
2760 connection->getInputChannelName().c_str(), inputTarget.flags,
2761 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2762 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763#endif
2764
2765 // Skip this event if the connection status is not normal.
2766 // We don't want to enqueue additional outbound events if the connection is broken.
2767 if (connection->status != Connection::STATUS_NORMAL) {
2768#if DEBUG_DISPATCH_CYCLE
2769 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002770 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771#endif
2772 return;
2773 }
2774
2775 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002776 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2777 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2778 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002779 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002781 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002782 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002783 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002784 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 if (!splitMotionEntry) {
2786 return; // split event was dropped
2787 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002788 if (DEBUG_FOCUS) {
2789 ALOGD("channel '%s' ~ Split motion event.",
2790 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002791 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002792 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002793 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2794 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 return;
2796 }
2797 }
2798
2799 // Not splitting. Enqueue dispatch entries for the event as is.
2800 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2801}
2802
2803void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002804 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002805 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002806 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002807 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002809 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002810 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002811 ATRACE_NAME(message.c_str());
2812 }
2813
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002814 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815
2816 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002817 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002819 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002820 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002821 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002822 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002823 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002826 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829
2830 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002831 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 startDispatchCycleLocked(currentTime, connection);
2833 }
2834}
2835
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836void InputDispatcher::enqueueDispatchEntryLocked(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,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002839 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002840 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2842 connection->getInputChannelName().c_str(),
2843 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002844 ATRACE_NAME(message.c_str());
2845 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002846 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 if (!(inputTargetFlags & dispatchMode)) {
2848 return;
2849 }
2850 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2851
2852 // This is a new event.
2853 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002854 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002855 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002857 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2858 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002859 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002861 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002862 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002863 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002864 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002865 dispatchEntry->resolvedAction = keyEntry.action;
2866 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002868 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2869 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2872 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002874 return; // skip the inconsistent event
2875 }
2876 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002879 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002880 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002881 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2882 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2883 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2884 static_cast<int32_t>(IdGenerator::Source::OTHER);
2885 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2887 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2888 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2889 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2890 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2891 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2892 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2893 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2894 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2895 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2896 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002897 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002898 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 }
2900 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002901 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2902 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2905 "event",
2906 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002908 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2909 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002913 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2915 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2916 }
2917 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2918 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2922 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2925 "event",
2926 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 return; // skip the inconsistent event
2929 }
2930
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002931 dispatchEntry->resolvedEventId =
2932 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2933 ? mIdGenerator.nextId()
2934 : motionEntry.id;
2935 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2936 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2937 ") to MotionEvent(id=0x%" PRIx32 ").",
2938 motionEntry.id, dispatchEntry->resolvedEventId);
2939 ATRACE_NAME(message.c_str());
2940 }
2941
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002942 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2943 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2944 // Skip reporting pointer down outside focus to the policy.
2945 break;
2946 }
2947
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002949 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950
2951 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002953 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002954 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2955 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002956 break;
2957 }
Chris Yef59a2f42020-10-16 12:55:26 -07002958 case EventEntry::Type::SENSOR: {
2959 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2960 break;
2961 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002962 case EventEntry::Type::CONFIGURATION_CHANGED:
2963 case EventEntry::Type::DEVICE_RESET: {
2964 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002965 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002966 break;
2967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 }
2969
2970 // Remember that we are waiting for this dispatch to complete.
2971 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002972 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
2974
2975 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002976 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002977 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002978}
2979
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002980/**
2981 * This function is purely for debugging. It helps us understand where the user interaction
2982 * was taking place. For example, if user is touching launcher, we will see a log that user
2983 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2984 * We will see both launcher and wallpaper in that list.
2985 * Once the interaction with a particular set of connections starts, no new logs will be printed
2986 * until the set of interacted connections changes.
2987 *
2988 * The following items are skipped, to reduce the logspam:
2989 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2990 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2991 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2992 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2993 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002994 */
2995void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2996 const std::vector<InputTarget>& targets) {
2997 // Skip ACTION_UP events, and all events other than keys and motions
2998 if (entry.type == EventEntry::Type::KEY) {
2999 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3000 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3001 return;
3002 }
3003 } else if (entry.type == EventEntry::Type::MOTION) {
3004 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3005 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3006 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3007 return;
3008 }
3009 } else {
3010 return; // Not a key or a motion
3011 }
3012
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003013 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003014 std::vector<sp<Connection>> newConnections;
3015 for (const InputTarget& target : targets) {
3016 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3017 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3018 continue; // Skip windows that receive ACTION_OUTSIDE
3019 }
3020
3021 sp<IBinder> token = target.inputChannel->getConnectionToken();
3022 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003023 if (connection == nullptr) {
3024 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003025 }
3026 newConnectionTokens.insert(std::move(token));
3027 newConnections.emplace_back(connection);
3028 }
3029 if (newConnectionTokens == mInteractionConnectionTokens) {
3030 return; // no change
3031 }
3032 mInteractionConnectionTokens = newConnectionTokens;
3033
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003034 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003035 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003036 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003037 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003038 std::string message = "Interaction with: " + targetList;
3039 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003040 message += "<none>";
3041 }
3042 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3043}
3044
chaviwfd6d3512019-03-25 13:23:49 -07003045void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003046 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003047 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003048 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3049 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003050 return;
3051 }
3052
Vishnu Nairc519ff72021-01-21 08:23:08 -08003053 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003054 if (focusedToken == token) {
3055 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003056 return;
3057 }
3058
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003059 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3060 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003061 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003062 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063}
3064
3065void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003067 if (ATRACE_ENABLED()) {
3068 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003070 ATRACE_NAME(message.c_str());
3071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074#endif
3075
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003076 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3077 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003079 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003080 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003081 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
3083 // Publish the event.
3084 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003085 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3086 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003087 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003088 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3089 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003092 status = connection->inputPublisher
3093 .publishKeyEvent(dispatchEntry->seq,
3094 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3095 keyEntry.source, keyEntry.displayId,
3096 std::move(hmac), dispatchEntry->resolvedAction,
3097 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3098 keyEntry.scanCode, keyEntry.metaState,
3099 keyEntry.repeatCount, keyEntry.downTime,
3100 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102 }
3103
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003104 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109
chaviw82357092020-01-28 13:13:06 -08003110 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003111 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3113 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003114 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003115 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3116 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003117 // Don't apply window scale here since we don't want scale to affect raw
3118 // coordinates. The scale will be sent back to the client and applied
3119 // later when requesting relative coordinates.
3120 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3121 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 }
3123 usingCoords = scaledCoords;
3124 }
3125 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 // We don't want the dispatch target to know.
3127 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003128 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 scaledCoords[i].clear();
3130 }
3131 usingCoords = scaledCoords;
3132 }
3133 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003134
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003135 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136
3137 // Publish the motion event.
3138 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003139 .publishMotionEvent(dispatchEntry->seq,
3140 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003141 motionEntry.deviceId, motionEntry.source,
3142 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003143 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003144 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003146 motionEntry.edgeFlags, motionEntry.metaState,
3147 motionEntry.buttonState,
3148 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003149 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003150 motionEntry.xPrecision, motionEntry.yPrecision,
3151 motionEntry.xCursorPosition,
3152 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003153 dispatchEntry->displaySize.x,
3154 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003155 motionEntry.downTime, motionEntry.eventTime,
3156 motionEntry.pointerCount,
3157 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 break;
3159 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003160
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003161 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003163 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 focusEntry.id,
3165 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003166 mInTouchMode);
3167 break;
3168 }
3169
Prabir Pradhan99987712020-11-10 18:43:05 -08003170 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3171 const auto& captureEntry =
3172 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3173 status = connection->inputPublisher
3174 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3175 captureEntry.pointerCaptureEnabled);
3176 break;
3177 }
3178
arthurhungb89ccb02020-12-30 16:19:01 +08003179 case EventEntry::Type::DRAG: {
3180 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3181 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3182 dragEntry.id, dragEntry.x,
3183 dragEntry.y,
3184 dragEntry.isExiting);
3185 break;
3186 }
3187
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003188 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003189 case EventEntry::Type::DEVICE_RESET:
3190 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003191 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003192 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 }
3196
3197 // Check the result.
3198 if (status) {
3199 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003200 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 "This is unexpected because the wait queue is empty, so the pipe "
3203 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003204 "event to it, status=%s(%d)",
3205 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3206 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3208 } else {
3209 // Pipe is full and we are waiting for the app to finish process some events
3210 // before sending more events to it.
3211#if DEBUG_DISPATCH_CYCLE
3212 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 "waiting for the application to catch up",
3214 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 }
3217 } else {
3218 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003219 "status=%s(%d)",
3220 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3221 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3223 }
3224 return;
3225 }
3226
3227 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003228 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3229 connection->outboundQueue.end(),
3230 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003231 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003232 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003233 if (connection->responsive) {
3234 mAnrTracker.insert(dispatchEntry->timeoutTime,
3235 connection->inputChannel->getConnectionToken());
3236 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003237 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 }
3239}
3240
chaviw09c8d2d2020-08-24 15:48:26 -07003241std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3242 size_t size;
3243 switch (event.type) {
3244 case VerifiedInputEvent::Type::KEY: {
3245 size = sizeof(VerifiedKeyEvent);
3246 break;
3247 }
3248 case VerifiedInputEvent::Type::MOTION: {
3249 size = sizeof(VerifiedMotionEvent);
3250 break;
3251 }
3252 }
3253 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3254 return mHmacKeyManager.sign(start, size);
3255}
3256
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003257const std::array<uint8_t, 32> InputDispatcher::getSignature(
3258 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3259 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3260 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3261 // Only sign events up and down events as the purely move events
3262 // are tied to their up/down counterparts so signing would be redundant.
3263 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3264 verifiedEvent.actionMasked = actionMasked;
3265 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003266 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003267 }
3268 return INVALID_HMAC;
3269}
3270
3271const std::array<uint8_t, 32> InputDispatcher::getSignature(
3272 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3273 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3274 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3275 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003276 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003277}
3278
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003281 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282#if DEBUG_DISPATCH_CYCLE
3283 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003284 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285#endif
3286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 if (connection->status == Connection::STATUS_BROKEN ||
3288 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 return;
3290 }
3291
3292 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003293 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294}
3295
3296void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 const sp<Connection>& connection,
3298 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299#if DEBUG_DISPATCH_CYCLE
3300 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302#endif
3303
3304 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003305 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003306 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003307 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003308 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309
3310 // The connection appears to be unrecoverably broken.
3311 // Ignore already broken or zombie connections.
3312 if (connection->status == Connection::STATUS_NORMAL) {
3313 connection->status = Connection::STATUS_BROKEN;
3314
3315 if (notify) {
3316 // Notify other system components.
3317 onDispatchCycleBrokenLocked(currentTime, connection);
3318 }
3319 }
3320}
3321
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003322void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3323 while (!queue.empty()) {
3324 DispatchEntry* dispatchEntry = queue.front();
3325 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003326 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 }
3328}
3329
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003330void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003332 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
3334 delete dispatchEntry;
3335}
3336
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003337int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3338 std::scoped_lock _l(mLock);
3339 sp<Connection> connection = getConnectionLocked(connectionToken);
3340 if (connection == nullptr) {
3341 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3342 connectionToken.get(), events);
3343 return 0; // remove the callback
3344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003346 bool notify;
3347 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3348 if (!(events & ALOOPER_EVENT_INPUT)) {
3349 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3350 "events=0x%x",
3351 connection->getInputChannelName().c_str(), events);
3352 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003355 nsecs_t currentTime = now();
3356 bool gotOne = false;
3357 status_t status = OK;
3358 for (;;) {
3359 Result<InputPublisher::ConsumerResponse> result =
3360 connection->inputPublisher.receiveConsumerResponse();
3361 if (!result.ok()) {
3362 status = result.error().code();
3363 break;
3364 }
3365
3366 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3367 const InputPublisher::Finished& finish =
3368 std::get<InputPublisher::Finished>(*result);
3369 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3370 finish.consumeTime);
3371 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003372 if (shouldReportMetricsForConnection(*connection)) {
3373 const InputPublisher::Timeline& timeline =
3374 std::get<InputPublisher::Timeline>(*result);
3375 mLatencyTracker
3376 .trackGraphicsLatency(timeline.inputEventId,
3377 connection->inputChannel->getConnectionToken(),
3378 std::move(timeline.graphicsTimeline));
3379 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003380 }
3381 gotOne = true;
3382 }
3383 if (gotOne) {
3384 runCommandsLockedInterruptible();
3385 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 return 1;
3387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003390 notify = status != DEAD_OBJECT || !connection->monitor;
3391 if (notify) {
3392 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3393 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3394 status);
3395 }
3396 } else {
3397 // Monitor channels are never explicitly unregistered.
3398 // We do it automatically when the remote endpoint is closed so don't warn about them.
3399 const bool stillHaveWindowHandle =
3400 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3401 notify = !connection->monitor && stillHaveWindowHandle;
3402 if (notify) {
3403 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3404 connection->getInputChannelName().c_str(), events);
3405 }
3406 }
3407
3408 // Remove the channel.
3409 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3410 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411}
3412
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003413void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003415 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003416 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 }
3418}
3419
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003420void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003421 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003422 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3423 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3424}
3425
3426void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3427 const CancelationOptions& options,
3428 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3429 for (const auto& it : monitorsByDisplay) {
3430 const std::vector<Monitor>& monitors = it.second;
3431 for (const Monitor& monitor : monitors) {
3432 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003433 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003434 }
3435}
3436
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003438 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003439 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003440 if (connection == nullptr) {
3441 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003443
3444 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445}
3446
3447void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3448 const sp<Connection>& connection, const CancelationOptions& options) {
3449 if (connection->status == Connection::STATUS_BROKEN) {
3450 return;
3451 }
3452
3453 nsecs_t currentTime = now();
3454
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003455 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003456 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003458 if (cancelationEvents.empty()) {
3459 return;
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003462 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3463 "with reality: %s, mode=%d.",
3464 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3465 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003467
3468 InputTarget target;
3469 sp<InputWindowHandle> windowHandle =
3470 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3471 if (windowHandle != nullptr) {
3472 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003473 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003474 target.globalScaleFactor = windowInfo->globalScaleFactor;
3475 }
3476 target.inputChannel = connection->inputChannel;
3477 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3478
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003479 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003480 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003481 switch (cancelationEventEntry->type) {
3482 case EventEntry::Type::KEY: {
3483 logOutboundKeyDetails("cancel - ",
3484 static_cast<const KeyEntry&>(*cancelationEventEntry));
3485 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003487 case EventEntry::Type::MOTION: {
3488 logOutboundMotionDetails("cancel - ",
3489 static_cast<const MotionEntry&>(*cancelationEventEntry));
3490 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003492 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003493 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3494 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003495 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003496 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003497 break;
3498 }
3499 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003500 case EventEntry::Type::DEVICE_RESET:
3501 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003502 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003503 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003504 break;
3505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
3507
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003508 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3509 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003511
3512 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513}
3514
Svet Ganov5d3bc372020-01-26 23:11:07 -08003515void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3516 const sp<Connection>& connection) {
3517 if (connection->status == Connection::STATUS_BROKEN) {
3518 return;
3519 }
3520
3521 nsecs_t currentTime = now();
3522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003523 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003524 connection->inputState.synthesizePointerDownEvents(currentTime);
3525
3526 if (downEvents.empty()) {
3527 return;
3528 }
3529
3530#if DEBUG_OUTBOUND_EVENT_DETAILS
3531 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3532 connection->getInputChannelName().c_str(), downEvents.size());
3533#endif
3534
3535 InputTarget target;
3536 sp<InputWindowHandle> windowHandle =
3537 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3538 if (windowHandle != nullptr) {
3539 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003540 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003541 target.globalScaleFactor = windowInfo->globalScaleFactor;
3542 }
3543 target.inputChannel = connection->inputChannel;
3544 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3545
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003546 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003547 switch (downEventEntry->type) {
3548 case EventEntry::Type::MOTION: {
3549 logOutboundMotionDetails("down - ",
3550 static_cast<const MotionEntry&>(*downEventEntry));
3551 break;
3552 }
3553
3554 case EventEntry::Type::KEY:
3555 case EventEntry::Type::FOCUS:
3556 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003557 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003558 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003559 case EventEntry::Type::SENSOR:
3560 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003561 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003562 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003563 break;
3564 }
3565 }
3566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003567 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3568 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003569 }
3570
3571 startDispatchCycleLocked(currentTime, connection);
3572}
3573
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003574std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3575 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 ALOG_ASSERT(pointerIds.value != 0);
3577
3578 uint32_t splitPointerIndexMap[MAX_POINTERS];
3579 PointerProperties splitPointerProperties[MAX_POINTERS];
3580 PointerCoords splitPointerCoords[MAX_POINTERS];
3581
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003582 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 uint32_t splitPointerCount = 0;
3584
3585 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003586 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003588 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 uint32_t pointerId = uint32_t(pointerProperties.id);
3590 if (pointerIds.hasBit(pointerId)) {
3591 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3592 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3593 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003594 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 splitPointerCount += 1;
3596 }
3597 }
3598
3599 if (splitPointerCount != pointerIds.count()) {
3600 // This is bad. We are missing some of the pointers that we expected to deliver.
3601 // Most likely this indicates that we received an ACTION_MOVE events that has
3602 // different pointer ids than we expected based on the previous ACTION_DOWN
3603 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3604 // in this way.
3605 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 "we expected there to be %d pointers. This probably means we received "
3607 "a broken sequence of pointer ids from the input device.",
3608 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003609 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003612 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3615 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3617 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003618 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 uint32_t pointerId = uint32_t(pointerProperties.id);
3620 if (pointerIds.hasBit(pointerId)) {
3621 if (pointerIds.count() == 1) {
3622 // The first/last pointer went down/up.
3623 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003624 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003625 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3626 ? AMOTION_EVENT_ACTION_CANCEL
3627 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 } else {
3629 // A secondary pointer went down/up.
3630 uint32_t splitPointerIndex = 0;
3631 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3632 splitPointerIndex += 1;
3633 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003634 action = maskedAction |
3635 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637 } else {
3638 // An unrelated pointer changed.
3639 action = AMOTION_EVENT_ACTION_MOVE;
3640 }
3641 }
3642
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003643 int32_t newId = mIdGenerator.nextId();
3644 if (ATRACE_ENABLED()) {
3645 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3646 ") to MotionEvent(id=0x%" PRIx32 ").",
3647 originalMotionEntry.id, newId);
3648 ATRACE_NAME(message.c_str());
3649 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003650 std::unique_ptr<MotionEntry> splitMotionEntry =
3651 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3652 originalMotionEntry.deviceId, originalMotionEntry.source,
3653 originalMotionEntry.displayId,
3654 originalMotionEntry.policyFlags, action,
3655 originalMotionEntry.actionButton,
3656 originalMotionEntry.flags, originalMotionEntry.metaState,
3657 originalMotionEntry.buttonState,
3658 originalMotionEntry.classification,
3659 originalMotionEntry.edgeFlags,
3660 originalMotionEntry.xPrecision,
3661 originalMotionEntry.yPrecision,
3662 originalMotionEntry.xCursorPosition,
3663 originalMotionEntry.yCursorPosition,
3664 originalMotionEntry.downTime, splitPointerCount,
3665 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003667 if (originalMotionEntry.injectionState) {
3668 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 splitMotionEntry->injectionState->refCount += 1;
3670 }
3671
3672 return splitMotionEntry;
3673}
3674
3675void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3676#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003677 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678#endif
3679
3680 bool needWake;
3681 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003682 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3685 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3686 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 } // release lock
3688
3689 if (needWake) {
3690 mLooper->wake();
3691 }
3692}
3693
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003694/**
3695 * If one of the meta shortcuts is detected, process them here:
3696 * Meta + Backspace -> generate BACK
3697 * Meta + Enter -> generate HOME
3698 * This will potentially overwrite keyCode and metaState.
3699 */
3700void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003701 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003702 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3703 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3704 if (keyCode == AKEYCODE_DEL) {
3705 newKeyCode = AKEYCODE_BACK;
3706 } else if (keyCode == AKEYCODE_ENTER) {
3707 newKeyCode = AKEYCODE_HOME;
3708 }
3709 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003710 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003711 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003712 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003713 keyCode = newKeyCode;
3714 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3715 }
3716 } else if (action == AKEY_EVENT_ACTION_UP) {
3717 // In order to maintain a consistent stream of up and down events, check to see if the key
3718 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3719 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003720 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003721 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003722 auto replacementIt = mReplacedKeys.find(replacement);
3723 if (replacementIt != mReplacedKeys.end()) {
3724 keyCode = replacementIt->second;
3725 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003726 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3727 }
3728 }
3729}
3730
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3732#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003733 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3734 "policyFlags=0x%x, action=0x%x, "
3735 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3736 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3737 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3738 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739#endif
3740 if (!validateKeyEvent(args->action)) {
3741 return;
3742 }
3743
3744 uint32_t policyFlags = args->policyFlags;
3745 int32_t flags = args->flags;
3746 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003747 // InputDispatcher tracks and generates key repeats on behalf of
3748 // whatever notifies it, so repeatCount should always be set to 0
3749 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3751 policyFlags |= POLICY_FLAG_VIRTUAL;
3752 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 if (policyFlags & POLICY_FLAG_FUNCTION) {
3755 metaState |= AMETA_FUNCTION_ON;
3756 }
3757
3758 policyFlags |= POLICY_FLAG_TRUSTED;
3759
Michael Wright78f24442014-08-06 15:55:28 -07003760 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003761 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003762
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003764 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003765 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3766 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767
Michael Wright2b3c3302018-03-02 17:19:13 +00003768 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003770 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3771 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003772 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 bool needWake;
3776 { // acquire lock
3777 mLock.lock();
3778
3779 if (shouldSendKeyToInputFilterLocked(args)) {
3780 mLock.unlock();
3781
3782 policyFlags |= POLICY_FLAG_FILTERED;
3783 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3784 return; // event was consumed by the filter
3785 }
3786
3787 mLock.lock();
3788 }
3789
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003790 std::unique_ptr<KeyEntry> newEntry =
3791 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3792 args->displayId, policyFlags, args->action, flags,
3793 keyCode, args->scanCode, metaState, repeatCount,
3794 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003796 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 mLock.unlock();
3798 } // release lock
3799
3800 if (needWake) {
3801 mLooper->wake();
3802 }
3803}
3804
3805bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3806 return mInputFilterEnabled;
3807}
3808
3809void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3810#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003811 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3812 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003813 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3814 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003815 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003816 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3817 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3818 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3819 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 for (uint32_t i = 0; i < args->pointerCount; i++) {
3821 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003822 "x=%f, y=%f, pressure=%f, size=%f, "
3823 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3824 "orientation=%f",
3825 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3826 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3827 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3828 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3829 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3830 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3831 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3832 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3833 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3834 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003837 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3838 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 return;
3840 }
3841
3842 uint32_t policyFlags = args->policyFlags;
3843 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003844
3845 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003846 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003847 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3848 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003849 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851
3852 bool needWake;
3853 { // acquire lock
3854 mLock.lock();
3855
3856 if (shouldSendMotionToInputFilterLocked(args)) {
3857 mLock.unlock();
3858
3859 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003860 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003861 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3862 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003863 args->metaState, args->buttonState, args->classification, transform,
3864 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003865 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3866 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003867 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868
3869 policyFlags |= POLICY_FLAG_FILTERED;
3870 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3871 return; // event was consumed by the filter
3872 }
3873
3874 mLock.lock();
3875 }
3876
3877 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003878 std::unique_ptr<MotionEntry> newEntry =
3879 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3880 args->source, args->displayId, policyFlags,
3881 args->action, args->actionButton, args->flags,
3882 args->metaState, args->buttonState,
3883 args->classification, args->edgeFlags,
3884 args->xPrecision, args->yPrecision,
3885 args->xCursorPosition, args->yCursorPosition,
3886 args->downTime, args->pointerCount,
3887 args->pointerProperties, args->pointerCoords, 0, 0);
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003888 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3889 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3890 !mInputFilterEnabled) {
3891 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3892 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003895 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 mLock.unlock();
3897 } // release lock
3898
3899 if (needWake) {
3900 mLooper->wake();
3901 }
3902}
3903
Chris Yef59a2f42020-10-16 12:55:26 -07003904void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3905#if DEBUG_INBOUND_EVENT_DETAILS
3906 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3907 " sensorType=%s",
3908 args->id, args->eventTime, args->deviceId, args->source,
3909 NamedEnum::string(args->sensorType).c_str());
3910#endif
3911
3912 bool needWake;
3913 { // acquire lock
3914 mLock.lock();
3915
3916 // Just enqueue a new sensor event.
3917 std::unique_ptr<SensorEntry> newEntry =
3918 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3919 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3920 args->sensorType, args->accuracy,
3921 args->accuracyChanged, args->values);
3922
3923 needWake = enqueueInboundEventLocked(std::move(newEntry));
3924 mLock.unlock();
3925 } // release lock
3926
3927 if (needWake) {
3928 mLooper->wake();
3929 }
3930}
3931
Chris Yefb552902021-02-03 17:18:37 -08003932void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3933#if DEBUG_INBOUND_EVENT_DETAILS
3934 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3935 args->deviceId, args->isOn);
3936#endif
3937 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3938}
3939
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003941 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942}
3943
3944void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3945#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003946 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003947 "switchMask=0x%08x",
3948 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949#endif
3950
3951 uint32_t policyFlags = args->policyFlags;
3952 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003953 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954}
3955
3956void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3957#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3959 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960#endif
3961
3962 bool needWake;
3963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003964 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003966 std::unique_ptr<DeviceResetEntry> newEntry =
3967 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3968 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 } // release lock
3970
3971 if (needWake) {
3972 mLooper->wake();
3973 }
3974}
3975
Prabir Pradhan7e186182020-11-10 13:56:45 -08003976void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3977#if DEBUG_INBOUND_EVENT_DETAILS
3978 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3979 args->enabled ? "true" : "false");
3980#endif
3981
Prabir Pradhan99987712020-11-10 18:43:05 -08003982 bool needWake;
3983 { // acquire lock
3984 std::scoped_lock _l(mLock);
3985 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3986 args->enabled);
3987 needWake = enqueueInboundEventLocked(std::move(entry));
3988 } // release lock
3989
3990 if (needWake) {
3991 mLooper->wake();
3992 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003993}
3994
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003995InputEventInjectionResult InputDispatcher::injectInputEvent(
3996 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3997 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998#if DEBUG_INBOUND_EVENT_DETAILS
3999 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004000 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4001 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004003 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
4005 policyFlags |= POLICY_FLAG_INJECTED;
4006 if (hasInjectionPermission(injectorPid, injectorUid)) {
4007 policyFlags |= POLICY_FLAG_TRUSTED;
4008 }
4009
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004010 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004012 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004013 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4014 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004016 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004019 int32_t flags = incomingKey.getFlags();
4020 int32_t keyCode = incomingKey.getKeyCode();
4021 int32_t metaState = incomingKey.getMetaState();
4022 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004023 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004024 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08004025 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004026 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4027 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4028 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004030 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4031 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004032 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004033
4034 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4035 android::base::Timer t;
4036 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4037 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4038 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4039 std::to_string(t.duration().count()).c_str());
4040 }
4041 }
4042
4043 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004044 std::unique_ptr<KeyEntry> injectedEntry =
4045 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
4046 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
4047 incomingKey.getDisplayId(), policyFlags, action,
4048 flags, keyCode, incomingKey.getScanCode(), metaState,
4049 incomingKey.getRepeatCount(),
4050 incomingKey.getDownTime());
4051 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 }
4054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 case AINPUT_EVENT_TYPE_MOTION: {
4056 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
4057 int32_t action = motionEvent->getAction();
4058 size_t pointerCount = motionEvent->getPointerCount();
4059 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
4060 int32_t actionButton = motionEvent->getActionButton();
4061 int32_t displayId = motionEvent->getDisplayId();
4062 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 }
4065
4066 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4067 nsecs_t eventTime = motionEvent->getEventTime();
4068 android::base::Timer t;
4069 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4070 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4071 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4072 std::to_string(t.duration().count()).c_str());
4073 }
4074 }
4075
4076 mLock.lock();
4077 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4078 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 std::unique_ptr<MotionEntry> injectedEntry =
4080 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4081 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4082 motionEvent->getDisplayId(), policyFlags, action,
4083 actionButton, motionEvent->getFlags(),
4084 motionEvent->getMetaState(),
4085 motionEvent->getButtonState(),
4086 motionEvent->getClassification(),
4087 motionEvent->getEdgeFlags(),
4088 motionEvent->getXPrecision(),
4089 motionEvent->getYPrecision(),
4090 motionEvent->getRawXCursorPosition(),
4091 motionEvent->getRawYCursorPosition(),
4092 motionEvent->getDownTime(),
4093 uint32_t(pointerCount), pointerProperties,
4094 samplePointerCoords, motionEvent->getXOffset(),
4095 motionEvent->getYOffset());
4096 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4098 sampleEventTimes += 1;
4099 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004100 std::unique_ptr<MotionEntry> nextInjectedEntry =
4101 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4102 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4103 motionEvent->getDisplayId(), policyFlags,
4104 action, actionButton, motionEvent->getFlags(),
4105 motionEvent->getMetaState(),
4106 motionEvent->getButtonState(),
4107 motionEvent->getClassification(),
4108 motionEvent->getEdgeFlags(),
4109 motionEvent->getXPrecision(),
4110 motionEvent->getYPrecision(),
4111 motionEvent->getRawXCursorPosition(),
4112 motionEvent->getRawYCursorPosition(),
4113 motionEvent->getDownTime(),
4114 uint32_t(pointerCount), pointerProperties,
4115 samplePointerCoords,
4116 motionEvent->getXOffset(),
4117 motionEvent->getYOffset());
4118 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 }
4120 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004124 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004125 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 }
4127
4128 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004129 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 injectionState->injectionIsAsync = true;
4131 }
4132
4133 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004134 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135
4136 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004137 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004138 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004139 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
4141
4142 mLock.unlock();
4143
4144 if (needWake) {
4145 mLooper->wake();
4146 }
4147
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004148 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004150 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 if (syncMode == InputEventInjectionSync::NONE) {
4153 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 } else {
4155 for (;;) {
4156 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 break;
4159 }
4160
4161 nsecs_t remainingTimeout = endTime - now();
4162 if (remainingTimeout <= 0) {
4163#if DEBUG_INJECTION
4164 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004167 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 break;
4169 }
4170
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004171 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004174 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4175 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 while (injectionState->pendingForegroundDispatches != 0) {
4177#if DEBUG_INJECTION
4178 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004179 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180#endif
4181 nsecs_t remainingTimeout = endTime - now();
4182 if (remainingTimeout <= 0) {
4183#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004184 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4185 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 break;
4189 }
4190
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004191 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193 }
4194 }
4195
4196 injectionState->release();
4197 } // release lock
4198
4199#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004200 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202#endif
4203
4204 return injectionResult;
4205}
4206
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004207std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004208 std::array<uint8_t, 32> calculatedHmac;
4209 std::unique_ptr<VerifiedInputEvent> result;
4210 switch (event.getType()) {
4211 case AINPUT_EVENT_TYPE_KEY: {
4212 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4213 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4214 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004215 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004216 break;
4217 }
4218 case AINPUT_EVENT_TYPE_MOTION: {
4219 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4220 VerifiedMotionEvent verifiedMotionEvent =
4221 verifiedMotionEventFromMotionEvent(motionEvent);
4222 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004223 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004224 break;
4225 }
4226 default: {
4227 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4228 return nullptr;
4229 }
4230 }
4231 if (calculatedHmac == INVALID_HMAC) {
4232 return nullptr;
4233 }
4234 if (calculatedHmac != event.getHmac()) {
4235 return nullptr;
4236 }
4237 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004238}
4239
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 return injectorUid == 0 ||
4242 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243}
4244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004246 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 if (injectionState) {
4249#if DEBUG_INJECTION
4250 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 "injectorPid=%d, injectorUid=%d",
4252 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253#endif
4254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004255 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 // Log the outcome since the injector did not wait for the injection result.
4257 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004258 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 ALOGV("Asynchronous input event injection succeeded.");
4260 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004261 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 ALOGW("Asynchronous input event injection failed.");
4263 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004264 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 ALOGW("Asynchronous input event injection permission denied.");
4266 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004267 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 ALOGW("Asynchronous input event injection timed out.");
4269 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 case InputEventInjectionResult::PENDING:
4271 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4272 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274 }
4275
4276 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004277 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279}
4280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4282 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 if (injectionState) {
4284 injectionState->pendingForegroundDispatches += 1;
4285 }
4286}
4287
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004288void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4289 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 if (injectionState) {
4291 injectionState->pendingForegroundDispatches -= 1;
4292
4293 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004294 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 }
4296 }
4297}
4298
Vishnu Nairad321cd2020-08-20 16:40:21 -07004299const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004300 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004301 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4302 auto it = mWindowHandlesByDisplay.find(displayId);
4303 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004304}
4305
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004307 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004308 if (windowHandleToken == nullptr) {
4309 return nullptr;
4310 }
4311
Arthur Hungb92218b2018-08-14 12:00:21 +08004312 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004313 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004314 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004315 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004316 return windowHandle;
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004320 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321}
4322
Vishnu Nairad321cd2020-08-20 16:40:21 -07004323sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4324 int displayId) const {
4325 if (windowHandleToken == nullptr) {
4326 return nullptr;
4327 }
4328
4329 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4330 if (windowHandle->getToken() == windowHandleToken) {
4331 return windowHandle;
4332 }
4333 }
4334 return nullptr;
4335}
4336
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004337sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4338 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004339 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004340 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004341 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004342 if (handle->getId() == windowHandle->getId() &&
4343 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004344 if (windowHandle->getInfo()->displayId != it.first) {
4345 ALOGE("Found window %s in display %" PRId32
4346 ", but it should belong to display %" PRId32,
4347 windowHandle->getName().c_str(), it.first,
4348 windowHandle->getInfo()->displayId);
4349 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004350 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
4353 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004354 return nullptr;
4355}
4356
4357sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4358 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4359 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360}
4361
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004362bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4363 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4364 const bool noInputChannel =
4365 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4366 if (connection != nullptr && noInputChannel) {
4367 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4368 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4369 return false;
4370 }
4371
4372 if (connection == nullptr) {
4373 if (!noInputChannel) {
4374 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4375 }
4376 return false;
4377 }
4378 if (!connection->responsive) {
4379 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4380 return false;
4381 }
4382 return true;
4383}
4384
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004385std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4386 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004387 auto connectionIt = mConnectionsByToken.find(token);
4388 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004389 return nullptr;
4390 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004391 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004392}
4393
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004394void InputDispatcher::updateWindowHandlesForDisplayLocked(
4395 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4396 if (inputWindowHandles.empty()) {
4397 // Remove all handles on a display if there are no windows left.
4398 mWindowHandlesByDisplay.erase(displayId);
4399 return;
4400 }
4401
4402 // Since we compare the pointer of input window handles across window updates, we need
4403 // to make sure the handle object for the same window stays unchanged across updates.
4404 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004405 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004406 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004407 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004408 }
4409
4410 std::vector<sp<InputWindowHandle>> newHandles;
4411 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4412 if (!handle->updateInfo()) {
4413 // handle no longer valid
4414 continue;
4415 }
4416
4417 const InputWindowInfo* info = handle->getInfo();
4418 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4419 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4420 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004421 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4422 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4423 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004424 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004425 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004426 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004427 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004428 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004429 }
4430
4431 if (info->displayId != displayId) {
4432 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4433 handle->getName().c_str(), displayId, info->displayId);
4434 continue;
4435 }
4436
Robert Carredd13602020-04-13 17:24:34 -07004437 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4438 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004439 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004440 oldHandle->updateFrom(handle);
4441 newHandles.push_back(oldHandle);
4442 } else {
4443 newHandles.push_back(handle);
4444 }
4445 }
4446
4447 // Insert or replace
4448 mWindowHandlesByDisplay[displayId] = newHandles;
4449}
4450
Arthur Hung72d8dc32020-03-28 00:48:39 +00004451void InputDispatcher::setInputWindows(
4452 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4453 { // acquire lock
4454 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004455 for (const auto& [displayId, handles] : handlesPerDisplay) {
4456 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004457 }
4458 }
4459 // Wake up poll loop since it may need to make new input dispatching choices.
4460 mLooper->wake();
4461}
4462
Arthur Hungb92218b2018-08-14 12:00:21 +08004463/**
4464 * Called from InputManagerService, update window handle list by displayId that can receive input.
4465 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4466 * If set an empty list, remove all handles from the specific display.
4467 * For focused handle, check if need to change and send a cancel event to previous one.
4468 * For removed handle, check if need to send a cancel event if already in touch.
4469 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004470void InputDispatcher::setInputWindowsLocked(
4471 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004472 if (DEBUG_FOCUS) {
4473 std::string windowList;
4474 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4475 windowList += iwh->getName() + " ";
4476 }
4477 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004480 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4481 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4482 const bool noInputWindow =
4483 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4484 if (noInputWindow && window->getToken() != nullptr) {
4485 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4486 window->getName().c_str());
4487 window->releaseChannel();
4488 }
4489 }
4490
Arthur Hung72d8dc32020-03-28 00:48:39 +00004491 // Copy old handles for release if they are no longer present.
4492 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
Arthur Hung72d8dc32020-03-28 00:48:39 +00004494 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004495
Vishnu Nair958da932020-08-21 17:12:37 -07004496 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4497 if (mLastHoverWindowHandle &&
4498 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4499 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004500 mLastHoverWindowHandle = nullptr;
4501 }
4502
Vishnu Nairc519ff72021-01-21 08:23:08 -08004503 std::optional<FocusResolver::FocusChanges> changes =
4504 mFocusResolver.setInputWindows(displayId, windowHandles);
4505 if (changes) {
4506 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004509 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4510 mTouchStatesByDisplay.find(displayId);
4511 if (stateIt != mTouchStatesByDisplay.end()) {
4512 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004513 for (size_t i = 0; i < state.windows.size();) {
4514 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004515 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004516 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004517 ALOGD("Touched window was removed: %s in display %" PRId32,
4518 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004519 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004520 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004521 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4522 if (touchedInputChannel != nullptr) {
4523 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4524 "touched window was removed");
4525 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004527 state.windows.erase(state.windows.begin() + i);
4528 } else {
4529 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 }
4531 }
arthurhungb89ccb02020-12-30 16:19:01 +08004532
arthurhung6d4bed92021-03-17 11:59:33 +08004533 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004534 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004535 if (mDragState &&
4536 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004537 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004538 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004539 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004540 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004541
Arthur Hung72d8dc32020-03-28 00:48:39 +00004542 // Release information for windows that are no longer present.
4543 // This ensures that unused input channels are released promptly.
4544 // Otherwise, they might stick around until the window handle is destroyed
4545 // which might not happen until the next GC.
4546 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004547 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004548 if (DEBUG_FOCUS) {
4549 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004550 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004551 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004552 // To avoid making too many calls into the compat framework, only
4553 // check for window flags when windows are going away.
4554 // TODO(b/157929241) : delete this. This is only needed temporarily
4555 // in order to gather some data about the flag usage
4556 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4557 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4558 oldWindowHandle->getName().c_str());
4559 if (mCompatService != nullptr) {
4560 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4561 oldWindowHandle->getInfo()->ownerUid);
4562 }
4563 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004564 }
chaviw291d88a2019-02-14 10:33:58 -08004565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566}
4567
4568void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004569 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004570 if (DEBUG_FOCUS) {
4571 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4572 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4573 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004574 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004575 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
Chris Yea209fde2020-07-22 13:54:51 -07004577 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004578 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004580 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4581 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004582 }
4583
Chris Yea209fde2020-07-22 13:54:51 -07004584 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004585 if (inputApplicationHandle != nullptr) {
4586 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4587 } else {
4588 mFocusedApplicationHandlesByDisplay.erase(displayId);
4589 }
4590
4591 // No matter what the old focused application was, stop waiting on it because it is
4592 // no longer focused.
4593 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 } // release lock
4595
4596 // Wake up poll loop since it may need to make new input dispatching choices.
4597 mLooper->wake();
4598}
4599
Tiger Huang721e26f2018-07-24 22:26:19 +08004600/**
4601 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4602 * the display not specified.
4603 *
4604 * We track any unreleased events for each window. If a window loses the ability to receive the
4605 * released event, we will send a cancel event to it. So when the focused display is changed, we
4606 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4607 * display. The display-specified events won't be affected.
4608 */
4609void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004610 if (DEBUG_FOCUS) {
4611 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4612 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004613 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004614 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004615
4616 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004617 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004618 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004619 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004620 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004621 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004622 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004623 CancelationOptions
4624 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4625 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004626 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004627 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4628 }
4629 }
4630 mFocusedDisplayId = displayId;
4631
Chris Ye3c2d6f52020-08-09 10:39:48 -07004632 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004633 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004634 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004635
Vishnu Nairad321cd2020-08-20 16:40:21 -07004636 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004637 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004638 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004639 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004640 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004641 }
4642 }
4643 }
4644
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004645 if (DEBUG_FOCUS) {
4646 logDispatchStateLocked();
4647 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004648 } // release lock
4649
4650 // Wake up poll loop since it may need to make new input dispatching choices.
4651 mLooper->wake();
4652}
4653
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004655 if (DEBUG_FOCUS) {
4656 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658
4659 bool changed;
4660 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004661 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662
4663 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4664 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004665 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 }
4667
4668 if (mDispatchEnabled && !enabled) {
4669 resetAndDropEverythingLocked("dispatcher is being disabled");
4670 }
4671
4672 mDispatchEnabled = enabled;
4673 mDispatchFrozen = frozen;
4674 changed = true;
4675 } else {
4676 changed = false;
4677 }
4678
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004679 if (DEBUG_FOCUS) {
4680 logDispatchStateLocked();
4681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 } // release lock
4683
4684 if (changed) {
4685 // Wake up poll loop since it may need to make new input dispatching choices.
4686 mLooper->wake();
4687 }
4688}
4689
4690void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004691 if (DEBUG_FOCUS) {
4692 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694
4695 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004696 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697
4698 if (mInputFilterEnabled == enabled) {
4699 return;
4700 }
4701
4702 mInputFilterEnabled = enabled;
4703 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4704 } // release lock
4705
4706 // Wake up poll loop since there might be work to do to drop everything.
4707 mLooper->wake();
4708}
4709
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004710void InputDispatcher::setInTouchMode(bool inTouchMode) {
4711 std::scoped_lock lock(mLock);
4712 mInTouchMode = inTouchMode;
4713}
4714
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004715void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4716 if (opacity < 0 || opacity > 1) {
4717 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4718 return;
4719 }
4720
4721 std::scoped_lock lock(mLock);
4722 mMaximumObscuringOpacityForTouch = opacity;
4723}
4724
4725void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4726 std::scoped_lock lock(mLock);
4727 mBlockUntrustedTouchesMode = mode;
4728}
4729
arthurhungb89ccb02020-12-30 16:19:01 +08004730bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4731 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004732 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004733 if (DEBUG_FOCUS) {
4734 ALOGD("Trivial transfer to same window.");
4735 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004736 return true;
4737 }
4738
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004740 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741
chaviwfbe5d9c2018-12-26 12:23:37 -08004742 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4743 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004744 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004745 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 return false;
4747 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004748 if (DEBUG_FOCUS) {
4749 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4750 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004753 if (DEBUG_FOCUS) {
4754 ALOGD("Cannot transfer focus because windows are on different displays.");
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 return false;
4757 }
4758
4759 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004760 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4761 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004762 for (size_t i = 0; i < state.windows.size(); i++) {
4763 const TouchedWindow& touchedWindow = state.windows[i];
4764 if (touchedWindow.windowHandle == fromWindowHandle) {
4765 int32_t oldTargetFlags = touchedWindow.targetFlags;
4766 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004768 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004770 int32_t newTargetFlags = oldTargetFlags &
4771 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4772 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004773 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774
arthurhungb89ccb02020-12-30 16:19:01 +08004775 // Store the dragging window.
4776 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004777 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004778 }
4779
Jeff Brownf086ddb2014-02-11 14:28:48 -08004780 found = true;
4781 goto Found;
4782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
4784 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004788 if (DEBUG_FOCUS) {
4789 ALOGD("Focus transfer failed because from window did not have focus.");
4790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 return false;
4792 }
4793
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004794 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4795 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004796 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004797 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 CancelationOptions
4799 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4800 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004802 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 }
4804
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004805 if (DEBUG_FOCUS) {
4806 logDispatchStateLocked();
4807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 } // release lock
4809
4810 // Wake up poll loop since it may need to make new input dispatching choices.
4811 mLooper->wake();
4812 return true;
4813}
4814
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004815// Binder call
4816bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4817 sp<IBinder> fromToken;
4818 { // acquire lock
4819 std::scoped_lock _l(mLock);
4820
4821 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4822 if (toWindowHandle == nullptr) {
4823 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4824 return false;
4825 }
4826
4827 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4828
4829 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4830 if (touchStateIt == mTouchStatesByDisplay.end()) {
4831 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4832 displayId);
4833 return false;
4834 }
4835
4836 TouchState& state = touchStateIt->second;
4837 if (state.windows.size() != 1) {
4838 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4839 state.windows.size());
4840 return false;
4841 }
4842 const TouchedWindow& touchedWindow = state.windows[0];
4843 fromToken = touchedWindow.windowHandle->getToken();
4844 } // release lock
4845
4846 return transferTouchFocus(fromToken, destChannelToken);
4847}
4848
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004850 if (DEBUG_FOCUS) {
4851 ALOGD("Resetting and dropping all events (%s).", reason);
4852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853
4854 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4855 synthesizeCancelationEventsForAllConnectionsLocked(options);
4856
4857 resetKeyRepeatLocked();
4858 releasePendingEventLocked();
4859 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004860 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004862 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004863 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004865 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866}
4867
4868void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004869 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 dumpDispatchStateLocked(dump);
4871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004872 std::istringstream stream(dump);
4873 std::string line;
4874
4875 while (std::getline(stream, line, '\n')) {
4876 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
4878}
4879
Prabir Pradhan99987712020-11-10 18:43:05 -08004880std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4881 std::string dump;
4882
4883 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4884 toString(mFocusedWindowRequestedPointerCapture));
4885
4886 std::string windowName = "None";
4887 if (mWindowTokenWithPointerCapture) {
4888 const sp<InputWindowHandle> captureWindowHandle =
4889 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4890 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4891 : "token has capture without window";
4892 }
4893 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4894
4895 return dump;
4896}
4897
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004898void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004899 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4900 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4901 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004902 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903
Tiger Huang721e26f2018-07-24 22:26:19 +08004904 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4905 dump += StringPrintf(INDENT "FocusedApplications:\n");
4906 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4907 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004908 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004909 const std::chrono::duration timeout =
4910 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004911 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004912 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004913 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004916 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004918
Vishnu Nairc519ff72021-01-21 08:23:08 -08004919 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004920 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004922 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004923 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004924 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4925 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004926 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004927 state.displayId, toString(state.down), toString(state.split),
4928 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004929 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004930 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004931 for (size_t i = 0; i < state.windows.size(); i++) {
4932 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004933 dump += StringPrintf(INDENT4
4934 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4935 i, touchedWindow.windowHandle->getName().c_str(),
4936 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004937 }
4938 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004939 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004940 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004941 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004942 dump += INDENT3 "Portal windows:\n";
4943 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004944 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4946 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004947 }
4948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 }
4950 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004951 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 }
4953
arthurhung6d4bed92021-03-17 11:59:33 +08004954 if (mDragState) {
4955 dump += StringPrintf(INDENT "DragState:\n");
4956 mDragState->dump(dump, INDENT2);
4957 }
4958
Arthur Hungb92218b2018-08-14 12:00:21 +08004959 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004960 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004961 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004962 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004963 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004964 dump += INDENT2 "Windows:\n";
4965 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004966 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004967 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004969 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004970 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004971 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004972 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004973 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004974 "applicationInfo.name=%s, "
4975 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004976 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004977 i, windowInfo->name.c_str(), windowInfo->id,
4978 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004979 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004980 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004981 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004982 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004983 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004984 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004985 windowInfo->frameLeft, windowInfo->frameTop,
4986 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004987 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004988 windowInfo->applicationInfo.name.c_str(),
4989 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004990 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004991 dump += StringPrintf(", inputFeatures=%s",
4992 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004993 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004994 "ms, trustedOverlay=%s, hasToken=%s, "
4995 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004996 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004997 millis(windowInfo->dispatchingTimeout),
4998 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004999 toString(windowInfo->token != nullptr),
5000 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005001 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005002 }
5003 } else {
5004 dump += INDENT2 "Windows: <none>\n";
5005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 }
5007 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005008 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 }
5010
Michael Wright3dd60e22019-03-27 22:06:44 +00005011 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005012 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005013 const std::vector<Monitor>& monitors = it.second;
5014 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5015 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 }
5017 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005018 const std::vector<Monitor>& monitors = it.second;
5019 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5020 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005023 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005024 }
5025
5026 nsecs_t currentTime = now();
5027
5028 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005029 if (!mRecentQueue.empty()) {
5030 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005031 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005032 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005033 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005034 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 }
5036 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005037 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039
5040 // Dump event currently being dispatched.
5041 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005042 dump += INDENT "PendingEvent:\n";
5043 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005044 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005045 dump += StringPrintf(", age=%" PRId64 "ms\n",
5046 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005048 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049 }
5050
5051 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005052 if (!mInboundQueue.empty()) {
5053 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005054 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005055 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005056 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005057 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 }
5059 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005060 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005063 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005064 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005065 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5066 const KeyReplacement& replacement = pair.first;
5067 int32_t newKeyCode = pair.second;
5068 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005069 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005070 }
5071 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005072 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005073 }
5074
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005075 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005076 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005077 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005078 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005079 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005080 connection->inputChannel->getFd().get(),
5081 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005082 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005083 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005085 if (!connection->outboundQueue.empty()) {
5086 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5087 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005088 dump += dumpQueue(connection->outboundQueue, currentTime);
5089
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005091 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 }
5093
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005094 if (!connection->waitQueue.empty()) {
5095 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5096 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005097 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 }
5101 }
5102 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005103 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 }
5105
5106 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005107 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5108 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005110 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 }
5112
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005113 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005114 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5115 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5116 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005117 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005118 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119}
5120
Michael Wright3dd60e22019-03-27 22:06:44 +00005121void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5122 const size_t numMonitors = monitors.size();
5123 for (size_t i = 0; i < numMonitors; i++) {
5124 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005125 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005126 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5127 dump += "\n";
5128 }
5129}
5130
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005131class LooperEventCallback : public LooperCallback {
5132public:
5133 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5134 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5135
5136private:
5137 std::function<int(int events)> mCallback;
5138};
5139
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005140Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005141#if DEBUG_CHANNEL_CREATION
5142 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143#endif
5144
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005145 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005146 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005147 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005148
5149 if (result) {
5150 return base::Error(result) << "Failed to open input channel pair with name " << name;
5151 }
5152
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005154 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005155 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005156 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005157 sp<Connection> connection =
5158 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005160 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5161 ALOGE("Created a new connection, but the token %p is already known", token.get());
5162 }
5163 mConnectionsByToken.emplace(token, connection);
5164
5165 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5166 this, std::placeholders::_1, token);
5167
5168 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 } // release lock
5170
5171 // Wake the looper because some connections have changed.
5172 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005173 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174}
5175
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005176Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5177 bool isGestureMonitor,
5178 const std::string& name,
5179 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005180 std::shared_ptr<InputChannel> serverChannel;
5181 std::unique_ptr<InputChannel> clientChannel;
5182 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5183 if (result) {
5184 return base::Error(result) << "Failed to open input channel pair with name " << name;
5185 }
5186
Michael Wright3dd60e22019-03-27 22:06:44 +00005187 { // acquire lock
5188 std::scoped_lock _l(mLock);
5189
5190 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005191 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5192 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005193 }
5194
Garfield Tan15601662020-09-22 15:32:38 -07005195 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005196 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005197 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005198
5199 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5200 ALOGE("Created a new connection, but the token %p is already known", token.get());
5201 }
5202 mConnectionsByToken.emplace(token, connection);
5203 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5204 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005205
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005206 auto& monitorsByDisplay =
5207 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005208 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005209
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005210 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005211 }
Garfield Tan15601662020-09-22 15:32:38 -07005212
Michael Wright3dd60e22019-03-27 22:06:44 +00005213 // Wake the looper because some connections have changed.
5214 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005215 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005216}
5217
Garfield Tan15601662020-09-22 15:32:38 -07005218status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005220 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221
Garfield Tan15601662020-09-22 15:32:38 -07005222 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 if (status) {
5224 return status;
5225 }
5226 } // release lock
5227
5228 // Wake the poll loop because removing the connection may have changed the current
5229 // synchronization state.
5230 mLooper->wake();
5231 return OK;
5232}
5233
Garfield Tan15601662020-09-22 15:32:38 -07005234status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5235 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005236 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005237 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005238 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 return BAD_VALUE;
5240 }
5241
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005242 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005243
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005245 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
5247
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005248 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249
5250 nsecs_t currentTime = now();
5251 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5252
5253 connection->status = Connection::STATUS_ZOMBIE;
5254 return OK;
5255}
5256
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005257void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5258 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5259 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005260}
5261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005262void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005263 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005264 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005265 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005266 std::vector<Monitor>& monitors = it->second;
5267 const size_t numMonitors = monitors.size();
5268 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005269 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005270 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5271 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005272 monitors.erase(monitors.begin() + i);
5273 break;
5274 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005275 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005276 if (monitors.empty()) {
5277 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005278 } else {
5279 ++it;
5280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 }
5282}
5283
Michael Wright3dd60e22019-03-27 22:06:44 +00005284status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5285 { // acquire lock
5286 std::scoped_lock _l(mLock);
5287 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5288
5289 if (!foundDisplayId) {
5290 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5291 return BAD_VALUE;
5292 }
5293 int32_t displayId = foundDisplayId.value();
5294
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005295 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5296 mTouchStatesByDisplay.find(displayId);
5297 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005298 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5299 return BAD_VALUE;
5300 }
5301
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005302 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005303 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005304 std::optional<int32_t> foundDeviceId;
5305 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005306 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005307 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005308 foundDeviceId = state.deviceId;
5309 }
5310 }
5311 if (!foundDeviceId || !state.down) {
5312 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005313 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005314 return BAD_VALUE;
5315 }
5316 int32_t deviceId = foundDeviceId.value();
5317
5318 // Send cancel events to all the input channels we're stealing from.
5319 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005320 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005321 options.deviceId = deviceId;
5322 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005323 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005324 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005325 std::shared_ptr<InputChannel> channel =
5326 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005327 if (channel != nullptr) {
5328 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005329 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005330 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005331 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005332 canceledWindows += "]";
5333 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5334 canceledWindows.c_str());
5335
Michael Wright3dd60e22019-03-27 22:06:44 +00005336 // Then clear the current touch state so we stop dispatching to them as well.
5337 state.filterNonMonitors();
5338 }
5339 return OK;
5340}
5341
Prabir Pradhan99987712020-11-10 18:43:05 -08005342void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5343 { // acquire lock
5344 std::scoped_lock _l(mLock);
5345 if (DEBUG_FOCUS) {
5346 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5347 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5348 windowHandle != nullptr ? windowHandle->getName().c_str()
5349 : "token without window");
5350 }
5351
Vishnu Nairc519ff72021-01-21 08:23:08 -08005352 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005353 if (focusedToken != windowToken) {
5354 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5355 enabled ? "enable" : "disable");
5356 return;
5357 }
5358
5359 if (enabled == mFocusedWindowRequestedPointerCapture) {
5360 ALOGW("Ignoring request to %s Pointer Capture: "
5361 "window has %s requested pointer capture.",
5362 enabled ? "enable" : "disable", enabled ? "already" : "not");
5363 return;
5364 }
5365
5366 mFocusedWindowRequestedPointerCapture = enabled;
5367 setPointerCaptureLocked(enabled);
5368 } // release lock
5369
5370 // Wake the thread to process command entries.
5371 mLooper->wake();
5372}
5373
Michael Wright3dd60e22019-03-27 22:06:44 +00005374std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5375 const sp<IBinder>& token) {
5376 for (const auto& it : mGestureMonitorsByDisplay) {
5377 const std::vector<Monitor>& monitors = it.second;
5378 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005379 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005380 return it.first;
5381 }
5382 }
5383 }
5384 return std::nullopt;
5385}
5386
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005387std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5388 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5389 if (gesturePid.has_value()) {
5390 return gesturePid;
5391 }
5392 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5393}
5394
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005395sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005396 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005397 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005398 }
5399
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005400 for (const auto& [token, connection] : mConnectionsByToken) {
5401 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005402 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 }
5404 }
Robert Carr4e670e52018-08-15 13:26:12 -07005405
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005406 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407}
5408
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005409std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5410 sp<Connection> connection = getConnectionLocked(connectionToken);
5411 if (connection == nullptr) {
5412 return "<nullptr>";
5413 }
5414 return connection->getInputChannelName();
5415}
5416
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005417void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005418 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005419 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005420}
5421
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005422void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5423 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005424 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005425 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5426 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 commandEntry->connection = connection;
5428 commandEntry->eventTime = currentTime;
5429 commandEntry->seq = seq;
5430 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005431 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005432 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433}
5434
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005435void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5436 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005438 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005440 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5441 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005443 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444}
5445
Vishnu Nairad321cd2020-08-20 16:40:21 -07005446void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5447 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005448 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5449 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005450 commandEntry->oldToken = oldToken;
5451 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005452 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005453}
5454
arthurhungf452d0b2021-01-06 00:19:52 +08005455void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5456 std::unique_ptr<CommandEntry> commandEntry =
5457 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5458 commandEntry->newToken = token;
5459 commandEntry->x = x;
5460 commandEntry->y = y;
5461 postCommandLocked(std::move(commandEntry));
5462}
5463
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005464void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5465 if (connection == nullptr) {
5466 LOG_ALWAYS_FATAL("Caller must check for nullness");
5467 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005468 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5469 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005470 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005471 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005472 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005473 return;
5474 }
5475 /**
5476 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5477 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5478 * has changed. This could cause newer entries to time out before the already dispatched
5479 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5480 * processes the events linearly. So providing information about the oldest entry seems to be
5481 * most useful.
5482 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005483 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005484 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5485 std::string reason =
5486 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005487 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005488 ns2ms(currentWait),
5489 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005490 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005491 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005492
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005493 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5494
5495 // Stop waking up for events on this connection, it is already unresponsive
5496 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005497}
5498
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005499void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5500 std::string reason =
5501 StringPrintf("%s does not have a focused window", application->getName().c_str());
5502 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005503
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005504 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5505 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5506 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005507 postCommandLocked(std::move(commandEntry));
5508}
5509
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005510void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5511 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5512 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5513 commandEntry->obscuringPackage = obscuringPackage;
5514 postCommandLocked(std::move(commandEntry));
5515}
5516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005517void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5518 const std::string& reason) {
5519 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5520 updateLastAnrStateLocked(windowLabel, reason);
5521}
5522
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005523void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5524 const std::string& reason) {
5525 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005526 updateLastAnrStateLocked(windowLabel, reason);
5527}
5528
5529void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5530 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005532 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 struct tm tm;
5534 localtime_r(&t, &tm);
5535 char timestr[64];
5536 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005537 mLastAnrState.clear();
5538 mLastAnrState += INDENT "ANR:\n";
5539 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005540 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5541 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005542 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543}
5544
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005545void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546 mLock.unlock();
5547
5548 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5549
5550 mLock.lock();
5551}
5552
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005553void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 sp<Connection> connection = commandEntry->connection;
5555
5556 if (connection->status != Connection::STATUS_ZOMBIE) {
5557 mLock.unlock();
5558
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005559 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560
5561 mLock.lock();
5562 }
5563}
5564
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005565void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005566 sp<IBinder> oldToken = commandEntry->oldToken;
5567 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005568 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005569 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005570 mLock.lock();
5571}
5572
arthurhungf452d0b2021-01-06 00:19:52 +08005573void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5574 sp<IBinder> newToken = commandEntry->newToken;
5575 mLock.unlock();
5576 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5577 mLock.lock();
5578}
5579
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005580void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005582
5583 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5584
5585 mLock.lock();
5586}
5587
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005588void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005589 mLock.unlock();
5590
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005591 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592
5593 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005594}
5595
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005596void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005597 mLock.unlock();
5598
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005599 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5600
5601 mLock.lock();
5602}
5603
5604void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5605 mLock.unlock();
5606
5607 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5608
5609 mLock.lock();
5610}
5611
5612void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5613 mLock.unlock();
5614
5615 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005616
5617 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005618}
5619
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005620void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5621 mLock.unlock();
5622
5623 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5624
5625 mLock.lock();
5626}
5627
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5629 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005630 KeyEntry& entry = *(commandEntry->keyEntry);
5631 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632
5633 mLock.unlock();
5634
Michael Wright2b3c3302018-03-02 17:19:13 +00005635 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005636 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005637 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005638 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5639 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005640 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642
5643 mLock.lock();
5644
5645 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005646 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005648 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005650 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5651 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653}
5654
chaviwfd6d3512019-03-25 13:23:49 -07005655void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5656 mLock.unlock();
5657 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5658 mLock.lock();
5659}
5660
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005661/**
5662 * Connection is responsive if it has no events in the waitQueue that are older than the
5663 * current time.
5664 */
5665static bool isConnectionResponsive(const Connection& connection) {
5666 const nsecs_t currentTime = now();
5667 for (const DispatchEntry* entry : connection.waitQueue) {
5668 if (entry->timeoutTime < currentTime) {
5669 return false;
5670 }
5671 }
5672 return true;
5673}
5674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005675void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005677 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005679 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680
5681 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005682 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005683 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005684 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005686 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005687 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005688 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005689 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5690 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005691 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005692 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5693 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5694 connection->inputChannel->getConnectionToken(),
5695 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5696 finishTime);
5697 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005698
5699 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005700 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005701 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005702 restartEvent =
5703 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005704 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005705 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005706 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5707 handled);
5708 } else {
5709 restartEvent = false;
5710 }
5711
5712 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005713 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005714 // contents of the wait queue to have been drained, so we need to double-check
5715 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005716 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5717 if (dispatchEntryIt != connection->waitQueue.end()) {
5718 dispatchEntry = *dispatchEntryIt;
5719 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005720 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5721 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005722 if (!connection->responsive) {
5723 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005724 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005725 // The connection was unresponsive, and now it's responsive.
5726 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005727 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005728 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005729 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005730 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005731 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005732 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005733 } else {
5734 releaseDispatchEntry(dispatchEntry);
5735 }
5736 }
5737
5738 // Start the next dispatch cycle for this connection.
5739 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740}
5741
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005742void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5743 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5744 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5745 monitorUnresponsiveCommand->pid = pid;
5746 monitorUnresponsiveCommand->reason = std::move(reason);
5747 postCommandLocked(std::move(monitorUnresponsiveCommand));
5748}
5749
5750void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5751 std::string reason) {
5752 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5753 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5754 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5755 windowUnresponsiveCommand->reason = std::move(reason);
5756 postCommandLocked(std::move(windowUnresponsiveCommand));
5757}
5758
5759void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5760 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5761 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5762 monitorResponsiveCommand->pid = pid;
5763 postCommandLocked(std::move(monitorResponsiveCommand));
5764}
5765
5766void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5767 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5768 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5769 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5770 postCommandLocked(std::move(windowResponsiveCommand));
5771}
5772
5773/**
5774 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5775 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5776 * command entry to the command queue.
5777 */
5778void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5779 std::string reason) {
5780 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5781 if (connection.monitor) {
5782 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5783 reason.c_str());
5784 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5785 if (!pid.has_value()) {
5786 ALOGE("Could not find unresponsive monitor for connection %s",
5787 connection.inputChannel->getName().c_str());
5788 return;
5789 }
5790 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5791 return;
5792 }
5793 // If not a monitor, must be a window
5794 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5795 reason.c_str());
5796 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5797}
5798
5799/**
5800 * Tell the policy that a connection has become responsive so that it can stop ANR.
5801 */
5802void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5803 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5804 if (connection.monitor) {
5805 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5806 if (!pid.has_value()) {
5807 ALOGE("Could not find responsive monitor for connection %s",
5808 connection.inputChannel->getName().c_str());
5809 return;
5810 }
5811 sendMonitorResponsiveCommandLocked(pid.value());
5812 return;
5813 }
5814 // If not a monitor, must be a window
5815 sendWindowResponsiveCommandLocked(connectionToken);
5816}
5817
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005819 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005820 KeyEntry& keyEntry, bool handled) {
5821 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005822 if (!handled) {
5823 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005824 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005825 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005826 return false;
5827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005829 // Get the fallback key state.
5830 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005831 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005832 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005833 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005834 connection->inputState.removeFallbackKey(originalKeyCode);
5835 }
5836
5837 if (handled || !dispatchEntry->hasForegroundTarget()) {
5838 // If the application handles the original key for which we previously
5839 // generated a fallback or if the window is not a foreground window,
5840 // then cancel the associated fallback key, if any.
5841 if (fallbackKeyCode != -1) {
5842 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005844 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005845 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005846 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005848 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005849 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850
5851 mLock.unlock();
5852
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005853 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005854 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855
5856 mLock.lock();
5857
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005858 // Cancel the fallback key.
5859 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005861 "application handled the original non-fallback key "
5862 "or is no longer a foreground target, "
5863 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 options.keyCode = fallbackKeyCode;
5865 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005866 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005867 connection->inputState.removeFallbackKey(originalKeyCode);
5868 }
5869 } else {
5870 // If the application did not handle a non-fallback key, first check
5871 // that we are in a good state to perform unhandled key event processing
5872 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005873 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005874 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005876 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005877 "since this is not an initial down. "
5878 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005879 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005880#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005881 return false;
5882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005884 // Dispatch the unhandled key to the policy.
5885#if DEBUG_OUTBOUND_EVENT_DETAILS
5886 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005887 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005888 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005890 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005891
5892 mLock.unlock();
5893
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005894 bool fallback =
5895 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005896 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005897
5898 mLock.lock();
5899
5900 if (connection->status != Connection::STATUS_NORMAL) {
5901 connection->inputState.removeFallbackKey(originalKeyCode);
5902 return false;
5903 }
5904
5905 // Latch the fallback keycode for this key on an initial down.
5906 // The fallback keycode cannot change at any other point in the lifecycle.
5907 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005909 fallbackKeyCode = event.getKeyCode();
5910 } else {
5911 fallbackKeyCode = AKEYCODE_UNKNOWN;
5912 }
5913 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5914 }
5915
5916 ALOG_ASSERT(fallbackKeyCode != -1);
5917
5918 // Cancel the fallback key if the policy decides not to send it anymore.
5919 // We will continue to dispatch the key to the policy but we will no
5920 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005921 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5922 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005923#if DEBUG_OUTBOUND_EVENT_DETAILS
5924 if (fallback) {
5925 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005926 "as a fallback for %d, but on the DOWN it had requested "
5927 "to send %d instead. Fallback canceled.",
5928 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005929 } else {
5930 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005931 "but on the DOWN it had requested to send %d. "
5932 "Fallback canceled.",
5933 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005934 }
5935#endif
5936
5937 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5938 "canceling fallback, policy no longer desires it");
5939 options.keyCode = fallbackKeyCode;
5940 synthesizeCancelationEventsForConnectionLocked(connection, options);
5941
5942 fallback = false;
5943 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005944 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005945 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005946 }
5947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948
5949#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005950 {
5951 std::string msg;
5952 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5953 connection->inputState.getFallbackKeys();
5954 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005955 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005957 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005958 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005959 }
5960#endif
5961
5962 if (fallback) {
5963 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005964 keyEntry.eventTime = event.getEventTime();
5965 keyEntry.deviceId = event.getDeviceId();
5966 keyEntry.source = event.getSource();
5967 keyEntry.displayId = event.getDisplayId();
5968 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5969 keyEntry.keyCode = fallbackKeyCode;
5970 keyEntry.scanCode = event.getScanCode();
5971 keyEntry.metaState = event.getMetaState();
5972 keyEntry.repeatCount = event.getRepeatCount();
5973 keyEntry.downTime = event.getDownTime();
5974 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005975
5976#if DEBUG_OUTBOUND_EVENT_DETAILS
5977 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005978 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005979 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005980#endif
5981 return true; // restart the event
5982 } else {
5983#if DEBUG_OUTBOUND_EVENT_DETAILS
5984 ALOGD("Unhandled key event: No fallback key.");
5985#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005986
5987 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005988 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989 }
5990 }
5991 return false;
5992}
5993
5994bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005995 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005996 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997 return false;
5998}
5999
6000void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6001 mLock.unlock();
6002
Sean Stoutb4e0a592021-02-23 07:34:53 -08006003 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6004 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005
6006 mLock.lock();
6007}
6008
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009void InputDispatcher::traceInboundQueueLengthLocked() {
6010 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006011 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012 }
6013}
6014
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006015void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016 if (ATRACE_ENABLED()) {
6017 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006018 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6019 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020 }
6021}
6022
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006023void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 if (ATRACE_ENABLED()) {
6025 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006026 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6027 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 }
6029}
6030
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006031void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006032 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006034 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035 dumpDispatchStateLocked(dump);
6036
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006037 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006038 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006039 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006040 }
6041}
6042
6043void InputDispatcher::monitor() {
6044 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006045 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006047 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048}
6049
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006050/**
6051 * Wake up the dispatcher and wait until it processes all events and commands.
6052 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6053 * this method can be safely called from any thread, as long as you've ensured that
6054 * the work you are interested in completing has already been queued.
6055 */
6056bool InputDispatcher::waitForIdle() {
6057 /**
6058 * Timeout should represent the longest possible time that a device might spend processing
6059 * events and commands.
6060 */
6061 constexpr std::chrono::duration TIMEOUT = 100ms;
6062 std::unique_lock lock(mLock);
6063 mLooper->wake();
6064 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6065 return result == std::cv_status::no_timeout;
6066}
6067
Vishnu Naire798b472020-07-23 13:52:21 -07006068/**
6069 * Sets focus to the window identified by the token. This must be called
6070 * after updating any input window handles.
6071 *
6072 * Params:
6073 * request.token - input channel token used to identify the window that should gain focus.
6074 * request.focusedToken - the token that the caller expects currently to be focused. If the
6075 * specified token does not match the currently focused window, this request will be dropped.
6076 * If the specified focused token matches the currently focused window, the call will succeed.
6077 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6078 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6079 * when requesting the focus change. This determines which request gets
6080 * precedence if there is a focus change request from another source such as pointer down.
6081 */
Vishnu Nair958da932020-08-21 17:12:37 -07006082void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6083 { // acquire lock
6084 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006085 std::optional<FocusResolver::FocusChanges> changes =
6086 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6087 if (changes) {
6088 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006089 }
6090 } // release lock
6091 // Wake up poll loop since it may need to make new input dispatching choices.
6092 mLooper->wake();
6093}
6094
Vishnu Nairc519ff72021-01-21 08:23:08 -08006095void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6096 if (changes.oldFocus) {
6097 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006098 if (focusedInputChannel) {
6099 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6100 "focus left window");
6101 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006102 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006103 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006104 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006105 if (changes.newFocus) {
6106 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006107 }
6108
Prabir Pradhan99987712020-11-10 18:43:05 -08006109 // If a window has pointer capture, then it must have focus. We need to ensure that this
6110 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6111 // If the window loses focus before it loses pointer capture, then the window can be in a state
6112 // where it has pointer capture but not focus, violating the contract. Therefore we must
6113 // dispatch the pointer capture event before the focus event. Since focus events are added to
6114 // the front of the queue (above), we add the pointer capture event to the front of the queue
6115 // after the focus events are added. This ensures the pointer capture event ends up at the
6116 // front.
6117 disablePointerCaptureForcedLocked();
6118
Vishnu Nairc519ff72021-01-21 08:23:08 -08006119 if (mFocusedDisplayId == changes.displayId) {
6120 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006121 }
6122}
Vishnu Nair958da932020-08-21 17:12:37 -07006123
Prabir Pradhan99987712020-11-10 18:43:05 -08006124void InputDispatcher::disablePointerCaptureForcedLocked() {
6125 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6126 return;
6127 }
6128
6129 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6130
6131 if (mFocusedWindowRequestedPointerCapture) {
6132 mFocusedWindowRequestedPointerCapture = false;
6133 setPointerCaptureLocked(false);
6134 }
6135
6136 if (!mWindowTokenWithPointerCapture) {
6137 // No need to send capture changes because no window has capture.
6138 return;
6139 }
6140
6141 if (mPendingEvent != nullptr) {
6142 // Move the pending event to the front of the queue. This will give the chance
6143 // for the pending event to be dropped if it is a captured event.
6144 mInboundQueue.push_front(mPendingEvent);
6145 mPendingEvent = nullptr;
6146 }
6147
6148 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6149 false /* hasCapture */);
6150 mInboundQueue.push_front(std::move(entry));
6151}
6152
Prabir Pradhan99987712020-11-10 18:43:05 -08006153void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6154 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6155 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6156 commandEntry->enabled = enabled;
6157 postCommandLocked(std::move(commandEntry));
6158}
6159
6160void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6161 android::inputdispatcher::CommandEntry* commandEntry) {
6162 mLock.unlock();
6163
6164 mPolicy->setPointerCapture(commandEntry->enabled);
6165
6166 mLock.lock();
6167}
6168
Garfield Tane84e6f92019-08-29 17:28:41 -07006169} // namespace android::inputdispatcher