blob: f36aecf32bd186825b319873c0a606dcbb311e81 [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 Vishniakouf2652122021-03-05 21:39:46 +0000520 mLatencyTracker(&mEmptyProcessor),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000521 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800523 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524
Yi Kong9b14ac62018-07-17 13:48:38 -0700525 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526
527 policy->getDispatcherConfiguration(&mConfig);
528}
529
530InputDispatcher::~InputDispatcher() {
531 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800532 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 resetKeyRepeatLocked();
535 releasePendingEventLocked();
536 drainInboundQueueLocked();
537 }
538
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000539 while (!mConnectionsByToken.empty()) {
540 sp<Connection> connection = mConnectionsByToken.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700541 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 }
543}
544
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700545status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700546 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700547 return ALREADY_EXISTS;
548 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700549 mThread = std::make_unique<InputThread>(
550 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
551 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700552}
553
554status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700555 if (mThread && mThread->isCallingThread()) {
556 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700557 return INVALID_OPERATION;
558 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700559 mThread.reset();
560 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700561}
562
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563void InputDispatcher::dispatchOnce() {
564 nsecs_t nextWakeupTime = LONG_LONG_MAX;
565 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800566 std::scoped_lock _l(mLock);
567 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568
569 // Run a dispatch loop if there are no pending commands.
570 // The dispatch loop might enqueue commands to run afterwards.
571 if (!haveCommandsLocked()) {
572 dispatchOnceInnerLocked(&nextWakeupTime);
573 }
574
575 // Run all pending commands if there are any.
576 // If any commands were run then force the next poll to wake up immediately.
577 if (runCommandsLockedInterruptible()) {
578 nextWakeupTime = LONG_LONG_MIN;
579 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800580
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700581 // If we are still waiting for ack on some events,
582 // we might have to wake up earlier to check if an app is anr'ing.
583 const nsecs_t nextAnrCheck = processAnrsLocked();
584 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
585
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800586 // We are about to enter an infinitely long sleep, because we have no commands or
587 // pending or queued events
588 if (nextWakeupTime == LONG_LONG_MAX) {
589 mDispatcherEnteredIdle.notify_all();
590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 } // release lock
592
593 // Wait for callback or timeout or wake. (make sure we round up, not down)
594 nsecs_t currentTime = now();
595 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
596 mLooper->pollOnce(timeoutMillis);
597}
598
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700599/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500600 * Raise ANR if there is no focused window.
601 * Before the ANR is raised, do a final state check:
602 * 1. The currently focused application must be the same one we are waiting for.
603 * 2. Ensure we still don't have a focused window.
604 */
605void InputDispatcher::processNoFocusedWindowAnrLocked() {
606 // Check if the application that we are waiting for is still focused.
607 std::shared_ptr<InputApplicationHandle> focusedApplication =
608 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
609 if (focusedApplication == nullptr ||
610 focusedApplication->getApplicationToken() !=
611 mAwaitedFocusedApplication->getApplicationToken()) {
612 // Unexpected because we should have reset the ANR timer when focused application changed
613 ALOGE("Waited for a focused window, but focused application has already changed to %s",
614 focusedApplication->getName().c_str());
615 return; // The focused application has changed.
616 }
617
618 const sp<InputWindowHandle>& focusedWindowHandle =
619 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
620 if (focusedWindowHandle != nullptr) {
621 return; // We now have a focused window. No need for ANR.
622 }
623 onAnrLocked(mAwaitedFocusedApplication);
624}
625
626/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700627 * Check if any of the connections' wait queues have events that are too old.
628 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
629 * Return the time at which we should wake up next.
630 */
631nsecs_t InputDispatcher::processAnrsLocked() {
632 const nsecs_t currentTime = now();
633 nsecs_t nextAnrCheck = LONG_LONG_MAX;
634 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
635 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
636 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500637 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700638 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500639 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700640 return LONG_LONG_MIN;
641 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500642 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
644 }
645 }
646
647 // Check if any connection ANRs are due
648 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
649 if (currentTime < nextAnrCheck) { // most likely scenario
650 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
651 }
652
653 // If we reached here, we have an unresponsive connection.
654 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
655 if (connection == nullptr) {
656 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
657 return nextAnrCheck;
658 }
659 connection->responsive = false;
660 // Stop waking up for this unresponsive connection
661 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000662 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700663 return LONG_LONG_MIN;
664}
665
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500666std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700667 sp<InputWindowHandle> window = getWindowHandleLocked(token);
668 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500669 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700670 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500671 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700672}
673
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
675 nsecs_t currentTime = now();
676
Jeff Browndc5992e2014-04-11 01:27:26 -0700677 // Reset the key repeat timer whenever normal dispatch is suspended while the
678 // device is in a non-interactive state. This is to ensure that we abort a key
679 // repeat if the device is just coming out of sleep.
680 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 resetKeyRepeatLocked();
682 }
683
684 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
685 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100686 if (DEBUG_FOCUS) {
687 ALOGD("Dispatch frozen. Waiting some more.");
688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 return;
690 }
691
692 // Optimize latency of app switches.
693 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
694 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
695 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
696 if (mAppSwitchDueTime < *nextWakeupTime) {
697 *nextWakeupTime = mAppSwitchDueTime;
698 }
699
700 // Ready to start a new event.
701 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700702 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700703 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 if (isAppSwitchDue) {
705 // The inbound queue is empty so the app switch key we were waiting
706 // for will never arrive. Stop waiting for it.
707 resetPendingAppSwitchLocked(false);
708 isAppSwitchDue = false;
709 }
710
711 // Synthesize a key repeat if appropriate.
712 if (mKeyRepeatState.lastKeyEntry) {
713 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
714 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
715 } else {
716 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
717 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
718 }
719 }
720 }
721
722 // Nothing to do if there is no pending event.
723 if (!mPendingEvent) {
724 return;
725 }
726 } else {
727 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700728 mPendingEvent = mInboundQueue.front();
729 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 traceInboundQueueLengthLocked();
731 }
732
733 // Poke user activity for this event.
734 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700735 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
738
739 // Now we have an event to dispatch.
740 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700741 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700743 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700745 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700747 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 }
749
750 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700751 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 }
753
754 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700755 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700756 const ConfigurationChangedEntry& typedEntry =
757 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700759 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700760 break;
761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700763 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700764 const DeviceResetEntry& typedEntry =
765 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 break;
769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100771 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700772 std::shared_ptr<FocusEntry> typedEntry =
773 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100774 dispatchFocusLocked(currentTime, typedEntry);
775 done = true;
776 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
777 break;
778 }
779
Prabir Pradhan99987712020-11-10 18:43:05 -0800780 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
781 const auto typedEntry =
782 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
783 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
784 done = true;
785 break;
786 }
787
arthurhungb89ccb02020-12-30 16:19:01 +0800788 case EventEntry::Type::DRAG: {
789 std::shared_ptr<DragEntry> typedEntry =
790 std::static_pointer_cast<DragEntry>(mPendingEvent);
791 dispatchDragLocked(currentTime, typedEntry);
792 done = true;
793 break;
794 }
795
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700796 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700797 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700800 resetPendingAppSwitchLocked(true);
801 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 } else if (dropReason == DropReason::NOT_DROPPED) {
803 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 }
805 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700806 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700807 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700809 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
810 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700812 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 break;
814 }
815
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700816 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700817 std::shared_ptr<MotionEntry> motionEntry =
818 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700819 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
820 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700822 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700825 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
826 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700828 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 }
Chris Yef59a2f42020-10-16 12:55:26 -0700831
832 case EventEntry::Type::SENSOR: {
833 std::shared_ptr<SensorEntry> sensorEntry =
834 std::static_pointer_cast<SensorEntry>(mPendingEvent);
835 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
836 dropReason = DropReason::APP_SWITCH;
837 }
838 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
839 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
840 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
841 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
842 dropReason = DropReason::STALE;
843 }
844 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
845 done = true;
846 break;
847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 }
849
850 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700852 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
Michael Wright3a981722015-06-10 15:26:13 +0100854 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855
856 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 }
859}
860
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700861/**
862 * Return true if the events preceding this incoming motion event should be dropped
863 * Return false otherwise (the default behaviour)
864 */
865bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700866 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700867 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700868
869 // Optimize case where the current application is unresponsive and the user
870 // decides to touch a window in a different application.
871 // If the application takes too long to catch up then we drop all events preceding
872 // the touch into the other window.
873 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700874 int32_t displayId = motionEntry.displayId;
875 int32_t x = static_cast<int32_t>(
876 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
877 int32_t y = static_cast<int32_t>(
878 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
879 sp<InputWindowHandle> touchedWindowHandle =
880 findTouchedWindowAtLocked(displayId, x, y, nullptr);
881 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700882 touchedWindowHandle->getApplicationToken() !=
883 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700884 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700885 ALOGI("Pruning input queue because user touched a different application while waiting "
886 "for %s",
887 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700888 return true;
889 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700890
891 // Alternatively, maybe there's a gesture monitor that could handle this event
892 std::vector<TouchedMonitor> gestureMonitors =
893 findTouchedGestureMonitorsLocked(displayId, {});
894 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
895 sp<Connection> connection =
896 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000897 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700898 // This monitor could take more input. Drop all events preceding this
899 // event, so that gesture monitor could get a chance to receive the stream
900 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
901 "responsive gesture monitor that may handle the event",
902 mAwaitedFocusedApplication->getName().c_str());
903 return true;
904 }
905 }
906 }
907
908 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
909 // yet been processed by some connections, the dispatcher will wait for these motion
910 // events to be processed before dispatching the key event. This is because these motion events
911 // may cause a new window to be launched, which the user might expect to receive focus.
912 // To prevent waiting forever for such events, just send the key to the currently focused window
913 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
914 ALOGD("Received a new pointer down event, stop waiting for events to process and "
915 "just send the pending key event to the focused window.");
916 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700917 }
918 return false;
919}
920
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700921bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700922 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700923 mInboundQueue.push_back(std::move(newEntry));
924 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 traceInboundQueueLengthLocked();
926
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700927 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700928 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 // Optimize app switch latency.
930 // If the application takes too long to catch up then we drop all events preceding
931 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700932 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700934 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700936 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700941 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700942 mAppSwitchSawKeyDown = false;
943 needWake = true;
944 }
945 }
946 }
947 break;
948 }
949
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700950 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700951 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
952 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700953 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100957 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700958 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
959 break;
960 }
961 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800962 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700963 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +0800964 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
965 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700966 // nothing to do
967 break;
968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970
971 return needWake;
972}
973
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700975 // Do not store sensor event in recent queue to avoid flooding the queue.
976 if (entry->type != EventEntry::Type::SENSOR) {
977 mRecentQueue.push_back(entry);
978 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700979 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700980 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 }
982}
983
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700985 int32_t y, TouchState* touchState,
986 bool addOutsideTargets,
arthurhungb89ccb02020-12-30 16:19:01 +0800987 bool addPortalWindows,
988 bool ignoreDragWindow) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700989 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
990 LOG_ALWAYS_FATAL(
991 "Must provide a valid touch state if adding portal windows or outside targets");
992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700994 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800995 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +0800996 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +0800997 continue;
998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1000 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +01001001 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002
1003 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +01001004 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
1005 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
1006 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001008 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1010 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001011 if (addPortalWindows) {
1012 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001013 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001014 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001015 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 // Found window.
1019 return windowHandle;
1020 }
1021 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001022
Michael Wright44753b12020-07-08 13:48:11 +01001023 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001024 touchState->addOrUpdateWindow(windowHandle,
1025 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1026 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001031 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032}
1033
Garfield Tane84e6f92019-08-29 17:28:41 -07001034std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001035 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001036 std::vector<TouchedMonitor> touchedMonitors;
1037
1038 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1039 addGestureMonitors(monitors, touchedMonitors);
1040 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1041 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1042 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1044 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001045 }
1046 return touchedMonitors;
1047}
1048
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001049void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 const char* reason;
1051 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001052 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 reason = "inbound event was dropped because the policy consumed it";
1057 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001058 case DropReason::DISABLED:
1059 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 ALOGI("Dropped event because input dispatch is disabled.");
1061 }
1062 reason = "inbound event was dropped because input dispatch is disabled";
1063 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001064 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 ALOGI("Dropped event because of pending overdue app switch.");
1066 reason = "inbound event was dropped because of pending overdue app switch";
1067 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001068 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 ALOGI("Dropped event because the current application is not responding and the user "
1070 "has started interacting with a different application.");
1071 reason = "inbound event was dropped because the current application is not responding "
1072 "and the user has started interacting with a different application";
1073 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 ALOGI("Dropped event because it is stale.");
1076 reason = "inbound event was dropped because it is stale";
1077 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001078 case DropReason::NO_POINTER_CAPTURE:
1079 ALOGI("Dropped event because there is no window with Pointer Capture.");
1080 reason = "inbound event was dropped because there is no window with Pointer Capture";
1081 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 case DropReason::NOT_DROPPED: {
1083 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 }
1087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001088 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001089 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1091 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001094 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001095 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1096 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1098 synthesizeCancelationEventsForAllConnectionsLocked(options);
1099 } else {
1100 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1101 synthesizeCancelationEventsForAllConnectionsLocked(options);
1102 }
1103 break;
1104 }
Chris Yef59a2f42020-10-16 12:55:26 -07001105 case EventEntry::Type::SENSOR: {
1106 break;
1107 }
arthurhungb89ccb02020-12-30 16:19:01 +08001108 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1109 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001110 break;
1111 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001113 case EventEntry::Type::CONFIGURATION_CHANGED:
1114 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001115 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001116 break;
1117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119}
1120
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001121static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1123 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124}
1125
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001126bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1127 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1128 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1129 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130}
1131
1132bool InputDispatcher::isAppSwitchPendingLocked() {
1133 return mAppSwitchDueTime != LONG_LONG_MAX;
1134}
1135
1136void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1137 mAppSwitchDueTime = LONG_LONG_MAX;
1138
1139#if DEBUG_APP_SWITCH
1140 if (handled) {
1141 ALOGD("App switch has arrived.");
1142 } else {
1143 ALOGD("App switch was abandoned.");
1144 }
1145#endif
1146}
1147
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001149 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150}
1151
1152bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001153 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 return false;
1155 }
1156
1157 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001158 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001159 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001161 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162
1163 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001164 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 return true;
1166}
1167
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001168void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1169 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170}
1171
1172void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001173 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001175 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 releaseInboundEventLocked(entry);
1177 }
1178 traceInboundQueueLengthLocked();
1179}
1180
1181void InputDispatcher::releasePendingEventLocked() {
1182 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001184 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186}
1187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001190 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191#if DEBUG_DISPATCH_CYCLE
1192 ALOGD("Injected inbound event was dropped.");
1193#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 }
1196 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001197 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 }
1199 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200}
1201
1202void InputDispatcher::resetKeyRepeatLocked() {
1203 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001204 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206}
1207
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001208std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1209 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210
Michael Wright2e732952014-09-24 13:26:59 -07001211 uint32_t policyFlags = entry->policyFlags &
1212 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214 std::shared_ptr<KeyEntry> newEntry =
1215 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1216 entry->source, entry->displayId, policyFlags, entry->action,
1217 entry->flags, entry->keyCode, entry->scanCode,
1218 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001220 newEntry->syntheticRepeat = true;
1221 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224}
1225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001226bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001229 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230#endif
1231
1232 // Reset key repeating in case a keyboard device was added or removed or something.
1233 resetKeyRepeatLocked();
1234
1235 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001236 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1237 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001239 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 return true;
1241}
1242
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1244 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1247 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248#endif
1249
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001250 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001251 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 synthesizeCancelationEventsForAllConnectionsLocked(options);
1253 return true;
1254}
1255
Vishnu Nairad321cd2020-08-20 16:40:21 -07001256void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001257 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001258 if (mPendingEvent != nullptr) {
1259 // Move the pending event to the front of the queue. This will give the chance
1260 // for the pending event to get dispatched to the newly focused window
1261 mInboundQueue.push_front(mPendingEvent);
1262 mPendingEvent = nullptr;
1263 }
1264
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 std::unique_ptr<FocusEntry> focusEntry =
1266 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1267 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001268
1269 // This event should go to the front of the queue, but behind all other focus events
1270 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001272 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 [](const std::shared_ptr<EventEntry>& event) {
1274 return event->type == EventEntry::Type::FOCUS;
1275 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001276
1277 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001278 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001279}
1280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001282 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001283 if (channel == nullptr) {
1284 return; // Window has gone away
1285 }
1286 InputTarget target;
1287 target.inputChannel = channel;
1288 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1289 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001290 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1291 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001292 std::string reason = std::string("reason=").append(entry->reason);
1293 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001294 dispatchEventLocked(currentTime, entry, {target});
1295}
1296
Prabir Pradhan99987712020-11-10 18:43:05 -08001297void InputDispatcher::dispatchPointerCaptureChangedLocked(
1298 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1299 DropReason& dropReason) {
1300 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001301 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1302 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1303 }
1304 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001305 // Pointer capture was already forcefully disabled because of focus change.
1306 dropReason = DropReason::NOT_DROPPED;
1307 return;
1308 }
1309
1310 // Set drop reason for early returns
1311 dropReason = DropReason::NO_POINTER_CAPTURE;
1312
1313 sp<IBinder> token;
1314 if (entry->pointerCaptureEnabled) {
1315 // Enable Pointer Capture
1316 if (!mFocusedWindowRequestedPointerCapture) {
1317 // This can happen if a window requests capture and immediately releases capture.
1318 ALOGW("No window requested Pointer Capture.");
1319 return;
1320 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001321 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001322 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1323 mWindowTokenWithPointerCapture = token;
1324 } else {
1325 // Disable Pointer Capture
1326 token = mWindowTokenWithPointerCapture;
1327 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001328 if (mFocusedWindowRequestedPointerCapture) {
1329 mFocusedWindowRequestedPointerCapture = false;
1330 setPointerCaptureLocked(false);
1331 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001332 }
1333
1334 auto channel = getInputChannelLocked(token);
1335 if (channel == nullptr) {
1336 // Window has gone away, clean up Pointer Capture state.
1337 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001338 if (mFocusedWindowRequestedPointerCapture) {
1339 mFocusedWindowRequestedPointerCapture = false;
1340 setPointerCaptureLocked(false);
1341 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001342 return;
1343 }
1344 InputTarget target;
1345 target.inputChannel = channel;
1346 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1347 entry->dispatchInProgress = true;
1348 dispatchEventLocked(currentTime, entry, {target});
1349
1350 dropReason = DropReason::NOT_DROPPED;
1351}
1352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 if (!entry->dispatchInProgress) {
1357 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1358 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1359 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1360 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001361 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 // We have seen two identical key downs in a row which indicates that the device
1363 // driver is automatically generating key repeats itself. We take note of the
1364 // repeat here, but we disable our own next key repeat timer since it is clear that
1365 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001366 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1367 // Make sure we don't get key down from a different device. If a different
1368 // device Id has same key pressed down, the new device Id will replace the
1369 // current one to hold the key repeat with repeat count reset.
1370 // In the future when got a KEY_UP on the device id, drop it and do not
1371 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1373 resetKeyRepeatLocked();
1374 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1375 } else {
1376 // Not a repeat. Save key down state in case we do see a repeat later.
1377 resetKeyRepeatLocked();
1378 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1379 }
1380 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001381 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1382 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001383 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001384#if DEBUG_INBOUND_EVENT_DETAILS
1385 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1386#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 resetKeyRepeatLocked();
1389 }
1390
1391 if (entry->repeatCount == 1) {
1392 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1393 } else {
1394 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1395 }
1396
1397 entry->dispatchInProgress = true;
1398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 }
1401
1402 // Handle case where the policy asked us to try again later last time.
1403 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1404 if (currentTime < entry->interceptKeyWakeupTime) {
1405 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1406 *nextWakeupTime = entry->interceptKeyWakeupTime;
1407 }
1408 return false; // wait until next wakeup
1409 }
1410 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1411 entry->interceptKeyWakeupTime = 0;
1412 }
1413
1414 // Give the policy a chance to intercept the key.
1415 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1416 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001417 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001418 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001419 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001420 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001421 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001423 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 return false; // wait for the command to run
1425 } else {
1426 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1427 }
1428 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001429 if (*dropReason == DropReason::NOT_DROPPED) {
1430 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 }
1432 }
1433
1434 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001435 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001436 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1438 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001439 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 return true;
1441 }
1442
1443 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001444 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001445 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001446 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001447 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 return false;
1449 }
1450
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001452 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 return true;
1454 }
1455
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001456 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001457 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 // Dispatch the key.
1460 dispatchEventLocked(currentTime, entry, inputTargets);
1461 return true;
1462}
1463
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001464void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001466 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1468 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1470 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1471 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472#endif
1473}
1474
Chris Yef59a2f42020-10-16 12:55:26 -07001475void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1476 mLock.unlock();
1477
1478 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1479 if (entry->accuracyChanged) {
1480 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1481 }
1482 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1483 entry->hwTimestamp, entry->values);
1484 mLock.lock();
1485}
1486
1487void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1488 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1489#if DEBUG_OUTBOUND_EVENT_DETAILS
1490 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1491 "source=0x%x, sensorType=%s",
1492 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001493 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001494#endif
1495 std::unique_ptr<CommandEntry> commandEntry =
1496 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1497 commandEntry->sensorEntry = entry;
1498 postCommandLocked(std::move(commandEntry));
1499}
1500
1501bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1502#if DEBUG_OUTBOUND_EVENT_DETAILS
1503 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1504 NamedEnum::string(sensorType).c_str());
1505#endif
1506 { // acquire lock
1507 std::scoped_lock _l(mLock);
1508
1509 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1510 std::shared_ptr<EventEntry> entry = *it;
1511 if (entry->type == EventEntry::Type::SENSOR) {
1512 it = mInboundQueue.erase(it);
1513 releaseInboundEventLocked(entry);
1514 }
1515 }
1516 }
1517 return true;
1518}
1519
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001521 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001522 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001524 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 entry->dispatchInProgress = true;
1526
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001527 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 }
1529
1530 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001531 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001532 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001533 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1534 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 return true;
1536 }
1537
1538 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1539
1540 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001541 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542
1543 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001544 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 if (isPointerEvent) {
1546 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001548 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001549 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 } else {
1551 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001553 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 return false;
1557 }
1558
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001559 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001561 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1562 return true;
1563 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001565 CancelationOptions::Mode mode(isPointerEvent
1566 ? CancelationOptions::CANCEL_POINTER_EVENTS
1567 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1568 CancelationOptions options(mode, "input event injection failed");
1569 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return true;
1571 }
1572
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001573 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001574 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001576 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001577 std::unordered_map<int32_t, TouchState>::iterator it =
1578 mTouchStatesByDisplay.find(entry->displayId);
1579 if (it != mTouchStatesByDisplay.end()) {
1580 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001581 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001582 // The event has gone through these portal windows, so we add monitoring targets of
1583 // the corresponding displays as well.
1584 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001585 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001586 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001587 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001588 }
1589 }
1590 }
1591 }
1592
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 // Dispatch the motion.
1594 if (conflictingPointerActions) {
1595 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001596 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 synthesizeCancelationEventsForAllConnectionsLocked(options);
1598 }
1599 dispatchEventLocked(currentTime, entry, inputTargets);
1600 return true;
1601}
1602
arthurhungb89ccb02020-12-30 16:19:01 +08001603void InputDispatcher::enqueueDragEventLocked(const sp<InputWindowHandle>& windowHandle,
1604 bool isExiting, const MotionEntry& motionEntry) {
1605 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1606 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1607 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1608 PointerCoords pointerCoords;
1609 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1610 pointerCoords.transform(windowHandle->getInfo()->transform);
1611
1612 std::unique_ptr<DragEntry> dragEntry =
1613 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1614 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1615 pointerCoords.getY());
1616
1617 enqueueInboundEventLocked(std::move(dragEntry));
1618}
1619
1620void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1621 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1622 if (channel == nullptr) {
1623 return; // Window has gone away
1624 }
1625 InputTarget target;
1626 target.inputChannel = channel;
1627 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1628 entry->dispatchInProgress = true;
1629 dispatchEventLocked(currentTime, entry, {target});
1630}
1631
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001632void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001634 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001635 ", policyFlags=0x%x, "
1636 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1637 "metaState=0x%x, buttonState=0x%x,"
1638 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001639 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1640 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1641 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001643 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001645 "x=%f, y=%f, pressure=%f, size=%f, "
1646 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1647 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1649 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1650 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1651 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1652 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1653 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1654 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1655 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1656 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1657 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 }
1659#endif
1660}
1661
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001662void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1663 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001665 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666#if DEBUG_DISPATCH_CYCLE
1667 ALOGD("dispatchEventToCurrentInputTargets");
1668#endif
1669
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001670 updateInteractionTokensLocked(*eventEntry, inputTargets);
1671
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1673
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001674 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001676 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001677 sp<Connection> connection =
1678 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001679 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001680 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001682 if (DEBUG_FOCUS) {
1683 ALOGD("Dropping event delivery to target with channel '%s' because it "
1684 "is no longer registered with the input dispatcher.",
1685 inputTarget.inputChannel->getName().c_str());
1686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 }
1688 }
1689}
1690
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001691void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1692 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1693 // If the policy decides to close the app, we will get a channel removal event via
1694 // unregisterInputChannel, and will clean up the connection that way. We are already not
1695 // sending new pointers to the connection when it blocked, but focused events will continue to
1696 // pile up.
1697 ALOGW("Canceling events for %s because it is unresponsive",
1698 connection->inputChannel->getName().c_str());
1699 if (connection->status == Connection::STATUS_NORMAL) {
1700 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1701 "application not responding");
1702 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 }
1704}
1705
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001706void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001707 if (DEBUG_FOCUS) {
1708 ALOGD("Resetting ANR timeouts.");
1709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710
1711 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001712 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001713 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714}
1715
Tiger Huang721e26f2018-07-24 22:26:19 +08001716/**
1717 * Get the display id that the given event should go to. If this event specifies a valid display id,
1718 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1719 * Focused display is the display that the user most recently interacted with.
1720 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001721int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001722 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001723 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001724 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001725 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1726 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001727 break;
1728 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001729 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001730 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1731 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001732 break;
1733 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001734 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001735 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001736 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001737 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001738 case EventEntry::Type::SENSOR:
1739 case EventEntry::Type::DRAG: {
Chris Yef59a2f42020-10-16 12:55:26 -07001740 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 return ADISPLAY_ID_NONE;
1742 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001743 }
1744 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1745}
1746
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001747bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1748 const char* focusedWindowName) {
1749 if (mAnrTracker.empty()) {
1750 // already processed all events that we waited for
1751 mKeyIsWaitingForEventsTimeout = std::nullopt;
1752 return false;
1753 }
1754
1755 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1756 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001757 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001758 mKeyIsWaitingForEventsTimeout = currentTime +
1759 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1760 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001761 return true;
1762 }
1763
1764 // We still have pending events, and already started the timer
1765 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1766 return true; // Still waiting
1767 }
1768
1769 // Waited too long, and some connection still hasn't processed all motions
1770 // Just send the key to the focused window
1771 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1772 focusedWindowName);
1773 mKeyIsWaitingForEventsTimeout = std::nullopt;
1774 return false;
1775}
1776
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001777InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1778 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1779 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001780 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
Tiger Huang721e26f2018-07-24 22:26:19 +08001782 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001783 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001784 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001785 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1786
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 // If there is no currently focused window and no focused application
1788 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001789 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1790 ALOGI("Dropping %s event because there is no focused window or focused application in "
1791 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001792 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1797 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1798 // start interacting with another application via touch (app switch). This code can be removed
1799 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1800 // an app is expected to have a focused window.
1801 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1802 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1803 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001804 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1805 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1806 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001807 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001808 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001809 ALOGW("Waiting because no window has focus but %s may eventually add a "
1810 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001811 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001814 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1815 // Already raised ANR. Drop the event
1816 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001817 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001818 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001819 } else {
1820 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001822 }
1823 }
1824
1825 // we have a valid, non-null focused window
1826 resetNoFocusedWindowTimeoutLocked();
1827
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
1832
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833 if (focusedWindowHandle->getInfo()->paused) {
1834 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001835 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 }
1837
1838 // If the event is a key event, then we must wait for all previous events to
1839 // complete before delivering it because previous events may have the
1840 // side-effect of transferring focus to a different window and we want to
1841 // ensure that the following keys are sent to the new window.
1842 //
1843 // Suppose the user touches a button in a window then immediately presses "A".
1844 // If the button causes a pop-up window to appear then we want to ensure that
1845 // the "A" key is delivered to the new pop-up window. This is because users
1846 // often anticipate pending UI changes when typing on a keyboard.
1847 // To obtain this behavior, we must serialize key events with respect to all
1848 // prior input events.
1849 if (entry.type == EventEntry::Type::KEY) {
1850 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1851 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 }
1855
1856 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001857 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001858 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1859 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
1861 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863}
1864
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001865/**
1866 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1867 * that are currently unresponsive.
1868 */
1869std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1870 const std::vector<TouchedMonitor>& monitors) const {
1871 std::vector<TouchedMonitor> responsiveMonitors;
1872 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1873 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1874 sp<Connection> connection = getConnectionLocked(
1875 monitor.monitor.inputChannel->getConnectionToken());
1876 if (connection == nullptr) {
1877 ALOGE("Could not find connection for monitor %s",
1878 monitor.monitor.inputChannel->getName().c_str());
1879 return false;
1880 }
1881 if (!connection->responsive) {
1882 ALOGW("Unresponsive monitor %s will not get the new gesture",
1883 connection->inputChannel->getName().c_str());
1884 return false;
1885 }
1886 return true;
1887 });
1888 return responsiveMonitors;
1889}
1890
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001891InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1892 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1893 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001894 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 enum InjectionPermission {
1896 INJECTION_PERMISSION_UNKNOWN,
1897 INJECTION_PERMISSION_GRANTED,
1898 INJECTION_PERMISSION_DENIED
1899 };
1900
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 // For security reasons, we defer updating the touch state until we are sure that
1902 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001903 int32_t displayId = entry.displayId;
1904 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1906
1907 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001910 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1911 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001913 // Copy current touch state into tempTouchState.
1914 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1915 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001916 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001917 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001918 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1919 mTouchStatesByDisplay.find(displayId);
1920 if (oldStateIt != mTouchStatesByDisplay.end()) {
1921 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001923 }
1924
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001925 bool isSplit = tempTouchState.split;
1926 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1927 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1928 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001929 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1930 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1931 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1932 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1933 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001934 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 bool wrongDevice = false;
1936 if (newGesture) {
1937 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001938 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001939 ALOGI("Dropping event because a pointer for a different device is already down "
1940 "in display %" PRId32,
1941 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001942 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 switchedDevice = false;
1945 wrongDevice = true;
1946 goto Failed;
1947 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001948 tempTouchState.reset();
1949 tempTouchState.down = down;
1950 tempTouchState.deviceId = entry.deviceId;
1951 tempTouchState.source = entry.source;
1952 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001954 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001955 ALOGI("Dropping move event because a pointer for a different device is already active "
1956 "in display %" PRId32,
1957 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001958 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001960 switchedDevice = false;
1961 wrongDevice = true;
1962 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 }
1964
1965 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1966 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1967
Garfield Tan00f511d2019-06-12 16:55:40 -07001968 int32_t x;
1969 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001971 // Always dispatch mouse events to cursor position.
1972 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001973 x = int32_t(entry.xCursorPosition);
1974 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001975 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001976 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1977 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001978 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001979 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001980 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001981 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1982 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001983
1984 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001985 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001986 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001989 if (newTouchedWindowHandle != nullptr &&
1990 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001991 // New window supports splitting, but we should never split mouse events.
1992 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 } else if (isSplit) {
1994 // New window does not support splitting but we have already split events.
1995 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001996 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998
1999 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002000 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002002 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002003 }
2004
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2006 ALOGI("Not sending touch event to %s because it is paused",
2007 newTouchedWindowHandle->getName().c_str());
2008 newTouchedWindowHandle = nullptr;
2009 }
2010
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002011 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002012 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05002013 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2014 if (!isResponsive) {
2015 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002016 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2017 newTouchedWindowHandle = nullptr;
2018 }
2019 }
2020
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002021 // Drop events that can't be trusted due to occlusion
2022 if (newTouchedWindowHandle != nullptr &&
2023 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2024 TouchOcclusionInfo occlusionInfo =
2025 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002026 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002027 if (DEBUG_TOUCH_OCCLUSION) {
2028 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2029 for (const auto& log : occlusionInfo.debugInfo) {
2030 ALOGD("%s", log.c_str());
2031 }
2032 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00002033 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2034 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2035 ALOGW("Dropping untrusted touch event due to %s/%d",
2036 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2037 newTouchedWindowHandle = nullptr;
2038 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002039 }
2040 }
2041
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002042 // Also don't send the new touch event to unresponsive gesture monitors
2043 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
2044
Michael Wright3dd60e22019-03-27 22:06:44 +00002045 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2046 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002047 "(%d, %d) in display %" PRId32 ".",
2048 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002049 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00002050 goto Failed;
2051 }
2052
2053 if (newTouchedWindowHandle != nullptr) {
2054 // Set target flags.
2055 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2056 if (isSplit) {
2057 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2060 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2061 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2062 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2063 }
2064
2065 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002066 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2067 newHoverWindowHandle = nullptr;
2068 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002069 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002070 }
2071
2072 // Update the temporary touch state.
2073 BitSet32 pointerIds;
2074 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002075 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002076 pointerIds.markBit(pointerId);
2077 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002078 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002081 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 } else {
2083 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2084
2085 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002086 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002087 if (DEBUG_FOCUS) {
2088 ALOGD("Dropping event because the pointer is not down or we previously "
2089 "dropped the pointer down event in display %" PRId32,
2090 displayId);
2091 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 goto Failed;
2094 }
2095
arthurhung6d4bed92021-03-17 11:59:33 +08002096 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002097
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002099 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002101 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2102 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103
2104 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002105 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002106 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002107 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2108 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002109 if (DEBUG_FOCUS) {
2110 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2111 oldTouchedWindowHandle->getName().c_str(),
2112 newTouchedWindowHandle->getName().c_str(), displayId);
2113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002115 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2116 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2117 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118
2119 // Make a slippery entrance into the new window.
2120 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2121 isSplit = true;
2122 }
2123
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002124 int32_t targetFlags =
2125 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 if (isSplit) {
2127 targetFlags |= InputTarget::FLAG_SPLIT;
2128 }
2129 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2130 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002131 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2132 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 }
2134
2135 BitSet32 pointerIds;
2136 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002137 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002139 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 }
2141 }
2142 }
2143
2144 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002145 // Let the previous window know that the hover sequence is over, unless we already did it
2146 // when dispatching it as is to newTouchedWindowHandle.
2147 if (mLastHoverWindowHandle != nullptr &&
2148 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2149 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150#if DEBUG_HOVER
2151 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002152 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002154 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2155 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157
Garfield Tandf26e862020-07-01 20:18:19 -07002158 // Let the new window know that the hover sequence is starting, unless we already did it
2159 // when dispatching it as is to newTouchedWindowHandle.
2160 if (newHoverWindowHandle != nullptr &&
2161 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2162 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163#if DEBUG_HOVER
2164 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002167 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2168 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2169 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171 }
2172
2173 // Check permission to inject into all touched foreground windows and ensure there
2174 // is at least one touched foreground window.
2175 {
2176 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002177 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2179 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002180 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002181 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 injectionPermission = INJECTION_PERMISSION_DENIED;
2183 goto Failed;
2184 }
2185 }
2186 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002187 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002188 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002189 ALOGI("Dropping event because there is no touched foreground window in display "
2190 "%" PRId32 " or gesture monitor to receive it.",
2191 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002192 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 goto Failed;
2194 }
2195
2196 // Permission granted to injection into all touched foreground windows.
2197 injectionPermission = INJECTION_PERMISSION_GRANTED;
2198 }
2199
2200 // Check whether windows listening for outside touches are owned by the same UID. If it is
2201 // set the policy flag that we will not reveal coordinate information to this window.
2202 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2203 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002205 if (foregroundWindowHandle) {
2206 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002207 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002208 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2209 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2210 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002211 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2212 InputTarget::FLAG_ZERO_COORDS,
2213 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 }
2216 }
2217 }
2218 }
2219
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 // If this is the first pointer going down and the touched window has a wallpaper
2221 // then also add the touched wallpaper windows so they are locked in for the duration
2222 // of the touch gesture.
2223 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2224 // engine only supports touch events. We would need to add a mechanism similar
2225 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2226 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2227 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002228 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002229 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002230 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002231 getWindowHandlesLocked(displayId);
2232 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002234 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002235 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002236 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002237 .addOrUpdateWindow(windowHandle,
2238 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2239 InputTarget::
2240 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2241 InputTarget::FLAG_DISPATCH_AS_IS,
2242 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 }
2244 }
2245 }
2246 }
2247
2248 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002249 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002253 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
2255
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002256 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002257 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002259 }
2260
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 // Drop the outside or hover touch windows since we will not care about them
2262 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002263 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
2265Failed:
2266 // Check injection permission once and for all.
2267 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002268 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 injectionPermission = INJECTION_PERMISSION_GRANTED;
2270 } else {
2271 injectionPermission = INJECTION_PERMISSION_DENIED;
2272 }
2273 }
2274
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002275 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2276 return injectionResult;
2277 }
2278
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002280 if (!wrongDevice) {
2281 if (switchedDevice) {
2282 if (DEBUG_FOCUS) {
2283 ALOGD("Conflicting pointer actions: Switched to a different device.");
2284 }
2285 *outConflictingPointerActions = true;
2286 }
2287
2288 if (isHoverAction) {
2289 // Started hovering, therefore no longer down.
2290 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002291 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002292 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2293 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 *outConflictingPointerActions = true;
2296 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002297 tempTouchState.reset();
2298 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2299 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2300 tempTouchState.deviceId = entry.deviceId;
2301 tempTouchState.source = entry.source;
2302 tempTouchState.displayId = displayId;
2303 }
2304 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2305 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2306 // All pointers up or canceled.
2307 tempTouchState.reset();
2308 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2309 // First pointer went down.
2310 if (oldState && oldState->down) {
2311 if (DEBUG_FOCUS) {
2312 ALOGD("Conflicting pointer actions: Down received while already down.");
2313 }
2314 *outConflictingPointerActions = true;
2315 }
2316 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2317 // One pointer went up.
2318 if (isSplit) {
2319 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2320 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002322 for (size_t i = 0; i < tempTouchState.windows.size();) {
2323 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2324 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2325 touchedWindow.pointerIds.clearBit(pointerId);
2326 if (touchedWindow.pointerIds.isEmpty()) {
2327 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2328 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002331 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002333 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002334 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002335
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002336 // Save changes unless the action was scroll in which case the temporary touch
2337 // state was only valid for this one action.
2338 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2339 if (tempTouchState.displayId >= 0) {
2340 mTouchStatesByDisplay[displayId] = tempTouchState;
2341 } else {
2342 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002346 // Update hover state.
2347 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
2349
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 return injectionResult;
2351}
2352
arthurhung6d4bed92021-03-17 11:59:33 +08002353void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2354 const sp<InputWindowHandle> dropWindow =
2355 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2356 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2357 true /*ignoreDragWindow*/);
2358 if (dropWindow) {
2359 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2360 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002361 } else {
2362 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002363 }
2364 mDragState.reset();
2365}
2366
2367void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2368 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002369 return;
2370 }
2371
arthurhung6d4bed92021-03-17 11:59:33 +08002372 if (!mDragState->isStartDrag) {
2373 mDragState->isStartDrag = true;
2374 mDragState->isStylusButtonDownAtStart =
2375 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2376 }
2377
arthurhungb89ccb02020-12-30 16:19:01 +08002378 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2379 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2380 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2381 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002382 // Handle the special case : stylus button no longer pressed.
2383 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2384 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2385 finishDragAndDrop(entry.displayId, x, y);
2386 return;
2387 }
2388
arthurhungb89ccb02020-12-30 16:19:01 +08002389 const sp<InputWindowHandle> hoverWindowHandle =
arthurhung6d4bed92021-03-17 11:59:33 +08002390 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
arthurhungb89ccb02020-12-30 16:19:01 +08002391 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2392 true /*ignoreDragWindow*/);
2393 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002394 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2395 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2396 if (mDragState->dragHoverWindowHandle != nullptr) {
2397 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2398 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002399 }
arthurhung6d4bed92021-03-17 11:59:33 +08002400 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002401 }
2402 // enqueue drag location if needed.
2403 if (hoverWindowHandle != nullptr) {
2404 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2405 }
arthurhung6d4bed92021-03-17 11:59:33 +08002406 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2407 finishDragAndDrop(entry.displayId, x, y);
2408 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Arthur Hung6d0571e2021-04-09 20:18:16 +08002409 notifyDropWindowLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002410 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002411 }
2412}
2413
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 int32_t targetFlags, BitSet32 pointerIds,
2416 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002417 std::vector<InputTarget>::iterator it =
2418 std::find_if(inputTargets.begin(), inputTargets.end(),
2419 [&windowHandle](const InputTarget& inputTarget) {
2420 return inputTarget.inputChannel->getConnectionToken() ==
2421 windowHandle->getToken();
2422 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002423
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002424 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002425
2426 if (it == inputTargets.end()) {
2427 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002428 std::shared_ptr<InputChannel> inputChannel =
2429 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002430 if (inputChannel == nullptr) {
2431 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2432 return;
2433 }
2434 inputTarget.inputChannel = inputChannel;
2435 inputTarget.flags = targetFlags;
2436 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Evan Rosky84f07f02021-04-16 10:42:42 -07002437 inputTarget.displaySize =
2438 vec2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 inputTargets.push_back(inputTarget);
2440 it = inputTargets.end() - 1;
2441 }
2442
2443 ALOG_ASSERT(it->flags == targetFlags);
2444 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2445
chaviw1ff3d1e2020-07-01 15:53:47 -07002446 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447}
2448
Michael Wright3dd60e22019-03-27 22:06:44 +00002449void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002450 int32_t displayId, float xOffset,
2451 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002452 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2453 mGlobalMonitorsByDisplay.find(displayId);
2454
2455 if (it != mGlobalMonitorsByDisplay.end()) {
2456 const std::vector<Monitor>& monitors = it->second;
2457 for (const Monitor& monitor : monitors) {
2458 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
2461}
2462
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2464 float yOffset,
2465 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002466 InputTarget target;
2467 target.inputChannel = monitor.inputChannel;
2468 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002469 ui::Transform t;
2470 t.set(xOffset, yOffset);
2471 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002472 inputTargets.push_back(target);
2473}
2474
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 const InjectionState* injectionState) {
2477 if (injectionState &&
2478 (windowHandle == nullptr ||
2479 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2480 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002481 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 "owned by uid %d",
2484 injectionState->injectorPid, injectionState->injectorUid,
2485 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 } else {
2487 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
2490 return false;
2491 }
2492 return true;
2493}
2494
Robert Carrc9bf1d32020-04-13 17:21:08 -07002495/**
2496 * Indicate whether one window handle should be considered as obscuring
2497 * another window handle. We only check a few preconditions. Actually
2498 * checking the bounds is left to the caller.
2499 */
2500static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2501 const sp<InputWindowHandle>& otherHandle) {
2502 // Compare by token so cloned layers aren't counted
2503 if (haveSameToken(windowHandle, otherHandle)) {
2504 return false;
2505 }
2506 auto info = windowHandle->getInfo();
2507 auto otherInfo = otherHandle->getInfo();
2508 if (!otherInfo->visible) {
2509 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002510 } else if (otherInfo->alpha == 0 &&
2511 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2512 // Those act as if they were invisible, so we don't need to flag them.
2513 // We do want to potentially flag touchable windows even if they have 0
2514 // opacity, since they can consume touches and alter the effects of the
2515 // user interaction (eg. apps that rely on
2516 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2517 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2518 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002519 } else if (info->ownerUid == otherInfo->ownerUid) {
2520 // If ownerUid is the same we don't generate occlusion events as there
2521 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002522 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002523 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002524 return false;
2525 } else if (otherInfo->displayId != info->displayId) {
2526 return false;
2527 }
2528 return true;
2529}
2530
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002531/**
2532 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2533 * untrusted, one should check:
2534 *
2535 * 1. If result.hasBlockingOcclusion is true.
2536 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2537 * BLOCK_UNTRUSTED.
2538 *
2539 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2540 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2541 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2542 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2543 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2544 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2545 *
2546 * If neither of those is true, then it means the touch can be allowed.
2547 */
2548InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2549 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002550 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2551 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002552 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2553 TouchOcclusionInfo info;
2554 info.hasBlockingOcclusion = false;
2555 info.obscuringOpacity = 0;
2556 info.obscuringUid = -1;
2557 std::map<int32_t, float> opacityByUid;
2558 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2559 if (windowHandle == otherHandle) {
2560 break; // All future windows are below us. Exit early.
2561 }
2562 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002563 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2564 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002565 if (DEBUG_TOUCH_OCCLUSION) {
2566 info.debugInfo.push_back(
2567 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2568 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002569 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2570 // we perform the checks below to see if the touch can be propagated or not based on the
2571 // window's touch occlusion mode
2572 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2573 info.hasBlockingOcclusion = true;
2574 info.obscuringUid = otherInfo->ownerUid;
2575 info.obscuringPackage = otherInfo->packageName;
2576 break;
2577 }
2578 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2579 uint32_t uid = otherInfo->ownerUid;
2580 float opacity =
2581 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2582 // Given windows A and B:
2583 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2584 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2585 opacityByUid[uid] = opacity;
2586 if (opacity > info.obscuringOpacity) {
2587 info.obscuringOpacity = opacity;
2588 info.obscuringUid = uid;
2589 info.obscuringPackage = otherInfo->packageName;
2590 }
2591 }
2592 }
2593 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002594 if (DEBUG_TOUCH_OCCLUSION) {
2595 info.debugInfo.push_back(
2596 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2597 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002598 return info;
2599}
2600
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002601std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2602 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002603 return StringPrintf(INDENT2
2604 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2605 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2606 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2607 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002608 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002609 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002610 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002611 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2612 info->frameTop, info->frameRight, info->frameBottom,
2613 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002614 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2615 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2616 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002617}
2618
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002619bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2620 if (occlusionInfo.hasBlockingOcclusion) {
2621 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2622 occlusionInfo.obscuringUid);
2623 return false;
2624 }
2625 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2626 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2627 "%.2f, maximum allowed = %.2f)",
2628 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2629 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2630 return false;
2631 }
2632 return true;
2633}
2634
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2636 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002638 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002639 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002640 if (windowHandle == otherHandle) {
2641 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002644 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002645 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 return true;
2647 }
2648 }
2649 return false;
2650}
2651
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002652bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2653 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002654 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002655 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002656 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002657 if (windowHandle == otherHandle) {
2658 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002659 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002660 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002661 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002662 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002663 return true;
2664 }
2665 }
2666 return false;
2667}
2668
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002669std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002670 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002672 if (applicationHandle != nullptr) {
2673 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002674 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 } else {
2676 return applicationHandle->getName();
2677 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002678 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002679 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002681 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683}
2684
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002685void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002686 if (eventEntry.type == EventEntry::Type::FOCUS ||
arthurhungb89ccb02020-12-30 16:19:01 +08002687 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2688 eventEntry.type == EventEntry::Type::DRAG) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002689 // Focus or pointer capture changed events are passed to apps, but do not represent user
2690 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002691 return;
2692 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002693 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002694 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002695 if (focusedWindowHandle != nullptr) {
2696 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002697 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002699 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700#endif
2701 return;
2702 }
2703 }
2704
2705 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002706 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002707 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002708 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2709 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002710 return;
2711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002713 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002714 eventType = USER_ACTIVITY_EVENT_TOUCH;
2715 }
2716 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002718 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002719 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2720 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 return;
2722 }
2723 eventType = USER_ACTIVITY_EVENT_BUTTON;
2724 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002726 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002727 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002728 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002729 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08002730 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2731 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002732 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002733 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002734 break;
2735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002738 std::unique_ptr<CommandEntry> commandEntry =
2739 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002742 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002743 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744}
2745
2746void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002748 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002749 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002750 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002752 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002753 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002754 ATRACE_NAME(message.c_str());
2755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756#if DEBUG_DISPATCH_CYCLE
2757 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002758 "globalScaleFactor=%f, pointerIds=0x%x %s",
2759 connection->getInputChannelName().c_str(), inputTarget.flags,
2760 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2761 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762#endif
2763
2764 // Skip this event if the connection status is not normal.
2765 // We don't want to enqueue additional outbound events if the connection is broken.
2766 if (connection->status != Connection::STATUS_NORMAL) {
2767#if DEBUG_DISPATCH_CYCLE
2768 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770#endif
2771 return;
2772 }
2773
2774 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002775 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2776 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2777 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002778 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002780 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002781 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002782 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002783 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 if (!splitMotionEntry) {
2785 return; // split event was dropped
2786 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002787 if (DEBUG_FOCUS) {
2788 ALOGD("channel '%s' ~ Split motion event.",
2789 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002790 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002791 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002792 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2793 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 return;
2795 }
2796 }
2797
2798 // Not splitting. Enqueue dispatch entries for the event as is.
2799 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2800}
2801
2802void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002803 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002804 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002805 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002806 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002808 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002809 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002810 ATRACE_NAME(message.c_str());
2811 }
2812
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002813 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814
2815 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002816 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002818 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002819 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002820 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002822 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002824 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002826 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002827 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828
2829 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002830 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 startDispatchCycleLocked(currentTime, connection);
2832 }
2833}
2834
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002836 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002837 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002839 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2841 connection->getInputChannelName().c_str(),
2842 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002843 ATRACE_NAME(message.c_str());
2844 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002845 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 if (!(inputTargetFlags & dispatchMode)) {
2847 return;
2848 }
2849 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2850
2851 // This is a new event.
2852 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002853 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002854 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002856 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2857 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002858 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002860 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002861 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002862 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002863 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002864 dispatchEntry->resolvedAction = keyEntry.action;
2865 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002867 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2868 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002870 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2871 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002873 return; // skip the inconsistent event
2874 }
2875 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002878 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002879 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002880 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2881 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2882 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2883 static_cast<int32_t>(IdGenerator::Source::OTHER);
2884 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2886 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2887 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2888 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2889 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2890 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2891 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2892 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2893 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2894 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2895 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002896 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002897 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 }
2899 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002900 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2901 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002903 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2904 "event",
2905 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906#endif
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00002907 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2908 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2914 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2915 }
2916 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2917 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2921 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2924 "event",
2925 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 return; // skip the inconsistent event
2928 }
2929
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002930 dispatchEntry->resolvedEventId =
2931 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2932 ? mIdGenerator.nextId()
2933 : motionEntry.id;
2934 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2935 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2936 ") to MotionEvent(id=0x%" PRIx32 ").",
2937 motionEntry.id, dispatchEntry->resolvedEventId);
2938 ATRACE_NAME(message.c_str());
2939 }
2940
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002941 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2942 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2943 // Skip reporting pointer down outside focus to the policy.
2944 break;
2945 }
2946
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002947 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002948 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949
2950 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002952 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08002953 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2954 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002955 break;
2956 }
Chris Yef59a2f42020-10-16 12:55:26 -07002957 case EventEntry::Type::SENSOR: {
2958 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2959 break;
2960 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002961 case EventEntry::Type::CONFIGURATION_CHANGED:
2962 case EventEntry::Type::DEVICE_RESET: {
2963 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002964 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002965 break;
2966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 }
2968
2969 // Remember that we are waiting for this dispatch to complete.
2970 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002971 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
2973
2974 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002975 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00002976 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07002977}
2978
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002979/**
2980 * This function is purely for debugging. It helps us understand where the user interaction
2981 * was taking place. For example, if user is touching launcher, we will see a log that user
2982 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2983 * We will see both launcher and wallpaper in that list.
2984 * Once the interaction with a particular set of connections starts, no new logs will be printed
2985 * until the set of interacted connections changes.
2986 *
2987 * The following items are skipped, to reduce the logspam:
2988 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2989 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2990 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2991 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2992 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002993 */
2994void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2995 const std::vector<InputTarget>& targets) {
2996 // Skip ACTION_UP events, and all events other than keys and motions
2997 if (entry.type == EventEntry::Type::KEY) {
2998 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2999 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3000 return;
3001 }
3002 } else if (entry.type == EventEntry::Type::MOTION) {
3003 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3004 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3005 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3006 return;
3007 }
3008 } else {
3009 return; // Not a key or a motion
3010 }
3011
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003012 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003013 std::vector<sp<Connection>> newConnections;
3014 for (const InputTarget& target : targets) {
3015 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3016 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3017 continue; // Skip windows that receive ACTION_OUTSIDE
3018 }
3019
3020 sp<IBinder> token = target.inputChannel->getConnectionToken();
3021 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003022 if (connection == nullptr) {
3023 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003024 }
3025 newConnectionTokens.insert(std::move(token));
3026 newConnections.emplace_back(connection);
3027 }
3028 if (newConnectionTokens == mInteractionConnectionTokens) {
3029 return; // no change
3030 }
3031 mInteractionConnectionTokens = newConnectionTokens;
3032
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003033 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003034 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003035 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003036 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003037 std::string message = "Interaction with: " + targetList;
3038 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003039 message += "<none>";
3040 }
3041 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3042}
3043
chaviwfd6d3512019-03-25 13:23:49 -07003044void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003045 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003046 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003047 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3048 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003049 return;
3050 }
3051
Vishnu Nairc519ff72021-01-21 08:23:08 -08003052 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003053 if (focusedToken == token) {
3054 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003055 return;
3056 }
3057
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003058 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3059 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003060 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07003061 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062}
3063
3064void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003066 if (ATRACE_ENABLED()) {
3067 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003068 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003069 ATRACE_NAME(message.c_str());
3070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073#endif
3074
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003075 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3076 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003078 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003079 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003080 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081
3082 // Publish the event.
3083 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003084 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3085 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003086 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003087 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3088 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003091 status = connection->inputPublisher
3092 .publishKeyEvent(dispatchEntry->seq,
3093 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3094 keyEntry.source, keyEntry.displayId,
3095 std::move(hmac), dispatchEntry->resolvedAction,
3096 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3097 keyEntry.scanCode, keyEntry.metaState,
3098 keyEntry.repeatCount, keyEntry.downTime,
3099 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003103 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003104 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003107 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003108
chaviw82357092020-01-28 13:13:06 -08003109 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003110 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3112 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003113 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003114 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3115 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003116 // Don't apply window scale here since we don't want scale to affect raw
3117 // coordinates. The scale will be sent back to the client and applied
3118 // later when requesting relative coordinates.
3119 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3120 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 }
3122 usingCoords = scaledCoords;
3123 }
3124 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 // We don't want the dispatch target to know.
3126 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003127 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 scaledCoords[i].clear();
3129 }
3130 usingCoords = scaledCoords;
3131 }
3132 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003133
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003134 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135
3136 // Publish the motion event.
3137 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003138 .publishMotionEvent(dispatchEntry->seq,
3139 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003140 motionEntry.deviceId, motionEntry.source,
3141 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003142 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003143 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003145 motionEntry.edgeFlags, motionEntry.metaState,
3146 motionEntry.buttonState,
3147 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003148 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003149 motionEntry.xPrecision, motionEntry.yPrecision,
3150 motionEntry.xCursorPosition,
3151 motionEntry.yCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003152 dispatchEntry->displaySize.x,
3153 dispatchEntry->displaySize.y,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003154 motionEntry.downTime, motionEntry.eventTime,
3155 motionEntry.pointerCount,
3156 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 break;
3158 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003159
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003160 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003162 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 focusEntry.id,
3164 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003165 mInTouchMode);
3166 break;
3167 }
3168
Prabir Pradhan99987712020-11-10 18:43:05 -08003169 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3170 const auto& captureEntry =
3171 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3172 status = connection->inputPublisher
3173 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3174 captureEntry.pointerCaptureEnabled);
3175 break;
3176 }
3177
arthurhungb89ccb02020-12-30 16:19:01 +08003178 case EventEntry::Type::DRAG: {
3179 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3180 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3181 dragEntry.id, dragEntry.x,
3182 dragEntry.y,
3183 dragEntry.isExiting);
3184 break;
3185 }
3186
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003187 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003188 case EventEntry::Type::DEVICE_RESET:
3189 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003190 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003191 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 }
3195
3196 // Check the result.
3197 if (status) {
3198 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003199 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 "This is unexpected because the wait queue is empty, so the pipe "
3202 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003203 "event to it, status=%s(%d)",
3204 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3205 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3207 } else {
3208 // Pipe is full and we are waiting for the app to finish process some events
3209 // before sending more events to it.
3210#if DEBUG_DISPATCH_CYCLE
3211 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 "waiting for the application to catch up",
3213 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 }
3216 } else {
3217 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003218 "status=%s(%d)",
3219 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3220 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3222 }
3223 return;
3224 }
3225
3226 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003227 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3228 connection->outboundQueue.end(),
3229 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003230 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003231 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003232 if (connection->responsive) {
3233 mAnrTracker.insert(dispatchEntry->timeoutTime,
3234 connection->inputChannel->getConnectionToken());
3235 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003236 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 }
3238}
3239
chaviw09c8d2d2020-08-24 15:48:26 -07003240std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3241 size_t size;
3242 switch (event.type) {
3243 case VerifiedInputEvent::Type::KEY: {
3244 size = sizeof(VerifiedKeyEvent);
3245 break;
3246 }
3247 case VerifiedInputEvent::Type::MOTION: {
3248 size = sizeof(VerifiedMotionEvent);
3249 break;
3250 }
3251 }
3252 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3253 return mHmacKeyManager.sign(start, size);
3254}
3255
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003256const std::array<uint8_t, 32> InputDispatcher::getSignature(
3257 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3258 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3259 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3260 // Only sign events up and down events as the purely move events
3261 // are tied to their up/down counterparts so signing would be redundant.
3262 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3263 verifiedEvent.actionMasked = actionMasked;
3264 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003265 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003266 }
3267 return INVALID_HMAC;
3268}
3269
3270const std::array<uint8_t, 32> InputDispatcher::getSignature(
3271 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3272 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3273 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3274 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003275 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003276}
3277
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003280 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281#if DEBUG_DISPATCH_CYCLE
3282 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284#endif
3285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003286 if (connection->status == Connection::STATUS_BROKEN ||
3287 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 return;
3289 }
3290
3291 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003292 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293}
3294
3295void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 const sp<Connection>& connection,
3297 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298#if DEBUG_DISPATCH_CYCLE
3299 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301#endif
3302
3303 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003304 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003305 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003306 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003307 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
3309 // The connection appears to be unrecoverably broken.
3310 // Ignore already broken or zombie connections.
3311 if (connection->status == Connection::STATUS_NORMAL) {
3312 connection->status = Connection::STATUS_BROKEN;
3313
3314 if (notify) {
3315 // Notify other system components.
3316 onDispatchCycleBrokenLocked(currentTime, connection);
3317 }
3318 }
3319}
3320
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003321void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3322 while (!queue.empty()) {
3323 DispatchEntry* dispatchEntry = queue.front();
3324 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003325 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 }
3327}
3328
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003329void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003331 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
3333 delete dispatchEntry;
3334}
3335
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003336int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3337 std::scoped_lock _l(mLock);
3338 sp<Connection> connection = getConnectionLocked(connectionToken);
3339 if (connection == nullptr) {
3340 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3341 connectionToken.get(), events);
3342 return 0; // remove the callback
3343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003345 bool notify;
3346 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3347 if (!(events & ALOOPER_EVENT_INPUT)) {
3348 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3349 "events=0x%x",
3350 connection->getInputChannelName().c_str(), events);
3351 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
3353
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003354 nsecs_t currentTime = now();
3355 bool gotOne = false;
3356 status_t status = OK;
3357 for (;;) {
3358 Result<InputPublisher::ConsumerResponse> result =
3359 connection->inputPublisher.receiveConsumerResponse();
3360 if (!result.ok()) {
3361 status = result.error().code();
3362 break;
3363 }
3364
3365 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3366 const InputPublisher::Finished& finish =
3367 std::get<InputPublisher::Finished>(*result);
3368 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3369 finish.consumeTime);
3370 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003371 if (shouldReportMetricsForConnection(*connection)) {
3372 const InputPublisher::Timeline& timeline =
3373 std::get<InputPublisher::Timeline>(*result);
3374 mLatencyTracker
3375 .trackGraphicsLatency(timeline.inputEventId,
3376 connection->inputChannel->getConnectionToken(),
3377 std::move(timeline.graphicsTimeline));
3378 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003379 }
3380 gotOne = true;
3381 }
3382 if (gotOne) {
3383 runCommandsLockedInterruptible();
3384 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 return 1;
3386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
3388
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003389 notify = status != DEAD_OBJECT || !connection->monitor;
3390 if (notify) {
3391 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3392 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3393 status);
3394 }
3395 } else {
3396 // Monitor channels are never explicitly unregistered.
3397 // We do it automatically when the remote endpoint is closed so don't warn about them.
3398 const bool stillHaveWindowHandle =
3399 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3400 notify = !connection->monitor && stillHaveWindowHandle;
3401 if (notify) {
3402 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3403 connection->getInputChannelName().c_str(), events);
3404 }
3405 }
3406
3407 // Remove the channel.
3408 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3409 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410}
3411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003414 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003415 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417}
3418
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003419void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003420 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003421 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3422 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3423}
3424
3425void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3426 const CancelationOptions& options,
3427 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3428 for (const auto& it : monitorsByDisplay) {
3429 const std::vector<Monitor>& monitors = it.second;
3430 for (const Monitor& monitor : monitors) {
3431 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003432 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003433 }
3434}
3435
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003437 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003438 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003439 if (connection == nullptr) {
3440 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003442
3443 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444}
3445
3446void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3447 const sp<Connection>& connection, const CancelationOptions& options) {
3448 if (connection->status == Connection::STATUS_BROKEN) {
3449 return;
3450 }
3451
3452 nsecs_t currentTime = now();
3453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003454 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003455 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003457 if (cancelationEvents.empty()) {
3458 return;
3459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003461 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3462 "with reality: %s, mode=%d.",
3463 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3464 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003466
3467 InputTarget target;
3468 sp<InputWindowHandle> windowHandle =
3469 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3470 if (windowHandle != nullptr) {
3471 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003472 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003473 target.globalScaleFactor = windowInfo->globalScaleFactor;
3474 }
3475 target.inputChannel = connection->inputChannel;
3476 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3477
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003478 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003479 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003480 switch (cancelationEventEntry->type) {
3481 case EventEntry::Type::KEY: {
3482 logOutboundKeyDetails("cancel - ",
3483 static_cast<const KeyEntry&>(*cancelationEventEntry));
3484 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003486 case EventEntry::Type::MOTION: {
3487 logOutboundMotionDetails("cancel - ",
3488 static_cast<const MotionEntry&>(*cancelationEventEntry));
3489 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003491 case EventEntry::Type::FOCUS:
arthurhungb89ccb02020-12-30 16:19:01 +08003492 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3493 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003494 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003495 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003496 break;
3497 }
3498 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003499 case EventEntry::Type::DEVICE_RESET:
3500 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003501 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003502 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003503 break;
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003507 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3508 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003510
3511 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512}
3513
Svet Ganov5d3bc372020-01-26 23:11:07 -08003514void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3515 const sp<Connection>& connection) {
3516 if (connection->status == Connection::STATUS_BROKEN) {
3517 return;
3518 }
3519
3520 nsecs_t currentTime = now();
3521
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003522 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003523 connection->inputState.synthesizePointerDownEvents(currentTime);
3524
3525 if (downEvents.empty()) {
3526 return;
3527 }
3528
3529#if DEBUG_OUTBOUND_EVENT_DETAILS
3530 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3531 connection->getInputChannelName().c_str(), downEvents.size());
3532#endif
3533
3534 InputTarget target;
3535 sp<InputWindowHandle> windowHandle =
3536 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3537 if (windowHandle != nullptr) {
3538 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003539 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003540 target.globalScaleFactor = windowInfo->globalScaleFactor;
3541 }
3542 target.inputChannel = connection->inputChannel;
3543 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3544
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003545 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003546 switch (downEventEntry->type) {
3547 case EventEntry::Type::MOTION: {
3548 logOutboundMotionDetails("down - ",
3549 static_cast<const MotionEntry&>(*downEventEntry));
3550 break;
3551 }
3552
3553 case EventEntry::Type::KEY:
3554 case EventEntry::Type::FOCUS:
3555 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003556 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003557 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003558 case EventEntry::Type::SENSOR:
3559 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003560 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003561 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003562 break;
3563 }
3564 }
3565
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003566 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3567 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003568 }
3569
3570 startDispatchCycleLocked(currentTime, connection);
3571}
3572
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003573std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3574 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 ALOG_ASSERT(pointerIds.value != 0);
3576
3577 uint32_t splitPointerIndexMap[MAX_POINTERS];
3578 PointerProperties splitPointerProperties[MAX_POINTERS];
3579 PointerCoords splitPointerCoords[MAX_POINTERS];
3580
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003581 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 uint32_t splitPointerCount = 0;
3583
3584 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003585 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003587 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 uint32_t pointerId = uint32_t(pointerProperties.id);
3589 if (pointerIds.hasBit(pointerId)) {
3590 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3591 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3592 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003593 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 splitPointerCount += 1;
3595 }
3596 }
3597
3598 if (splitPointerCount != pointerIds.count()) {
3599 // This is bad. We are missing some of the pointers that we expected to deliver.
3600 // Most likely this indicates that we received an ACTION_MOVE events that has
3601 // different pointer ids than we expected based on the previous ACTION_DOWN
3602 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3603 // in this way.
3604 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 "we expected there to be %d pointers. This probably means we received "
3606 "a broken sequence of pointer ids from the input device.",
3607 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003608 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003611 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3614 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3616 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003617 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 uint32_t pointerId = uint32_t(pointerProperties.id);
3619 if (pointerIds.hasBit(pointerId)) {
3620 if (pointerIds.count() == 1) {
3621 // The first/last pointer went down/up.
3622 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003624 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3625 ? AMOTION_EVENT_ACTION_CANCEL
3626 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 } else {
3628 // A secondary pointer went down/up.
3629 uint32_t splitPointerIndex = 0;
3630 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3631 splitPointerIndex += 1;
3632 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003633 action = maskedAction |
3634 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 }
3636 } else {
3637 // An unrelated pointer changed.
3638 action = AMOTION_EVENT_ACTION_MOVE;
3639 }
3640 }
3641
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003642 int32_t newId = mIdGenerator.nextId();
3643 if (ATRACE_ENABLED()) {
3644 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3645 ") to MotionEvent(id=0x%" PRIx32 ").",
3646 originalMotionEntry.id, newId);
3647 ATRACE_NAME(message.c_str());
3648 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003649 std::unique_ptr<MotionEntry> splitMotionEntry =
3650 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3651 originalMotionEntry.deviceId, originalMotionEntry.source,
3652 originalMotionEntry.displayId,
3653 originalMotionEntry.policyFlags, action,
3654 originalMotionEntry.actionButton,
3655 originalMotionEntry.flags, originalMotionEntry.metaState,
3656 originalMotionEntry.buttonState,
3657 originalMotionEntry.classification,
3658 originalMotionEntry.edgeFlags,
3659 originalMotionEntry.xPrecision,
3660 originalMotionEntry.yPrecision,
3661 originalMotionEntry.xCursorPosition,
3662 originalMotionEntry.yCursorPosition,
3663 originalMotionEntry.downTime, splitPointerCount,
3664 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003666 if (originalMotionEntry.injectionState) {
3667 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 splitMotionEntry->injectionState->refCount += 1;
3669 }
3670
3671 return splitMotionEntry;
3672}
3673
3674void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3675#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003676 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677#endif
3678
3679 bool needWake;
3680 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003681 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003683 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3684 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3685 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 } // release lock
3687
3688 if (needWake) {
3689 mLooper->wake();
3690 }
3691}
3692
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003693/**
3694 * If one of the meta shortcuts is detected, process them here:
3695 * Meta + Backspace -> generate BACK
3696 * Meta + Enter -> generate HOME
3697 * This will potentially overwrite keyCode and metaState.
3698 */
3699void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003700 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003701 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3702 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3703 if (keyCode == AKEYCODE_DEL) {
3704 newKeyCode = AKEYCODE_BACK;
3705 } else if (keyCode == AKEYCODE_ENTER) {
3706 newKeyCode = AKEYCODE_HOME;
3707 }
3708 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003709 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003710 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003711 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003712 keyCode = newKeyCode;
3713 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3714 }
3715 } else if (action == AKEY_EVENT_ACTION_UP) {
3716 // In order to maintain a consistent stream of up and down events, check to see if the key
3717 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3718 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003719 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003720 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003721 auto replacementIt = mReplacedKeys.find(replacement);
3722 if (replacementIt != mReplacedKeys.end()) {
3723 keyCode = replacementIt->second;
3724 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003725 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3726 }
3727 }
3728}
3729
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3731#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3733 "policyFlags=0x%x, action=0x%x, "
3734 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3735 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3736 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3737 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738#endif
3739 if (!validateKeyEvent(args->action)) {
3740 return;
3741 }
3742
3743 uint32_t policyFlags = args->policyFlags;
3744 int32_t flags = args->flags;
3745 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003746 // InputDispatcher tracks and generates key repeats on behalf of
3747 // whatever notifies it, so repeatCount should always be set to 0
3748 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3750 policyFlags |= POLICY_FLAG_VIRTUAL;
3751 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 if (policyFlags & POLICY_FLAG_FUNCTION) {
3754 metaState |= AMETA_FUNCTION_ON;
3755 }
3756
3757 policyFlags |= POLICY_FLAG_TRUSTED;
3758
Michael Wright78f24442014-08-06 15:55:28 -07003759 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003760 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003761
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003763 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003764 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3765 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766
Michael Wright2b3c3302018-03-02 17:19:13 +00003767 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003769 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3770 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 bool needWake;
3775 { // acquire lock
3776 mLock.lock();
3777
3778 if (shouldSendKeyToInputFilterLocked(args)) {
3779 mLock.unlock();
3780
3781 policyFlags |= POLICY_FLAG_FILTERED;
3782 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3783 return; // event was consumed by the filter
3784 }
3785
3786 mLock.lock();
3787 }
3788
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003789 std::unique_ptr<KeyEntry> newEntry =
3790 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3791 args->displayId, policyFlags, args->action, flags,
3792 keyCode, args->scanCode, metaState, repeatCount,
3793 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003795 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 mLock.unlock();
3797 } // release lock
3798
3799 if (needWake) {
3800 mLooper->wake();
3801 }
3802}
3803
3804bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3805 return mInputFilterEnabled;
3806}
3807
3808void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3809#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003810 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3811 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003812 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3813 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003814 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003815 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3816 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3817 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3818 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 for (uint32_t i = 0; i < args->pointerCount; i++) {
3820 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 "x=%f, y=%f, pressure=%f, size=%f, "
3822 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3823 "orientation=%f",
3824 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3825 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3826 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3827 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3828 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3829 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3830 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3831 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3832 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3833 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003836 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3837 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 return;
3839 }
3840
3841 uint32_t policyFlags = args->policyFlags;
3842 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003843
3844 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003845 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003846 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3847 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850
3851 bool needWake;
3852 { // acquire lock
3853 mLock.lock();
3854
3855 if (shouldSendMotionToInputFilterLocked(args)) {
3856 mLock.unlock();
3857
3858 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003859 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003860 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3861 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003862 args->metaState, args->buttonState, args->classification, transform,
3863 args->xPrecision, args->yPrecision, args->xCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07003864 args->yCursorPosition, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
3865 AMOTION_EVENT_INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
chaviw9eaa22c2020-07-01 16:21:27 -07003866 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867
3868 policyFlags |= POLICY_FLAG_FILTERED;
3869 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3870 return; // event was consumed by the filter
3871 }
3872
3873 mLock.lock();
3874 }
3875
3876 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003877 std::unique_ptr<MotionEntry> newEntry =
3878 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3879 args->source, args->displayId, policyFlags,
3880 args->action, args->actionButton, args->flags,
3881 args->metaState, args->buttonState,
3882 args->classification, args->edgeFlags,
3883 args->xPrecision, args->yPrecision,
3884 args->xCursorPosition, args->yCursorPosition,
3885 args->downTime, args->pointerCount,
3886 args->pointerProperties, args->pointerCoords, 0, 0);
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003887 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
3888 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
3889 !mInputFilterEnabled) {
3890 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
3891 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
3892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003894 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 mLock.unlock();
3896 } // release lock
3897
3898 if (needWake) {
3899 mLooper->wake();
3900 }
3901}
3902
Chris Yef59a2f42020-10-16 12:55:26 -07003903void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3904#if DEBUG_INBOUND_EVENT_DETAILS
3905 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3906 " sensorType=%s",
3907 args->id, args->eventTime, args->deviceId, args->source,
3908 NamedEnum::string(args->sensorType).c_str());
3909#endif
3910
3911 bool needWake;
3912 { // acquire lock
3913 mLock.lock();
3914
3915 // Just enqueue a new sensor event.
3916 std::unique_ptr<SensorEntry> newEntry =
3917 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3918 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3919 args->sensorType, args->accuracy,
3920 args->accuracyChanged, args->values);
3921
3922 needWake = enqueueInboundEventLocked(std::move(newEntry));
3923 mLock.unlock();
3924 } // release lock
3925
3926 if (needWake) {
3927 mLooper->wake();
3928 }
3929}
3930
Chris Yefb552902021-02-03 17:18:37 -08003931void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3932#if DEBUG_INBOUND_EVENT_DETAILS
3933 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3934 args->deviceId, args->isOn);
3935#endif
3936 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3937}
3938
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003940 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941}
3942
3943void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3944#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003945 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003946 "switchMask=0x%08x",
3947 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948#endif
3949
3950 uint32_t policyFlags = args->policyFlags;
3951 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003952 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953}
3954
3955void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3956#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3958 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959#endif
3960
3961 bool needWake;
3962 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003963 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003965 std::unique_ptr<DeviceResetEntry> newEntry =
3966 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3967 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 } // release lock
3969
3970 if (needWake) {
3971 mLooper->wake();
3972 }
3973}
3974
Prabir Pradhan7e186182020-11-10 13:56:45 -08003975void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3976#if DEBUG_INBOUND_EVENT_DETAILS
3977 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3978 args->enabled ? "true" : "false");
3979#endif
3980
Prabir Pradhan99987712020-11-10 18:43:05 -08003981 bool needWake;
3982 { // acquire lock
3983 std::scoped_lock _l(mLock);
3984 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3985 args->enabled);
3986 needWake = enqueueInboundEventLocked(std::move(entry));
3987 } // release lock
3988
3989 if (needWake) {
3990 mLooper->wake();
3991 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003992}
3993
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003994InputEventInjectionResult InputDispatcher::injectInputEvent(
3995 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3996 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997#if DEBUG_INBOUND_EVENT_DETAILS
3998 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003999 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4000 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004002 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003
4004 policyFlags |= POLICY_FLAG_INJECTED;
4005 if (hasInjectionPermission(injectorPid, injectorUid)) {
4006 policyFlags |= POLICY_FLAG_TRUSTED;
4007 }
4008
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004009 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004011 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004012 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4013 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004014 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004015 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004018 int32_t flags = incomingKey.getFlags();
4019 int32_t keyCode = incomingKey.getKeyCode();
4020 int32_t metaState = incomingKey.getMetaState();
4021 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004023 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08004024 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004025 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4026 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4027 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004029 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4030 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004031 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004032
4033 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4034 android::base::Timer t;
4035 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4036 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4037 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4038 std::to_string(t.duration().count()).c_str());
4039 }
4040 }
4041
4042 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004043 std::unique_ptr<KeyEntry> injectedEntry =
4044 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
4045 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
4046 incomingKey.getDisplayId(), policyFlags, action,
4047 flags, keyCode, incomingKey.getScanCode(), metaState,
4048 incomingKey.getRepeatCount(),
4049 incomingKey.getDownTime());
4050 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 }
4053
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 case AINPUT_EVENT_TYPE_MOTION: {
4055 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
4056 int32_t action = motionEvent->getAction();
4057 size_t pointerCount = motionEvent->getPointerCount();
4058 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
4059 int32_t actionButton = motionEvent->getActionButton();
4060 int32_t displayId = motionEvent->getDisplayId();
4061 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004062 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 }
4064
4065 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4066 nsecs_t eventTime = motionEvent->getEventTime();
4067 android::base::Timer t;
4068 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4069 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4070 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4071 std::to_string(t.duration().count()).c_str());
4072 }
4073 }
4074
4075 mLock.lock();
4076 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
4077 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004078 std::unique_ptr<MotionEntry> injectedEntry =
4079 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4080 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4081 motionEvent->getDisplayId(), policyFlags, action,
4082 actionButton, motionEvent->getFlags(),
4083 motionEvent->getMetaState(),
4084 motionEvent->getButtonState(),
4085 motionEvent->getClassification(),
4086 motionEvent->getEdgeFlags(),
4087 motionEvent->getXPrecision(),
4088 motionEvent->getYPrecision(),
4089 motionEvent->getRawXCursorPosition(),
4090 motionEvent->getRawYCursorPosition(),
4091 motionEvent->getDownTime(),
4092 uint32_t(pointerCount), pointerProperties,
4093 samplePointerCoords, motionEvent->getXOffset(),
4094 motionEvent->getYOffset());
4095 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004096 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
4097 sampleEventTimes += 1;
4098 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004099 std::unique_ptr<MotionEntry> nextInjectedEntry =
4100 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
4101 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
4102 motionEvent->getDisplayId(), policyFlags,
4103 action, actionButton, motionEvent->getFlags(),
4104 motionEvent->getMetaState(),
4105 motionEvent->getButtonState(),
4106 motionEvent->getClassification(),
4107 motionEvent->getEdgeFlags(),
4108 motionEvent->getXPrecision(),
4109 motionEvent->getYPrecision(),
4110 motionEvent->getRawXCursorPosition(),
4111 motionEvent->getRawYCursorPosition(),
4112 motionEvent->getDownTime(),
4113 uint32_t(pointerCount), pointerProperties,
4114 samplePointerCoords,
4115 motionEvent->getXOffset(),
4116 motionEvent->getYOffset());
4117 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 }
4119 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004123 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004124 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 }
4126
4127 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004128 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 injectionState->injectionIsAsync = true;
4130 }
4131
4132 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004133 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
4135 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004136 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004137 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004138 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 }
4140
4141 mLock.unlock();
4142
4143 if (needWake) {
4144 mLooper->wake();
4145 }
4146
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004147 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004149 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004151 if (syncMode == InputEventInjectionSync::NONE) {
4152 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 } else {
4154 for (;;) {
4155 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 break;
4158 }
4159
4160 nsecs_t remainingTimeout = endTime - now();
4161 if (remainingTimeout <= 0) {
4162#if DEBUG_INJECTION
4163 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004164 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004166 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 break;
4168 }
4169
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004170 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4174 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 while (injectionState->pendingForegroundDispatches != 0) {
4176#if DEBUG_INJECTION
4177 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179#endif
4180 nsecs_t remainingTimeout = endTime - now();
4181 if (remainingTimeout <= 0) {
4182#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4184 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004186 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 break;
4188 }
4189
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004190 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 }
4192 }
4193 }
4194
4195 injectionState->release();
4196 } // release lock
4197
4198#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004199 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201#endif
4202
4203 return injectionResult;
4204}
4205
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004206std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004207 std::array<uint8_t, 32> calculatedHmac;
4208 std::unique_ptr<VerifiedInputEvent> result;
4209 switch (event.getType()) {
4210 case AINPUT_EVENT_TYPE_KEY: {
4211 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4212 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4213 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004214 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004215 break;
4216 }
4217 case AINPUT_EVENT_TYPE_MOTION: {
4218 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4219 VerifiedMotionEvent verifiedMotionEvent =
4220 verifiedMotionEventFromMotionEvent(motionEvent);
4221 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004222 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004223 break;
4224 }
4225 default: {
4226 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4227 return nullptr;
4228 }
4229 }
4230 if (calculatedHmac == INVALID_HMAC) {
4231 return nullptr;
4232 }
4233 if (calculatedHmac != event.getHmac()) {
4234 return nullptr;
4235 }
4236 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004237}
4238
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 return injectorUid == 0 ||
4241 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242}
4243
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004244void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004245 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004246 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 if (injectionState) {
4248#if DEBUG_INJECTION
4249 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 "injectorPid=%d, injectorUid=%d",
4251 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252#endif
4253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004254 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 // Log the outcome since the injector did not wait for the injection result.
4256 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004257 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 ALOGV("Asynchronous input event injection succeeded.");
4259 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004260 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 ALOGW("Asynchronous input event injection failed.");
4262 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004263 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 ALOGW("Asynchronous input event injection permission denied.");
4265 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 ALOGW("Asynchronous input event injection timed out.");
4268 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 case InputEventInjectionResult::PENDING:
4270 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4271 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 }
4273 }
4274
4275 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004276 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278}
4279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004280void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4281 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 if (injectionState) {
4283 injectionState->pendingForegroundDispatches += 1;
4284 }
4285}
4286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4288 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 if (injectionState) {
4290 injectionState->pendingForegroundDispatches -= 1;
4291
4292 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004293 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295 }
4296}
4297
Vishnu Nairad321cd2020-08-20 16:40:21 -07004298const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004299 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004300 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4301 auto it = mWindowHandlesByDisplay.find(displayId);
4302 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004303}
4304
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004306 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004307 if (windowHandleToken == nullptr) {
4308 return nullptr;
4309 }
4310
Arthur Hungb92218b2018-08-14 12:00:21 +08004311 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004312 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004313 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004314 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004315 return windowHandle;
4316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
4318 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004319 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320}
4321
Vishnu Nairad321cd2020-08-20 16:40:21 -07004322sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4323 int displayId) const {
4324 if (windowHandleToken == nullptr) {
4325 return nullptr;
4326 }
4327
4328 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4329 if (windowHandle->getToken() == windowHandleToken) {
4330 return windowHandle;
4331 }
4332 }
4333 return nullptr;
4334}
4335
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004336sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
4337 const sp<InputWindowHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004338 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004339 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004340 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004341 if (handle->getId() == windowHandle->getId() &&
4342 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004343 if (windowHandle->getInfo()->displayId != it.first) {
4344 ALOGE("Found window %s in display %" PRId32
4345 ", but it should belong to display %" PRId32,
4346 windowHandle->getName().c_str(), it.first,
4347 windowHandle->getInfo()->displayId);
4348 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004349 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 }
4352 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004353 return nullptr;
4354}
4355
4356sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4357 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4358 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359}
4360
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004361bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4362 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4363 const bool noInputChannel =
4364 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4365 if (connection != nullptr && noInputChannel) {
4366 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4367 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4368 return false;
4369 }
4370
4371 if (connection == nullptr) {
4372 if (!noInputChannel) {
4373 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4374 }
4375 return false;
4376 }
4377 if (!connection->responsive) {
4378 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4379 return false;
4380 }
4381 return true;
4382}
4383
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004384std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4385 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004386 auto connectionIt = mConnectionsByToken.find(token);
4387 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004388 return nullptr;
4389 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004390 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004391}
4392
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004393void InputDispatcher::updateWindowHandlesForDisplayLocked(
4394 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4395 if (inputWindowHandles.empty()) {
4396 // Remove all handles on a display if there are no windows left.
4397 mWindowHandlesByDisplay.erase(displayId);
4398 return;
4399 }
4400
4401 // Since we compare the pointer of input window handles across window updates, we need
4402 // to make sure the handle object for the same window stays unchanged across updates.
4403 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004404 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004405 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004406 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004407 }
4408
4409 std::vector<sp<InputWindowHandle>> newHandles;
4410 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4411 if (!handle->updateInfo()) {
4412 // handle no longer valid
4413 continue;
4414 }
4415
4416 const InputWindowInfo* info = handle->getInfo();
4417 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4418 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4419 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004420 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4421 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4422 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004423 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004424 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004425 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004426 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004427 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004428 }
4429
4430 if (info->displayId != displayId) {
4431 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4432 handle->getName().c_str(), displayId, info->displayId);
4433 continue;
4434 }
4435
Robert Carredd13602020-04-13 17:24:34 -07004436 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4437 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004438 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004439 oldHandle->updateFrom(handle);
4440 newHandles.push_back(oldHandle);
4441 } else {
4442 newHandles.push_back(handle);
4443 }
4444 }
4445
4446 // Insert or replace
4447 mWindowHandlesByDisplay[displayId] = newHandles;
4448}
4449
Arthur Hung72d8dc32020-03-28 00:48:39 +00004450void InputDispatcher::setInputWindows(
4451 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4452 { // acquire lock
4453 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004454 for (const auto& [displayId, handles] : handlesPerDisplay) {
4455 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004456 }
4457 }
4458 // Wake up poll loop since it may need to make new input dispatching choices.
4459 mLooper->wake();
4460}
4461
Arthur Hungb92218b2018-08-14 12:00:21 +08004462/**
4463 * Called from InputManagerService, update window handle list by displayId that can receive input.
4464 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4465 * If set an empty list, remove all handles from the specific display.
4466 * For focused handle, check if need to change and send a cancel event to previous one.
4467 * For removed handle, check if need to send a cancel event if already in touch.
4468 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004469void InputDispatcher::setInputWindowsLocked(
4470 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004471 if (DEBUG_FOCUS) {
4472 std::string windowList;
4473 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4474 windowList += iwh->getName() + " ";
4475 }
4476 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004479 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4480 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4481 const bool noInputWindow =
4482 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4483 if (noInputWindow && window->getToken() != nullptr) {
4484 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4485 window->getName().c_str());
4486 window->releaseChannel();
4487 }
4488 }
4489
Arthur Hung72d8dc32020-03-28 00:48:39 +00004490 // Copy old handles for release if they are no longer present.
4491 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492
Arthur Hung72d8dc32020-03-28 00:48:39 +00004493 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004494
Vishnu Nair958da932020-08-21 17:12:37 -07004495 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4496 if (mLastHoverWindowHandle &&
4497 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4498 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004499 mLastHoverWindowHandle = nullptr;
4500 }
4501
Vishnu Nairc519ff72021-01-21 08:23:08 -08004502 std::optional<FocusResolver::FocusChanges> changes =
4503 mFocusResolver.setInputWindows(displayId, windowHandles);
4504 if (changes) {
4505 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004508 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4509 mTouchStatesByDisplay.find(displayId);
4510 if (stateIt != mTouchStatesByDisplay.end()) {
4511 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004512 for (size_t i = 0; i < state.windows.size();) {
4513 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004514 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004515 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004516 ALOGD("Touched window was removed: %s in display %" PRId32,
4517 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004518 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004519 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004520 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4521 if (touchedInputChannel != nullptr) {
4522 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4523 "touched window was removed");
4524 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004526 state.windows.erase(state.windows.begin() + i);
4527 } else {
4528 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 }
4530 }
arthurhungb89ccb02020-12-30 16:19:01 +08004531
arthurhung6d4bed92021-03-17 11:59:33 +08004532 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004533 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004534 if (mDragState &&
4535 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004536 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004537 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004538 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004539 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004540
Arthur Hung72d8dc32020-03-28 00:48:39 +00004541 // Release information for windows that are no longer present.
4542 // This ensures that unused input channels are released promptly.
4543 // Otherwise, they might stick around until the window handle is destroyed
4544 // which might not happen until the next GC.
4545 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004546 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004547 if (DEBUG_FOCUS) {
4548 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004549 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004550 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004551 // To avoid making too many calls into the compat framework, only
4552 // check for window flags when windows are going away.
4553 // TODO(b/157929241) : delete this. This is only needed temporarily
4554 // in order to gather some data about the flag usage
4555 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4556 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4557 oldWindowHandle->getName().c_str());
4558 if (mCompatService != nullptr) {
4559 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4560 oldWindowHandle->getInfo()->ownerUid);
4561 }
4562 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004563 }
chaviw291d88a2019-02-14 10:33:58 -08004564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565}
4566
4567void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004568 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004569 if (DEBUG_FOCUS) {
4570 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4571 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4572 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004573 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004574 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Chris Yea209fde2020-07-22 13:54:51 -07004576 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004577 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004578
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004579 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4580 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581 }
4582
Chris Yea209fde2020-07-22 13:54:51 -07004583 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004584 if (inputApplicationHandle != nullptr) {
4585 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4586 } else {
4587 mFocusedApplicationHandlesByDisplay.erase(displayId);
4588 }
4589
4590 // No matter what the old focused application was, stop waiting on it because it is
4591 // no longer focused.
4592 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 } // release lock
4594
4595 // Wake up poll loop since it may need to make new input dispatching choices.
4596 mLooper->wake();
4597}
4598
Tiger Huang721e26f2018-07-24 22:26:19 +08004599/**
4600 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4601 * the display not specified.
4602 *
4603 * We track any unreleased events for each window. If a window loses the ability to receive the
4604 * released event, we will send a cancel event to it. So when the focused display is changed, we
4605 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4606 * display. The display-specified events won't be affected.
4607 */
4608void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004609 if (DEBUG_FOCUS) {
4610 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4611 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004612 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004613 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004614
4615 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004616 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004617 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004618 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004619 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004620 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004621 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 CancelationOptions
4623 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4624 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004625 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004626 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4627 }
4628 }
4629 mFocusedDisplayId = displayId;
4630
Chris Ye3c2d6f52020-08-09 10:39:48 -07004631 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004632 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004633 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004634
Vishnu Nairad321cd2020-08-20 16:40:21 -07004635 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004636 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004637 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004638 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004639 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004640 }
4641 }
4642 }
4643
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004644 if (DEBUG_FOCUS) {
4645 logDispatchStateLocked();
4646 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004647 } // release lock
4648
4649 // Wake up poll loop since it may need to make new input dispatching choices.
4650 mLooper->wake();
4651}
4652
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004654 if (DEBUG_FOCUS) {
4655 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657
4658 bool changed;
4659 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004660 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661
4662 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4663 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 }
4666
4667 if (mDispatchEnabled && !enabled) {
4668 resetAndDropEverythingLocked("dispatcher is being disabled");
4669 }
4670
4671 mDispatchEnabled = enabled;
4672 mDispatchFrozen = frozen;
4673 changed = true;
4674 } else {
4675 changed = false;
4676 }
4677
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004678 if (DEBUG_FOCUS) {
4679 logDispatchStateLocked();
4680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 } // release lock
4682
4683 if (changed) {
4684 // Wake up poll loop since it may need to make new input dispatching choices.
4685 mLooper->wake();
4686 }
4687}
4688
4689void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004690 if (DEBUG_FOCUS) {
4691 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693
4694 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004695 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
4697 if (mInputFilterEnabled == enabled) {
4698 return;
4699 }
4700
4701 mInputFilterEnabled = enabled;
4702 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4703 } // release lock
4704
4705 // Wake up poll loop since there might be work to do to drop everything.
4706 mLooper->wake();
4707}
4708
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004709void InputDispatcher::setInTouchMode(bool inTouchMode) {
4710 std::scoped_lock lock(mLock);
4711 mInTouchMode = inTouchMode;
4712}
4713
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004714void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4715 if (opacity < 0 || opacity > 1) {
4716 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4717 return;
4718 }
4719
4720 std::scoped_lock lock(mLock);
4721 mMaximumObscuringOpacityForTouch = opacity;
4722}
4723
4724void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4725 std::scoped_lock lock(mLock);
4726 mBlockUntrustedTouchesMode = mode;
4727}
4728
arthurhungb89ccb02020-12-30 16:19:01 +08004729bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4730 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004731 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004732 if (DEBUG_FOCUS) {
4733 ALOGD("Trivial transfer to same window.");
4734 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004735 return true;
4736 }
4737
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004739 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740
chaviwfbe5d9c2018-12-26 12:23:37 -08004741 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4742 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004743 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004744 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 return false;
4746 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004747 if (DEBUG_FOCUS) {
4748 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4749 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004752 if (DEBUG_FOCUS) {
4753 ALOGD("Cannot transfer focus because windows are on different displays.");
4754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 return false;
4756 }
4757
4758 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004759 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4760 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004761 for (size_t i = 0; i < state.windows.size(); i++) {
4762 const TouchedWindow& touchedWindow = state.windows[i];
4763 if (touchedWindow.windowHandle == fromWindowHandle) {
4764 int32_t oldTargetFlags = touchedWindow.targetFlags;
4765 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004767 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 int32_t newTargetFlags = oldTargetFlags &
4770 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4771 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004772 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773
arthurhungb89ccb02020-12-30 16:19:01 +08004774 // Store the dragging window.
4775 if (isDragDrop) {
arthurhung6d4bed92021-03-17 11:59:33 +08004776 mDragState = std::make_unique<DragState>(toWindowHandle);
arthurhungb89ccb02020-12-30 16:19:01 +08004777 }
4778
Jeff Brownf086ddb2014-02-11 14:28:48 -08004779 found = true;
4780 goto Found;
4781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 }
4783 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004786 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004787 if (DEBUG_FOCUS) {
4788 ALOGD("Focus transfer failed because from window did not have focus.");
4789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 return false;
4791 }
4792
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004793 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4794 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004795 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004796 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 CancelationOptions
4798 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4799 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004801 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 }
4803
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004804 if (DEBUG_FOCUS) {
4805 logDispatchStateLocked();
4806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 } // release lock
4808
4809 // Wake up poll loop since it may need to make new input dispatching choices.
4810 mLooper->wake();
4811 return true;
4812}
4813
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00004814// Binder call
4815bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4816 sp<IBinder> fromToken;
4817 { // acquire lock
4818 std::scoped_lock _l(mLock);
4819
4820 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(destChannelToken);
4821 if (toWindowHandle == nullptr) {
4822 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4823 return false;
4824 }
4825
4826 const int32_t displayId = toWindowHandle->getInfo()->displayId;
4827
4828 auto touchStateIt = mTouchStatesByDisplay.find(displayId);
4829 if (touchStateIt == mTouchStatesByDisplay.end()) {
4830 ALOGD("Could not transfer touch because the display %" PRId32 " is not being touched",
4831 displayId);
4832 return false;
4833 }
4834
4835 TouchState& state = touchStateIt->second;
4836 if (state.windows.size() != 1) {
4837 ALOGW("Cannot transfer touch state because there are %zu windows being touched",
4838 state.windows.size());
4839 return false;
4840 }
4841 const TouchedWindow& touchedWindow = state.windows[0];
4842 fromToken = touchedWindow.windowHandle->getToken();
4843 } // release lock
4844
4845 return transferTouchFocus(fromToken, destChannelToken);
4846}
4847
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004849 if (DEBUG_FOCUS) {
4850 ALOGD("Resetting and dropping all events (%s).", reason);
4851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852
4853 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4854 synthesizeCancelationEventsForAllConnectionsLocked(options);
4855
4856 resetKeyRepeatLocked();
4857 releasePendingEventLocked();
4858 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004862 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004864 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865}
4866
4867void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004868 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 dumpDispatchStateLocked(dump);
4870
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004871 std::istringstream stream(dump);
4872 std::string line;
4873
4874 while (std::getline(stream, line, '\n')) {
4875 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877}
4878
Prabir Pradhan99987712020-11-10 18:43:05 -08004879std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4880 std::string dump;
4881
4882 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4883 toString(mFocusedWindowRequestedPointerCapture));
4884
4885 std::string windowName = "None";
4886 if (mWindowTokenWithPointerCapture) {
4887 const sp<InputWindowHandle> captureWindowHandle =
4888 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4889 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4890 : "token has capture without window";
4891 }
4892 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4893
4894 return dump;
4895}
4896
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004897void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004898 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4899 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4900 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004901 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902
Tiger Huang721e26f2018-07-24 22:26:19 +08004903 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4904 dump += StringPrintf(INDENT "FocusedApplications:\n");
4905 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4906 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004907 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004908 const std::chrono::duration timeout =
4909 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004910 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004911 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004912 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004915 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004917
Vishnu Nairc519ff72021-01-21 08:23:08 -08004918 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004919 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004921 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004922 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004923 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4924 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004925 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004926 state.displayId, toString(state.down), toString(state.split),
4927 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004928 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004929 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004930 for (size_t i = 0; i < state.windows.size(); i++) {
4931 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 dump += StringPrintf(INDENT4
4933 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4934 i, touchedWindow.windowHandle->getName().c_str(),
4935 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004936 }
4937 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004938 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004939 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004940 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004941 dump += INDENT3 "Portal windows:\n";
4942 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004943 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004944 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4945 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004946 }
4947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 }
4949 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004950 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
4952
arthurhung6d4bed92021-03-17 11:59:33 +08004953 if (mDragState) {
4954 dump += StringPrintf(INDENT "DragState:\n");
4955 mDragState->dump(dump, INDENT2);
4956 }
4957
Arthur Hungb92218b2018-08-14 12:00:21 +08004958 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004959 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004960 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004961 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004962 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004963 dump += INDENT2 "Windows:\n";
4964 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004965 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004966 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004968 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004969 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004970 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004971 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004972 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004973 "applicationInfo.name=%s, "
4974 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004975 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004976 i, windowInfo->name.c_str(), windowInfo->id,
4977 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004979 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004980 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004981 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004982 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004983 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004984 windowInfo->frameLeft, windowInfo->frameTop,
4985 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004986 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004987 windowInfo->applicationInfo.name.c_str(),
4988 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004989 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004990 dump += StringPrintf(", inputFeatures=%s",
4991 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004992 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004993 "ms, trustedOverlay=%s, hasToken=%s, "
4994 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004996 millis(windowInfo->dispatchingTimeout),
4997 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004998 toString(windowInfo->token != nullptr),
4999 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005000 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005001 }
5002 } else {
5003 dump += INDENT2 "Windows: <none>\n";
5004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 }
5006 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005007 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 }
5009
Michael Wright3dd60e22019-03-27 22:06:44 +00005010 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005011 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005012 const std::vector<Monitor>& monitors = it.second;
5013 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5014 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005015 }
5016 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005017 const std::vector<Monitor>& monitors = it.second;
5018 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5019 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00005022 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 }
5024
5025 nsecs_t currentTime = now();
5026
5027 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005028 if (!mRecentQueue.empty()) {
5029 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005030 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005031 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005032 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005033 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034 }
5035 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005036 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 }
5038
5039 // Dump event currently being dispatched.
5040 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005041 dump += INDENT "PendingEvent:\n";
5042 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005043 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005044 dump += StringPrintf(", age=%" PRId64 "ms\n",
5045 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005047 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 }
5049
5050 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005051 if (!mInboundQueue.empty()) {
5052 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005053 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005054 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005055 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005056 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 }
5058 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005059 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 }
5061
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005062 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005063 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005064 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5065 const KeyReplacement& replacement = pair.first;
5066 int32_t newKeyCode = pair.second;
5067 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005068 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005069 }
5070 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005071 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005072 }
5073
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005074 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005075 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005076 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005077 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005078 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005079 connection->inputChannel->getFd().get(),
5080 connection->getInputChannelName().c_str(),
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005081 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005082 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005084 if (!connection->outboundQueue.empty()) {
5085 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5086 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005087 dump += dumpQueue(connection->outboundQueue, currentTime);
5088
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005090 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
5092
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005093 if (!connection->waitQueue.empty()) {
5094 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5095 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005096 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005098 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 }
5100 }
5101 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005102 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 }
5104
5105 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005106 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5107 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005109 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005112 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005113 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5114 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5115 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005116 dump += mLatencyTracker.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117}
5118
Michael Wright3dd60e22019-03-27 22:06:44 +00005119void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5120 const size_t numMonitors = monitors.size();
5121 for (size_t i = 0; i < numMonitors; i++) {
5122 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005123 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005124 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5125 dump += "\n";
5126 }
5127}
5128
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005129class LooperEventCallback : public LooperCallback {
5130public:
5131 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5132 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5133
5134private:
5135 std::function<int(int events)> mCallback;
5136};
5137
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005138Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Garfield Tan15601662020-09-22 15:32:38 -07005139#if DEBUG_CHANNEL_CREATION
5140 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141#endif
5142
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005143 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005144 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005145 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005146
5147 if (result) {
5148 return base::Error(result) << "Failed to open input channel pair with name " << name;
5149 }
5150
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005152 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005153 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005154 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005155 sp<Connection> connection =
5156 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005158 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5159 ALOGE("Created a new connection, but the token %p is already known", token.get());
5160 }
5161 mConnectionsByToken.emplace(token, connection);
5162
5163 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5164 this, std::placeholders::_1, token);
5165
5166 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 } // release lock
5168
5169 // Wake the looper because some connections have changed.
5170 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005171 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172}
5173
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005174Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5175 bool isGestureMonitor,
5176 const std::string& name,
5177 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005178 std::shared_ptr<InputChannel> serverChannel;
5179 std::unique_ptr<InputChannel> clientChannel;
5180 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5181 if (result) {
5182 return base::Error(result) << "Failed to open input channel pair with name " << name;
5183 }
5184
Michael Wright3dd60e22019-03-27 22:06:44 +00005185 { // acquire lock
5186 std::scoped_lock _l(mLock);
5187
5188 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005189 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5190 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005191 }
5192
Garfield Tan15601662020-09-22 15:32:38 -07005193 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005194 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005195 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005196
5197 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5198 ALOGE("Created a new connection, but the token %p is already known", token.get());
5199 }
5200 mConnectionsByToken.emplace(token, connection);
5201 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5202 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005204 auto& monitorsByDisplay =
5205 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005206 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005207
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005208 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005209 }
Garfield Tan15601662020-09-22 15:32:38 -07005210
Michael Wright3dd60e22019-03-27 22:06:44 +00005211 // Wake the looper because some connections have changed.
5212 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005213 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005214}
5215
Garfield Tan15601662020-09-22 15:32:38 -07005216status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005218 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219
Garfield Tan15601662020-09-22 15:32:38 -07005220 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 if (status) {
5222 return status;
5223 }
5224 } // release lock
5225
5226 // Wake the poll loop because removing the connection may have changed the current
5227 // synchronization state.
5228 mLooper->wake();
5229 return OK;
5230}
5231
Garfield Tan15601662020-09-22 15:32:38 -07005232status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5233 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005234 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005235 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005236 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 return BAD_VALUE;
5238 }
5239
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005240 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005241
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005243 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 }
5245
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005246 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247
5248 nsecs_t currentTime = now();
5249 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5250
5251 connection->status = Connection::STATUS_ZOMBIE;
5252 return OK;
5253}
5254
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005255void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5256 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5257 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005258}
5259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005260void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005261 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005262 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005263 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005264 std::vector<Monitor>& monitors = it->second;
5265 const size_t numMonitors = monitors.size();
5266 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005267 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Siarhei Vishniakou59a9f292021-04-22 18:43:28 +00005268 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5269 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005270 monitors.erase(monitors.begin() + i);
5271 break;
5272 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005273 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005274 if (monitors.empty()) {
5275 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005276 } else {
5277 ++it;
5278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 }
5280}
5281
Michael Wright3dd60e22019-03-27 22:06:44 +00005282status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5283 { // acquire lock
5284 std::scoped_lock _l(mLock);
5285 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5286
5287 if (!foundDisplayId) {
5288 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5289 return BAD_VALUE;
5290 }
5291 int32_t displayId = foundDisplayId.value();
5292
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005293 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5294 mTouchStatesByDisplay.find(displayId);
5295 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005296 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5297 return BAD_VALUE;
5298 }
5299
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005300 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005301 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005302 std::optional<int32_t> foundDeviceId;
5303 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005304 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005305 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005306 foundDeviceId = state.deviceId;
5307 }
5308 }
5309 if (!foundDeviceId || !state.down) {
5310 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005311 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005312 return BAD_VALUE;
5313 }
5314 int32_t deviceId = foundDeviceId.value();
5315
5316 // Send cancel events to all the input channels we're stealing from.
5317 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005318 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005319 options.deviceId = deviceId;
5320 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005321 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005322 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005323 std::shared_ptr<InputChannel> channel =
5324 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005325 if (channel != nullptr) {
5326 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005327 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005328 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005329 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005330 canceledWindows += "]";
5331 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5332 canceledWindows.c_str());
5333
Michael Wright3dd60e22019-03-27 22:06:44 +00005334 // Then clear the current touch state so we stop dispatching to them as well.
5335 state.filterNonMonitors();
5336 }
5337 return OK;
5338}
5339
Prabir Pradhan99987712020-11-10 18:43:05 -08005340void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5341 { // acquire lock
5342 std::scoped_lock _l(mLock);
5343 if (DEBUG_FOCUS) {
5344 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5345 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5346 windowHandle != nullptr ? windowHandle->getName().c_str()
5347 : "token without window");
5348 }
5349
Vishnu Nairc519ff72021-01-21 08:23:08 -08005350 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005351 if (focusedToken != windowToken) {
5352 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5353 enabled ? "enable" : "disable");
5354 return;
5355 }
5356
5357 if (enabled == mFocusedWindowRequestedPointerCapture) {
5358 ALOGW("Ignoring request to %s Pointer Capture: "
5359 "window has %s requested pointer capture.",
5360 enabled ? "enable" : "disable", enabled ? "already" : "not");
5361 return;
5362 }
5363
5364 mFocusedWindowRequestedPointerCapture = enabled;
5365 setPointerCaptureLocked(enabled);
5366 } // release lock
5367
5368 // Wake the thread to process command entries.
5369 mLooper->wake();
5370}
5371
Michael Wright3dd60e22019-03-27 22:06:44 +00005372std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5373 const sp<IBinder>& token) {
5374 for (const auto& it : mGestureMonitorsByDisplay) {
5375 const std::vector<Monitor>& monitors = it.second;
5376 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005377 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005378 return it.first;
5379 }
5380 }
5381 }
5382 return std::nullopt;
5383}
5384
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005385std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5386 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5387 if (gesturePid.has_value()) {
5388 return gesturePid;
5389 }
5390 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5391}
5392
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005393sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005394 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005395 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005396 }
5397
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005398 for (const auto& [token, connection] : mConnectionsByToken) {
5399 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005400 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 }
5402 }
Robert Carr4e670e52018-08-15 13:26:12 -07005403
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005404 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405}
5406
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005407std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5408 sp<Connection> connection = getConnectionLocked(connectionToken);
5409 if (connection == nullptr) {
5410 return "<nullptr>";
5411 }
5412 return connection->getInputChannelName();
5413}
5414
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005415void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005416 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005417 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005418}
5419
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005420void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5421 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005422 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005423 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5424 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 commandEntry->connection = connection;
5426 commandEntry->eventTime = currentTime;
5427 commandEntry->seq = seq;
5428 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005429 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005430 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431}
5432
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005433void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5434 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005436 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005438 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5439 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005441 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442}
5443
Vishnu Nairad321cd2020-08-20 16:40:21 -07005444void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5445 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005446 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5447 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005448 commandEntry->oldToken = oldToken;
5449 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005450 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005451}
5452
arthurhungf452d0b2021-01-06 00:19:52 +08005453void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5454 std::unique_ptr<CommandEntry> commandEntry =
5455 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5456 commandEntry->newToken = token;
5457 commandEntry->x = x;
5458 commandEntry->y = y;
5459 postCommandLocked(std::move(commandEntry));
5460}
5461
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005462void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5463 if (connection == nullptr) {
5464 LOG_ALWAYS_FATAL("Caller must check for nullness");
5465 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005466 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5467 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005468 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005469 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005470 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005471 return;
5472 }
5473 /**
5474 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5475 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5476 * has changed. This could cause newer entries to time out before the already dispatched
5477 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5478 * processes the events linearly. So providing information about the oldest entry seems to be
5479 * most useful.
5480 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005481 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005482 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5483 std::string reason =
5484 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005485 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005486 ns2ms(currentWait),
5487 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005488 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005489 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005490
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005491 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5492
5493 // Stop waking up for events on this connection, it is already unresponsive
5494 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005495}
5496
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005497void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5498 std::string reason =
5499 StringPrintf("%s does not have a focused window", application->getName().c_str());
5500 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005501
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005502 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5503 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5504 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005505 postCommandLocked(std::move(commandEntry));
5506}
5507
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005508void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5509 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5510 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5511 commandEntry->obscuringPackage = obscuringPackage;
5512 postCommandLocked(std::move(commandEntry));
5513}
5514
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005515void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5516 const std::string& reason) {
5517 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5518 updateLastAnrStateLocked(windowLabel, reason);
5519}
5520
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005521void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5522 const std::string& reason) {
5523 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005524 updateLastAnrStateLocked(windowLabel, reason);
5525}
5526
5527void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5528 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005530 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 struct tm tm;
5532 localtime_r(&t, &tm);
5533 char timestr[64];
5534 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005535 mLastAnrState.clear();
5536 mLastAnrState += INDENT "ANR:\n";
5537 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005538 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5539 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005540 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541}
5542
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005543void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 mLock.unlock();
5545
5546 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5547
5548 mLock.lock();
5549}
5550
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005551void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 sp<Connection> connection = commandEntry->connection;
5553
5554 if (connection->status != Connection::STATUS_ZOMBIE) {
5555 mLock.unlock();
5556
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005557 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558
5559 mLock.lock();
5560 }
5561}
5562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005563void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005564 sp<IBinder> oldToken = commandEntry->oldToken;
5565 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005566 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005567 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005568 mLock.lock();
5569}
5570
arthurhungf452d0b2021-01-06 00:19:52 +08005571void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5572 sp<IBinder> newToken = commandEntry->newToken;
5573 mLock.unlock();
5574 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5575 mLock.lock();
5576}
5577
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005578void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005580
5581 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5582
5583 mLock.lock();
5584}
5585
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005586void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005587 mLock.unlock();
5588
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005589 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590
5591 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005592}
5593
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005594void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005595 mLock.unlock();
5596
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005597 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5598
5599 mLock.lock();
5600}
5601
5602void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5603 mLock.unlock();
5604
5605 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5606
5607 mLock.lock();
5608}
5609
5610void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5611 mLock.unlock();
5612
5613 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005614
5615 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005616}
5617
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005618void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5619 mLock.unlock();
5620
5621 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5622
5623 mLock.lock();
5624}
5625
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5627 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005628 KeyEntry& entry = *(commandEntry->keyEntry);
5629 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630
5631 mLock.unlock();
5632
Michael Wright2b3c3302018-03-02 17:19:13 +00005633 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005634 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005635 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005636 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5637 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005638 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640
5641 mLock.lock();
5642
5643 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005644 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005646 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005648 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5649 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651}
5652
chaviwfd6d3512019-03-25 13:23:49 -07005653void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5654 mLock.unlock();
5655 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5656 mLock.lock();
5657}
5658
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005659/**
5660 * Connection is responsive if it has no events in the waitQueue that are older than the
5661 * current time.
5662 */
5663static bool isConnectionResponsive(const Connection& connection) {
5664 const nsecs_t currentTime = now();
5665 for (const DispatchEntry* entry : connection.waitQueue) {
5666 if (entry->timeoutTime < currentTime) {
5667 return false;
5668 }
5669 }
5670 return true;
5671}
5672
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005673void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005675 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005677 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678
5679 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005680 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005681 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005682 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005684 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005685 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005686 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005687 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5688 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005689 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005690 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5691 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5692 connection->inputChannel->getConnectionToken(),
5693 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5694 finishTime);
5695 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005696
5697 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005698 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005699 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005700 restartEvent =
5701 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005702 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005703 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005704 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5705 handled);
5706 } else {
5707 restartEvent = false;
5708 }
5709
5710 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005711 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005712 // contents of the wait queue to have been drained, so we need to double-check
5713 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005714 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5715 if (dispatchEntryIt != connection->waitQueue.end()) {
5716 dispatchEntry = *dispatchEntryIt;
5717 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005718 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5719 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005720 if (!connection->responsive) {
5721 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005722 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005723 // The connection was unresponsive, and now it's responsive.
5724 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005725 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005726 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005727 traceWaitQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005728 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005729 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00005730 traceOutboundQueueLength(*connection);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005731 } else {
5732 releaseDispatchEntry(dispatchEntry);
5733 }
5734 }
5735
5736 // Start the next dispatch cycle for this connection.
5737 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738}
5739
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005740void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5741 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5742 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5743 monitorUnresponsiveCommand->pid = pid;
5744 monitorUnresponsiveCommand->reason = std::move(reason);
5745 postCommandLocked(std::move(monitorUnresponsiveCommand));
5746}
5747
5748void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5749 std::string reason) {
5750 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5751 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5752 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5753 windowUnresponsiveCommand->reason = std::move(reason);
5754 postCommandLocked(std::move(windowUnresponsiveCommand));
5755}
5756
5757void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5758 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5759 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5760 monitorResponsiveCommand->pid = pid;
5761 postCommandLocked(std::move(monitorResponsiveCommand));
5762}
5763
5764void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5765 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5766 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5767 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5768 postCommandLocked(std::move(windowResponsiveCommand));
5769}
5770
5771/**
5772 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5773 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5774 * command entry to the command queue.
5775 */
5776void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5777 std::string reason) {
5778 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5779 if (connection.monitor) {
5780 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5781 reason.c_str());
5782 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5783 if (!pid.has_value()) {
5784 ALOGE("Could not find unresponsive monitor for connection %s",
5785 connection.inputChannel->getName().c_str());
5786 return;
5787 }
5788 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5789 return;
5790 }
5791 // If not a monitor, must be a window
5792 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5793 reason.c_str());
5794 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5795}
5796
5797/**
5798 * Tell the policy that a connection has become responsive so that it can stop ANR.
5799 */
5800void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5801 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5802 if (connection.monitor) {
5803 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5804 if (!pid.has_value()) {
5805 ALOGE("Could not find responsive monitor for connection %s",
5806 connection.inputChannel->getName().c_str());
5807 return;
5808 }
5809 sendMonitorResponsiveCommandLocked(pid.value());
5810 return;
5811 }
5812 // If not a monitor, must be a window
5813 sendWindowResponsiveCommandLocked(connectionToken);
5814}
5815
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005817 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005818 KeyEntry& keyEntry, bool handled) {
5819 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005820 if (!handled) {
5821 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005822 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005823 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005824 return false;
5825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005827 // Get the fallback key state.
5828 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005829 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005830 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005831 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005832 connection->inputState.removeFallbackKey(originalKeyCode);
5833 }
5834
5835 if (handled || !dispatchEntry->hasForegroundTarget()) {
5836 // If the application handles the original key for which we previously
5837 // generated a fallback or if the window is not a foreground window,
5838 // then cancel the associated fallback key, if any.
5839 if (fallbackKeyCode != -1) {
5840 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005842 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005843 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005844 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005846 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005847 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848
5849 mLock.unlock();
5850
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005851 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005852 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853
5854 mLock.lock();
5855
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005856 // Cancel the fallback key.
5857 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005859 "application handled the original non-fallback key "
5860 "or is no longer a foreground target, "
5861 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005862 options.keyCode = fallbackKeyCode;
5863 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005865 connection->inputState.removeFallbackKey(originalKeyCode);
5866 }
5867 } else {
5868 // If the application did not handle a non-fallback key, first check
5869 // that we are in a good state to perform unhandled key event processing
5870 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005871 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005872 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005874 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005875 "since this is not an initial down. "
5876 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005877 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005878#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005879 return false;
5880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005882 // Dispatch the unhandled key to the policy.
5883#if DEBUG_OUTBOUND_EVENT_DETAILS
5884 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005885 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005886 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005887#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005888 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005889
5890 mLock.unlock();
5891
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005892 bool fallback =
5893 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005894 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005895
5896 mLock.lock();
5897
5898 if (connection->status != Connection::STATUS_NORMAL) {
5899 connection->inputState.removeFallbackKey(originalKeyCode);
5900 return false;
5901 }
5902
5903 // Latch the fallback keycode for this key on an initial down.
5904 // The fallback keycode cannot change at any other point in the lifecycle.
5905 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907 fallbackKeyCode = event.getKeyCode();
5908 } else {
5909 fallbackKeyCode = AKEYCODE_UNKNOWN;
5910 }
5911 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5912 }
5913
5914 ALOG_ASSERT(fallbackKeyCode != -1);
5915
5916 // Cancel the fallback key if the policy decides not to send it anymore.
5917 // We will continue to dispatch the key to the policy but we will no
5918 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005919 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5920 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005921#if DEBUG_OUTBOUND_EVENT_DETAILS
5922 if (fallback) {
5923 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005924 "as a fallback for %d, but on the DOWN it had requested "
5925 "to send %d instead. Fallback canceled.",
5926 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005927 } else {
5928 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005929 "but on the DOWN it had requested to send %d. "
5930 "Fallback canceled.",
5931 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005932 }
5933#endif
5934
5935 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5936 "canceling fallback, policy no longer desires it");
5937 options.keyCode = fallbackKeyCode;
5938 synthesizeCancelationEventsForConnectionLocked(connection, options);
5939
5940 fallback = false;
5941 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005942 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005943 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005944 }
5945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946
5947#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005948 {
5949 std::string msg;
5950 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5951 connection->inputState.getFallbackKeys();
5952 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005953 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005955 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005956 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005957 }
5958#endif
5959
5960 if (fallback) {
5961 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005962 keyEntry.eventTime = event.getEventTime();
5963 keyEntry.deviceId = event.getDeviceId();
5964 keyEntry.source = event.getSource();
5965 keyEntry.displayId = event.getDisplayId();
5966 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5967 keyEntry.keyCode = fallbackKeyCode;
5968 keyEntry.scanCode = event.getScanCode();
5969 keyEntry.metaState = event.getMetaState();
5970 keyEntry.repeatCount = event.getRepeatCount();
5971 keyEntry.downTime = event.getDownTime();
5972 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973
5974#if DEBUG_OUTBOUND_EVENT_DETAILS
5975 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005976 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005977 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005978#endif
5979 return true; // restart the event
5980 } else {
5981#if DEBUG_OUTBOUND_EVENT_DETAILS
5982 ALOGD("Unhandled key event: No fallback key.");
5983#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005984
5985 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005986 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987 }
5988 }
5989 return false;
5990}
5991
5992bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005993 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005994 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995 return false;
5996}
5997
5998void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5999 mLock.unlock();
6000
Sean Stoutb4e0a592021-02-23 07:34:53 -08006001 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6002 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003
6004 mLock.lock();
6005}
6006
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007void InputDispatcher::traceInboundQueueLengthLocked() {
6008 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006009 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010 }
6011}
6012
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006013void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006014 if (ATRACE_ENABLED()) {
6015 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006016 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6017 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 }
6019}
6020
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006021void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 if (ATRACE_ENABLED()) {
6023 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006024 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6025 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 }
6027}
6028
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006029void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006030 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006032 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 dumpDispatchStateLocked(dump);
6034
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006035 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006036 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006037 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038 }
6039}
6040
6041void InputDispatcher::monitor() {
6042 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006043 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006045 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046}
6047
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006048/**
6049 * Wake up the dispatcher and wait until it processes all events and commands.
6050 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6051 * this method can be safely called from any thread, as long as you've ensured that
6052 * the work you are interested in completing has already been queued.
6053 */
6054bool InputDispatcher::waitForIdle() {
6055 /**
6056 * Timeout should represent the longest possible time that a device might spend processing
6057 * events and commands.
6058 */
6059 constexpr std::chrono::duration TIMEOUT = 100ms;
6060 std::unique_lock lock(mLock);
6061 mLooper->wake();
6062 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6063 return result == std::cv_status::no_timeout;
6064}
6065
Vishnu Naire798b472020-07-23 13:52:21 -07006066/**
6067 * Sets focus to the window identified by the token. This must be called
6068 * after updating any input window handles.
6069 *
6070 * Params:
6071 * request.token - input channel token used to identify the window that should gain focus.
6072 * request.focusedToken - the token that the caller expects currently to be focused. If the
6073 * specified token does not match the currently focused window, this request will be dropped.
6074 * If the specified focused token matches the currently focused window, the call will succeed.
6075 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6076 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6077 * when requesting the focus change. This determines which request gets
6078 * precedence if there is a focus change request from another source such as pointer down.
6079 */
Vishnu Nair958da932020-08-21 17:12:37 -07006080void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6081 { // acquire lock
6082 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006083 std::optional<FocusResolver::FocusChanges> changes =
6084 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6085 if (changes) {
6086 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006087 }
6088 } // release lock
6089 // Wake up poll loop since it may need to make new input dispatching choices.
6090 mLooper->wake();
6091}
6092
Vishnu Nairc519ff72021-01-21 08:23:08 -08006093void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6094 if (changes.oldFocus) {
6095 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006096 if (focusedInputChannel) {
6097 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6098 "focus left window");
6099 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006100 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006101 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006102 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006103 if (changes.newFocus) {
6104 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006105 }
6106
Prabir Pradhan99987712020-11-10 18:43:05 -08006107 // If a window has pointer capture, then it must have focus. We need to ensure that this
6108 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6109 // If the window loses focus before it loses pointer capture, then the window can be in a state
6110 // where it has pointer capture but not focus, violating the contract. Therefore we must
6111 // dispatch the pointer capture event before the focus event. Since focus events are added to
6112 // the front of the queue (above), we add the pointer capture event to the front of the queue
6113 // after the focus events are added. This ensures the pointer capture event ends up at the
6114 // front.
6115 disablePointerCaptureForcedLocked();
6116
Vishnu Nairc519ff72021-01-21 08:23:08 -08006117 if (mFocusedDisplayId == changes.displayId) {
6118 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006119 }
6120}
Vishnu Nair958da932020-08-21 17:12:37 -07006121
Prabir Pradhan99987712020-11-10 18:43:05 -08006122void InputDispatcher::disablePointerCaptureForcedLocked() {
6123 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
6124 return;
6125 }
6126
6127 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6128
6129 if (mFocusedWindowRequestedPointerCapture) {
6130 mFocusedWindowRequestedPointerCapture = false;
6131 setPointerCaptureLocked(false);
6132 }
6133
6134 if (!mWindowTokenWithPointerCapture) {
6135 // No need to send capture changes because no window has capture.
6136 return;
6137 }
6138
6139 if (mPendingEvent != nullptr) {
6140 // Move the pending event to the front of the queue. This will give the chance
6141 // for the pending event to be dropped if it is a captured event.
6142 mInboundQueue.push_front(mPendingEvent);
6143 mPendingEvent = nullptr;
6144 }
6145
6146 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6147 false /* hasCapture */);
6148 mInboundQueue.push_front(std::move(entry));
6149}
6150
Prabir Pradhan99987712020-11-10 18:43:05 -08006151void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6152 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6153 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6154 commandEntry->enabled = enabled;
6155 postCommandLocked(std::move(commandEntry));
6156}
6157
6158void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6159 android::inputdispatcher::CommandEntry* commandEntry) {
6160 mLock.unlock();
6161
6162 mPolicy->setPointerCapture(commandEntry->enabled);
6163
6164 mLock.lock();
6165}
6166
Garfield Tane84e6f92019-08-29 17:28:41 -07006167} // namespace android::inputdispatcher