blob: dca870d0dfdb2cec1bdf2f9188b3f3aeb62e5194 [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>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050052#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070053#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100054#include <binder/IServiceManager.h>
55#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080056#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000059#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010061#include <statslog.h>
62#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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080081using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080082using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100083using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::InputEventInjectionResult;
85using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080087
Garfield Tane84e6f92019-08-29 17:28:41 -070088namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Default input dispatching timeout if there is no focused application or paused window
91// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050092constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
93 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Amount of time to allow for an event to be dispatched (measured since its eventTime)
101// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// 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 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118// Event log tags. See EventLogTags.logtags for reference
119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
121
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122static inline nsecs_t now() {
123 return systemTime(SYSTEM_TIME_MONOTONIC);
124}
125
126static inline const char* toString(bool value) {
127 return value ? "true" : "false";
128}
129
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000130static inline const std::string toString(sp<IBinder> binder) {
131 if (binder == nullptr) {
132 return "<null>";
133 }
134 return StringPrintf("%p", binder.get());
135}
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
139 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140}
141
142static bool isValidKeyAction(int32_t action) {
143 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
146 return true;
147 default:
148 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150}
151
152static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 ALOGE("Key event has invalid action code 0x%x", action);
155 return false;
156 }
157 return true;
158}
159
Michael Wright7b159c92015-05-14 14:48:03 +0100160static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_DOWN:
163 case AMOTION_EVENT_ACTION_UP:
164 case AMOTION_EVENT_ACTION_CANCEL:
165 case AMOTION_EVENT_ACTION_MOVE:
166 case AMOTION_EVENT_ACTION_OUTSIDE:
167 case AMOTION_EVENT_ACTION_HOVER_ENTER:
168 case AMOTION_EVENT_ACTION_HOVER_MOVE:
169 case AMOTION_EVENT_ACTION_HOVER_EXIT:
170 case AMOTION_EVENT_ACTION_SCROLL:
171 return true;
172 case AMOTION_EVENT_ACTION_POINTER_DOWN:
173 case AMOTION_EVENT_ACTION_POINTER_UP: {
174 int32_t index = getMotionEventActionPointerIndex(action);
175 return index >= 0 && index < pointerCount;
176 }
177 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
178 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
179 return actionButton != 0;
180 default:
181 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 }
183}
184
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500185static int64_t millis(std::chrono::nanoseconds t) {
186 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
187}
188
Michael Wright7b159c92015-05-14 14:48:03 +0100189static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 const PointerProperties* pointerProperties) {
191 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 ALOGE("Motion event has invalid action code 0x%x", action);
193 return false;
194 }
195 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000196 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return false;
199 }
200 BitSet32 pointerIdBits;
201 for (size_t i = 0; i < pointerCount; i++) {
202 int32_t id = pointerProperties[i].id;
203 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700204 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
205 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 return false;
207 }
208 if (pointerIdBits.hasBit(id)) {
209 ALOGE("Motion event has duplicate pointer id %d", id);
210 return false;
211 }
212 pointerIdBits.markBit(id);
213 }
214 return true;
215}
216
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000217static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000219 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
221
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 bool first = true;
224 Region::const_iterator cur = region.begin();
225 Region::const_iterator const tail = region.end();
226 while (cur != tail) {
227 if (first) {
228 first = false;
229 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800230 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 cur++;
234 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000235 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236}
237
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500238static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
239 constexpr size_t maxEntries = 50; // max events to print
240 constexpr size_t skipBegin = maxEntries / 2;
241 const size_t skipEnd = queue.size() - maxEntries / 2;
242 // skip from maxEntries / 2 ... size() - maxEntries/2
243 // only print from 0 .. skipBegin and then from skipEnd .. size()
244
245 std::string dump;
246 for (size_t i = 0; i < queue.size(); i++) {
247 const DispatchEntry& entry = *queue[i];
248 if (i >= skipBegin && i < skipEnd) {
249 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
250 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
251 continue;
252 }
253 dump.append(INDENT4);
254 dump += entry.eventEntry->getDescription();
255 dump += StringPrintf(", seq=%" PRIu32
256 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
257 entry.seq, entry.targetFlags, entry.resolvedAction,
258 ns2ms(currentTime - entry.eventEntry->eventTime));
259 if (entry.deliveryTime != 0) {
260 // This entry was delivered, so add information on how long we've been waiting
261 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
262 }
263 dump.append("\n");
264 }
265 return dump;
266}
267
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700268/**
269 * Find the entry in std::unordered_map by key, and return it.
270 * If the entry is not found, return a default constructed entry.
271 *
272 * Useful when the entries are vectors, since an empty vector will be returned
273 * if the entry is not found.
274 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
275 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700276template <typename K, typename V>
277static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700278 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700279 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800280}
281
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700282/**
283 * Find the entry in std::unordered_map by value, and remove it.
284 * If more than one entry has the same value, then all matching
285 * key-value pairs will be removed.
286 *
287 * Return true if at least one value has been removed.
288 */
289template <typename K, typename V>
290static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
291 bool removed = false;
292 for (auto it = map.begin(); it != map.end();) {
293 if (it->second == value) {
294 it = map.erase(it);
295 removed = true;
296 } else {
297 it++;
298 }
299 }
300 return removed;
301}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800302
Vishnu Nair958da932020-08-21 17:12:37 -0700303/**
304 * Find the entry in std::unordered_map by key and return the value as an optional.
305 */
306template <typename K, typename V>
307static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
308 auto it = map.find(key);
309 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
310}
311
chaviwaf87b3e2019-10-01 16:59:28 -0700312static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
313 if (first == second) {
314 return true;
315 }
316
317 if (first == nullptr || second == nullptr) {
318 return false;
319 }
320
321 return first->getToken() == second->getToken();
322}
323
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800324static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
325 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
326}
327
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700329 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000330 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900331 if (eventEntry->type == EventEntry::Type::MOTION) {
332 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
333 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
334 const ui::Transform identityTransform;
335 // Use identity transform for joystick events events because they don't depend on
336 // the window info
337 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
338 1.0f /*globalScaleFactor*/);
339 }
340 }
341
chaviw1ff3d1e2020-07-01 15:53:47 -0700342 if (inputTarget.useDefaultPointerTransform()) {
343 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700344 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700345 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000346 }
347
348 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
349 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
350
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700351 std::vector<PointerCoords> pointerCoords;
352 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000353
354 // Use the first pointer information to normalize all other pointers. This could be any pointer
355 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700356 // uses the transform for the normalized pointer.
357 const ui::Transform& firstPointerTransform =
358 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
359 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360
361 // Iterate through all pointers in the event to normalize against the first.
362 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
363 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
364 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700365 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366
367 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700368 // First, apply the current pointer's transform to update the coordinates into
369 // window space.
370 pointerCoords[pointerIndex].transform(currTransform);
371 // Next, apply the inverse transform of the normalized coordinates so the
372 // current coordinates are transformed into the normalized coordinate space.
373 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374 }
375
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700376 std::unique_ptr<MotionEntry> combinedMotionEntry =
377 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
378 motionEntry.deviceId, motionEntry.source,
379 motionEntry.displayId, motionEntry.policyFlags,
380 motionEntry.action, motionEntry.actionButton,
381 motionEntry.flags, motionEntry.metaState,
382 motionEntry.buttonState, motionEntry.classification,
383 motionEntry.edgeFlags, motionEntry.xPrecision,
384 motionEntry.yPrecision, motionEntry.xCursorPosition,
385 motionEntry.yCursorPosition, motionEntry.downTime,
386 motionEntry.pointerCount, motionEntry.pointerProperties,
387 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388
389 if (motionEntry.injectionState) {
390 combinedMotionEntry->injectionState = motionEntry.injectionState;
391 combinedMotionEntry->injectionState->refCount += 1;
392 }
393
394 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700395 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
396 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000397 return dispatchEntry;
398}
399
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700400static void addGestureMonitors(const std::vector<Monitor>& monitors,
401 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
402 float yOffset = 0) {
403 if (monitors.empty()) {
404 return;
405 }
406 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
407 for (const Monitor& monitor : monitors) {
408 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
409 }
410}
411
Garfield Tan15601662020-09-22 15:32:38 -0700412static status_t openInputChannelPair(const std::string& name,
413 std::shared_ptr<InputChannel>& serverChannel,
414 std::unique_ptr<InputChannel>& clientChannel) {
415 std::unique_ptr<InputChannel> uniqueServerChannel;
416 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
417
418 serverChannel = std::move(uniqueServerChannel);
419 return result;
420}
421
Vishnu Nair958da932020-08-21 17:12:37 -0700422const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
423 switch (result) {
424 case InputDispatcher::FocusResult::OK:
425 return "Ok";
426 case InputDispatcher::FocusResult::NO_WINDOW:
427 return "Window not found";
428 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
429 return "Window not focusable";
430 case InputDispatcher::FocusResult::NOT_VISIBLE:
431 return "Window not visible";
432 }
433}
434
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500435template <typename T>
436static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
437 if (lhs == nullptr && rhs == nullptr) {
438 return true;
439 }
440 if (lhs == nullptr || rhs == nullptr) {
441 return false;
442 }
443 return *lhs == *rhs;
444}
445
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000446static sp<IPlatformCompatNative> getCompatService() {
447 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
448 if (service == nullptr) {
449 ALOGE("Failed to link to compat service");
450 return nullptr;
451 }
452 return interface_cast<IPlatformCompatNative>(service);
453}
454
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000455static KeyEvent createKeyEvent(const KeyEntry& entry) {
456 KeyEvent event;
457 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
458 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
459 entry.repeatCount, entry.downTime, entry.eventTime);
460 return event;
461}
462
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000463static std::optional<int32_t> findMonitorPidByToken(
464 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
465 const sp<IBinder>& token) {
466 for (const auto& it : monitorsByDisplay) {
467 const std::vector<Monitor>& monitors = it.second;
468 for (const Monitor& monitor : monitors) {
469 if (monitor.inputChannel->getConnectionToken() == token) {
470 return monitor.pid;
471 }
472 }
473 }
474 return std::nullopt;
475}
476
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477// --- InputDispatcher ---
478
Garfield Tan00f511d2019-06-12 16:55:40 -0700479InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
480 : mPolicy(policy),
481 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700482 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800483 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700484 mAppSwitchSawKeyDown(false),
485 mAppSwitchDueTime(LONG_LONG_MAX),
486 mNextUnblockedEvent(nullptr),
487 mDispatchEnabled(false),
488 mDispatchFrozen(false),
489 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800490 // mInTouchMode will be initialized by the WindowManager to the default device config.
491 // To avoid leaking stack in case that call never comes, and for tests,
492 // initialize it here anyways.
493 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100494 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000495 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800496 mFocusedWindowRequestedPointerCapture(false),
497 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000498 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800500 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501
Yi Kong9b14ac62018-07-17 13:48:38 -0700502 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503
504 policy->getDispatcherConfiguration(&mConfig);
505}
506
507InputDispatcher::~InputDispatcher() {
508 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800509 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510
511 resetKeyRepeatLocked();
512 releasePendingEventLocked();
513 drainInboundQueueLocked();
514 }
515
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700516 while (!mConnectionsByFd.empty()) {
517 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700518 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 }
520}
521
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700522status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700523 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700524 return ALREADY_EXISTS;
525 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700526 mThread = std::make_unique<InputThread>(
527 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
528 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700529}
530
531status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700532 if (mThread && mThread->isCallingThread()) {
533 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700534 return INVALID_OPERATION;
535 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700536 mThread.reset();
537 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700538}
539
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540void InputDispatcher::dispatchOnce() {
541 nsecs_t nextWakeupTime = LONG_LONG_MAX;
542 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800543 std::scoped_lock _l(mLock);
544 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545
546 // Run a dispatch loop if there are no pending commands.
547 // The dispatch loop might enqueue commands to run afterwards.
548 if (!haveCommandsLocked()) {
549 dispatchOnceInnerLocked(&nextWakeupTime);
550 }
551
552 // Run all pending commands if there are any.
553 // If any commands were run then force the next poll to wake up immediately.
554 if (runCommandsLockedInterruptible()) {
555 nextWakeupTime = LONG_LONG_MIN;
556 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800557
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700558 // If we are still waiting for ack on some events,
559 // we might have to wake up earlier to check if an app is anr'ing.
560 const nsecs_t nextAnrCheck = processAnrsLocked();
561 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
562
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800563 // We are about to enter an infinitely long sleep, because we have no commands or
564 // pending or queued events
565 if (nextWakeupTime == LONG_LONG_MAX) {
566 mDispatcherEnteredIdle.notify_all();
567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 } // release lock
569
570 // Wait for callback or timeout or wake. (make sure we round up, not down)
571 nsecs_t currentTime = now();
572 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
573 mLooper->pollOnce(timeoutMillis);
574}
575
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700576/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500577 * Raise ANR if there is no focused window.
578 * Before the ANR is raised, do a final state check:
579 * 1. The currently focused application must be the same one we are waiting for.
580 * 2. Ensure we still don't have a focused window.
581 */
582void InputDispatcher::processNoFocusedWindowAnrLocked() {
583 // Check if the application that we are waiting for is still focused.
584 std::shared_ptr<InputApplicationHandle> focusedApplication =
585 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
586 if (focusedApplication == nullptr ||
587 focusedApplication->getApplicationToken() !=
588 mAwaitedFocusedApplication->getApplicationToken()) {
589 // Unexpected because we should have reset the ANR timer when focused application changed
590 ALOGE("Waited for a focused window, but focused application has already changed to %s",
591 focusedApplication->getName().c_str());
592 return; // The focused application has changed.
593 }
594
595 const sp<InputWindowHandle>& focusedWindowHandle =
596 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
597 if (focusedWindowHandle != nullptr) {
598 return; // We now have a focused window. No need for ANR.
599 }
600 onAnrLocked(mAwaitedFocusedApplication);
601}
602
603/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700604 * Check if any of the connections' wait queues have events that are too old.
605 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
606 * Return the time at which we should wake up next.
607 */
608nsecs_t InputDispatcher::processAnrsLocked() {
609 const nsecs_t currentTime = now();
610 nsecs_t nextAnrCheck = LONG_LONG_MAX;
611 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
612 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
613 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500614 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700615 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500616 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700617 return LONG_LONG_MIN;
618 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500619 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700620 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
621 }
622 }
623
624 // Check if any connection ANRs are due
625 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
626 if (currentTime < nextAnrCheck) { // most likely scenario
627 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
628 }
629
630 // If we reached here, we have an unresponsive connection.
631 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
632 if (connection == nullptr) {
633 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
634 return nextAnrCheck;
635 }
636 connection->responsive = false;
637 // Stop waking up for this unresponsive connection
638 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000639 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700640 return LONG_LONG_MIN;
641}
642
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500643std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700644 sp<InputWindowHandle> window = getWindowHandleLocked(token);
645 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500646 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700647 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500648 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700649}
650
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
652 nsecs_t currentTime = now();
653
Jeff Browndc5992e2014-04-11 01:27:26 -0700654 // Reset the key repeat timer whenever normal dispatch is suspended while the
655 // device is in a non-interactive state. This is to ensure that we abort a key
656 // repeat if the device is just coming out of sleep.
657 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 resetKeyRepeatLocked();
659 }
660
661 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
662 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100663 if (DEBUG_FOCUS) {
664 ALOGD("Dispatch frozen. Waiting some more.");
665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 return;
667 }
668
669 // Optimize latency of app switches.
670 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
671 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
672 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
673 if (mAppSwitchDueTime < *nextWakeupTime) {
674 *nextWakeupTime = mAppSwitchDueTime;
675 }
676
677 // Ready to start a new event.
678 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700680 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 if (isAppSwitchDue) {
682 // The inbound queue is empty so the app switch key we were waiting
683 // for will never arrive. Stop waiting for it.
684 resetPendingAppSwitchLocked(false);
685 isAppSwitchDue = false;
686 }
687
688 // Synthesize a key repeat if appropriate.
689 if (mKeyRepeatState.lastKeyEntry) {
690 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
691 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
692 } else {
693 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
694 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
695 }
696 }
697 }
698
699 // Nothing to do if there is no pending event.
700 if (!mPendingEvent) {
701 return;
702 }
703 } else {
704 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700705 mPendingEvent = mInboundQueue.front();
706 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 traceInboundQueueLengthLocked();
708 }
709
710 // Poke user activity for this event.
711 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700712 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 }
715
716 // Now we have an event to dispatch.
717 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700718 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700720 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700722 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700724 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 }
726
727 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700728 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 }
730
731 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700732 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700733 const ConfigurationChangedEntry& typedEntry =
734 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700735 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700736 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 break;
738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700740 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700741 const DeviceResetEntry& typedEntry =
742 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700743 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700744 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700745 break;
746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100748 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700749 std::shared_ptr<FocusEntry> typedEntry =
750 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100751 dispatchFocusLocked(currentTime, typedEntry);
752 done = true;
753 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
754 break;
755 }
756
Prabir Pradhan99987712020-11-10 18:43:05 -0800757 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
758 const auto typedEntry =
759 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
760 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
761 done = true;
762 break;
763 }
764
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700765 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700766 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700768 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 resetPendingAppSwitchLocked(true);
770 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700771 } else if (dropReason == DropReason::NOT_DROPPED) {
772 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700773 }
774 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700775 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700776 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
779 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700781 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 break;
783 }
784
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700785 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700786 std::shared_ptr<MotionEntry> motionEntry =
787 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700788 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
789 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700791 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700792 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700793 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
795 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700797 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
Chris Yef59a2f42020-10-16 12:55:26 -0700800
801 case EventEntry::Type::SENSOR: {
802 std::shared_ptr<SensorEntry> sensorEntry =
803 std::static_pointer_cast<SensorEntry>(mPendingEvent);
804 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
805 dropReason = DropReason::APP_SWITCH;
806 }
807 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
808 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
809 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
810 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
811 dropReason = DropReason::STALE;
812 }
813 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
814 done = true;
815 break;
816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 }
818
819 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700821 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
Michael Wright3a981722015-06-10 15:26:13 +0100823 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824
825 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828}
829
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700830/**
831 * Return true if the events preceding this incoming motion event should be dropped
832 * Return false otherwise (the default behaviour)
833 */
834bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700835 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700836 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837
838 // Optimize case where the current application is unresponsive and the user
839 // decides to touch a window in a different application.
840 // If the application takes too long to catch up then we drop all events preceding
841 // the touch into the other window.
842 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700843 int32_t displayId = motionEntry.displayId;
844 int32_t x = static_cast<int32_t>(
845 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
846 int32_t y = static_cast<int32_t>(
847 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
848 sp<InputWindowHandle> touchedWindowHandle =
849 findTouchedWindowAtLocked(displayId, x, y, nullptr);
850 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700851 touchedWindowHandle->getApplicationToken() !=
852 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700853 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700854 ALOGI("Pruning input queue because user touched a different application while waiting "
855 "for %s",
856 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700857 return true;
858 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700859
860 // Alternatively, maybe there's a gesture monitor that could handle this event
861 std::vector<TouchedMonitor> gestureMonitors =
862 findTouchedGestureMonitorsLocked(displayId, {});
863 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
864 sp<Connection> connection =
865 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000866 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700867 // This monitor could take more input. Drop all events preceding this
868 // event, so that gesture monitor could get a chance to receive the stream
869 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
870 "responsive gesture monitor that may handle the event",
871 mAwaitedFocusedApplication->getName().c_str());
872 return true;
873 }
874 }
875 }
876
877 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
878 // yet been processed by some connections, the dispatcher will wait for these motion
879 // events to be processed before dispatching the key event. This is because these motion events
880 // may cause a new window to be launched, which the user might expect to receive focus.
881 // To prevent waiting forever for such events, just send the key to the currently focused window
882 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
883 ALOGD("Received a new pointer down event, stop waiting for events to process and "
884 "just send the pending key event to the focused window.");
885 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700886 }
887 return false;
888}
889
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700890bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700891 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 mInboundQueue.push_back(std::move(newEntry));
893 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 traceInboundQueueLengthLocked();
895
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700896 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700897 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 // Optimize app switch latency.
899 // If the application takes too long to catch up then we drop all events preceding
900 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700901 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700905 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700911 mAppSwitchSawKeyDown = false;
912 needWake = true;
913 }
914 }
915 }
916 break;
917 }
918
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700919 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700920 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
921 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700922 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100926 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700927 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
928 break;
929 }
930 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800931 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700932 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800933 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700934 // nothing to do
935 break;
936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 }
938
939 return needWake;
940}
941
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700942void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700943 // Do not store sensor event in recent queue to avoid flooding the queue.
944 if (entry->type != EventEntry::Type::SENSOR) {
945 mRecentQueue.push_back(entry);
946 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700947 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700948 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 }
950}
951
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700953 int32_t y, TouchState* touchState,
954 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700956 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
957 LOG_ALWAYS_FATAL(
958 "Must provide a valid touch state if adding portal windows or outside targets");
959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700961 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800962 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 const InputWindowInfo* windowInfo = windowHandle->getInfo();
964 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100965 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966
967 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100968 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
969 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
970 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800972 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 if (portalToDisplayId != ADISPLAY_ID_NONE &&
974 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800975 if (addPortalWindows) {
976 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700977 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800978 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700979 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 // Found window.
983 return windowHandle;
984 }
985 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800986
Michael Wright44753b12020-07-08 13:48:11 +0100987 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700988 touchState->addOrUpdateWindow(windowHandle,
989 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
990 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700995 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996}
997
Garfield Tane84e6f92019-08-29 17:28:41 -0700998std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700999 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001000 std::vector<TouchedMonitor> touchedMonitors;
1001
1002 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1003 addGestureMonitors(monitors, touchedMonitors);
1004 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1005 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1006 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1008 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001009 }
1010 return touchedMonitors;
1011}
1012
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001013void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 const char* reason;
1015 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001016 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 reason = "inbound event was dropped because the policy consumed it";
1021 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001022 case DropReason::DISABLED:
1023 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 ALOGI("Dropped event because input dispatch is disabled.");
1025 }
1026 reason = "inbound event was dropped because input dispatch is disabled";
1027 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 ALOGI("Dropped event because of pending overdue app switch.");
1030 reason = "inbound event was dropped because of pending overdue app switch";
1031 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001032 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 ALOGI("Dropped event because the current application is not responding and the user "
1034 "has started interacting with a different application.");
1035 reason = "inbound event was dropped because the current application is not responding "
1036 "and the user has started interacting with a different application";
1037 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001038 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039 ALOGI("Dropped event because it is stale.");
1040 reason = "inbound event was dropped because it is stale";
1041 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001042 case DropReason::NO_POINTER_CAPTURE:
1043 ALOGI("Dropped event because there is no window with Pointer Capture.");
1044 reason = "inbound event was dropped because there is no window with Pointer Capture";
1045 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001046 case DropReason::NOT_DROPPED: {
1047 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
1051
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001052 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001053 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1055 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001058 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001059 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1060 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1062 synthesizeCancelationEventsForAllConnectionsLocked(options);
1063 } else {
1064 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1065 synthesizeCancelationEventsForAllConnectionsLocked(options);
1066 }
1067 break;
1068 }
Chris Yef59a2f42020-10-16 12:55:26 -07001069 case EventEntry::Type::SENSOR: {
1070 break;
1071 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001072 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1073 break;
1074 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001075 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001076 case EventEntry::Type::CONFIGURATION_CHANGED:
1077 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001078 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001079 break;
1080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 }
1082}
1083
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001084static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1086 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087}
1088
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001089bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1090 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1091 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1092 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093}
1094
1095bool InputDispatcher::isAppSwitchPendingLocked() {
1096 return mAppSwitchDueTime != LONG_LONG_MAX;
1097}
1098
1099void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1100 mAppSwitchDueTime = LONG_LONG_MAX;
1101
1102#if DEBUG_APP_SWITCH
1103 if (handled) {
1104 ALOGD("App switch has arrived.");
1105 } else {
1106 ALOGD("App switch was abandoned.");
1107 }
1108#endif
1109}
1110
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001112 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113}
1114
1115bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001116 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 return false;
1118 }
1119
1120 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001121 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001122 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001124 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125
1126 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001127 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 return true;
1129}
1130
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001131void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1132 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133}
1134
1135void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001136 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001137 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001138 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 releaseInboundEventLocked(entry);
1140 }
1141 traceInboundQueueLengthLocked();
1142}
1143
1144void InputDispatcher::releasePendingEventLocked() {
1145 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001147 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149}
1150
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001151void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001153 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154#if DEBUG_DISPATCH_CYCLE
1155 ALOGD("Injected inbound event was dropped.");
1156#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001157 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001160 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 }
1162 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163}
1164
1165void InputDispatcher::resetKeyRepeatLocked() {
1166 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001167 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169}
1170
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001171std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1172 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173
Michael Wright2e732952014-09-24 13:26:59 -07001174 uint32_t policyFlags = entry->policyFlags &
1175 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001177 std::shared_ptr<KeyEntry> newEntry =
1178 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1179 entry->source, entry->displayId, policyFlags, entry->action,
1180 entry->flags, entry->keyCode, entry->scanCode,
1181 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001183 newEntry->syntheticRepeat = true;
1184 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001186 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187}
1188
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001189bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001190 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001192 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193#endif
1194
1195 // Reset key repeating in case a keyboard device was added or removed or something.
1196 resetKeyRepeatLocked();
1197
1198 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001199 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1200 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001202 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 return true;
1204}
1205
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001206bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1207 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1210 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211#endif
1212
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001213 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 synthesizeCancelationEventsForAllConnectionsLocked(options);
1216 return true;
1217}
1218
Vishnu Nairad321cd2020-08-20 16:40:21 -07001219void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001220 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001221 if (mPendingEvent != nullptr) {
1222 // Move the pending event to the front of the queue. This will give the chance
1223 // for the pending event to get dispatched to the newly focused window
1224 mInboundQueue.push_front(mPendingEvent);
1225 mPendingEvent = nullptr;
1226 }
1227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 std::unique_ptr<FocusEntry> focusEntry =
1229 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1230 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001231
1232 // This event should go to the front of the queue, but behind all other focus events
1233 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001234 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001235 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001236 [](const std::shared_ptr<EventEntry>& event) {
1237 return event->type == EventEntry::Type::FOCUS;
1238 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001239
1240 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001242}
1243
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001245 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001246 if (channel == nullptr) {
1247 return; // Window has gone away
1248 }
1249 InputTarget target;
1250 target.inputChannel = channel;
1251 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1252 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001253 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1254 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001255 std::string reason = std::string("reason=").append(entry->reason);
1256 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001257 dispatchEventLocked(currentTime, entry, {target});
1258}
1259
Prabir Pradhan99987712020-11-10 18:43:05 -08001260void InputDispatcher::dispatchPointerCaptureChangedLocked(
1261 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1262 DropReason& dropReason) {
1263 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1264 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1265 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1266 "The Pointer Capture state has already been dispatched to the window.");
1267 // Pointer capture was already forcefully disabled because of focus change.
1268 dropReason = DropReason::NOT_DROPPED;
1269 return;
1270 }
1271
1272 // Set drop reason for early returns
1273 dropReason = DropReason::NO_POINTER_CAPTURE;
1274
1275 sp<IBinder> token;
1276 if (entry->pointerCaptureEnabled) {
1277 // Enable Pointer Capture
1278 if (!mFocusedWindowRequestedPointerCapture) {
1279 // This can happen if a window requests capture and immediately releases capture.
1280 ALOGW("No window requested Pointer Capture.");
1281 return;
1282 }
1283 token = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
1284 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1285 mWindowTokenWithPointerCapture = token;
1286 } else {
1287 // Disable Pointer Capture
1288 token = mWindowTokenWithPointerCapture;
1289 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001290 if (mFocusedWindowRequestedPointerCapture) {
1291 mFocusedWindowRequestedPointerCapture = false;
1292 setPointerCaptureLocked(false);
1293 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001294 }
1295
1296 auto channel = getInputChannelLocked(token);
1297 if (channel == nullptr) {
1298 // Window has gone away, clean up Pointer Capture state.
1299 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001300 if (mFocusedWindowRequestedPointerCapture) {
1301 mFocusedWindowRequestedPointerCapture = false;
1302 setPointerCaptureLocked(false);
1303 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001304 return;
1305 }
1306 InputTarget target;
1307 target.inputChannel = channel;
1308 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1309 entry->dispatchInProgress = true;
1310 dispatchEventLocked(currentTime, entry, {target});
1311
1312 dropReason = DropReason::NOT_DROPPED;
1313}
1314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001318 if (!entry->dispatchInProgress) {
1319 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1320 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1321 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1322 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001323 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 // We have seen two identical key downs in a row which indicates that the device
1325 // driver is automatically generating key repeats itself. We take note of the
1326 // repeat here, but we disable our own next key repeat timer since it is clear that
1327 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001328 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1329 // Make sure we don't get key down from a different device. If a different
1330 // device Id has same key pressed down, the new device Id will replace the
1331 // current one to hold the key repeat with repeat count reset.
1332 // In the future when got a KEY_UP on the device id, drop it and do not
1333 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1335 resetKeyRepeatLocked();
1336 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1337 } else {
1338 // Not a repeat. Save key down state in case we do see a repeat later.
1339 resetKeyRepeatLocked();
1340 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1341 }
1342 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001343 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1344 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001345 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001346#if DEBUG_INBOUND_EVENT_DETAILS
1347 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1348#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 resetKeyRepeatLocked();
1351 }
1352
1353 if (entry->repeatCount == 1) {
1354 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1355 } else {
1356 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1357 }
1358
1359 entry->dispatchInProgress = true;
1360
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001361 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363
1364 // Handle case where the policy asked us to try again later last time.
1365 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1366 if (currentTime < entry->interceptKeyWakeupTime) {
1367 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1368 *nextWakeupTime = entry->interceptKeyWakeupTime;
1369 }
1370 return false; // wait until next wakeup
1371 }
1372 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1373 entry->interceptKeyWakeupTime = 0;
1374 }
1375
1376 // Give the policy a chance to intercept the key.
1377 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1378 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001379 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001380 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001381 sp<IBinder> focusedWindowToken =
1382 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001383 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001385 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 return false; // wait for the command to run
1387 } else {
1388 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1389 }
1390 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001391 if (*dropReason == DropReason::NOT_DROPPED) {
1392 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 }
1394 }
1395
1396 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001397 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001398 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1400 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001401 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 return true;
1403 }
1404
1405 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001406 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001407 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001408 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001409 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 return false;
1411 }
1412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001413 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001414 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 return true;
1416 }
1417
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001418 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001419 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420
1421 // Dispatch the key.
1422 dispatchEventLocked(currentTime, entry, inputTargets);
1423 return true;
1424}
1425
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001426void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001428 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001429 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1430 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1432 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1433 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434#endif
1435}
1436
Chris Yef59a2f42020-10-16 12:55:26 -07001437void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1438 mLock.unlock();
1439
1440 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1441 if (entry->accuracyChanged) {
1442 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1443 }
1444 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1445 entry->hwTimestamp, entry->values);
1446 mLock.lock();
1447}
1448
1449void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1450 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1451#if DEBUG_OUTBOUND_EVENT_DETAILS
1452 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1453 "source=0x%x, sensorType=%s",
1454 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1455 NamedEnum::string(sensorType).c_str());
1456#endif
1457 std::unique_ptr<CommandEntry> commandEntry =
1458 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1459 commandEntry->sensorEntry = entry;
1460 postCommandLocked(std::move(commandEntry));
1461}
1462
1463bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1464#if DEBUG_OUTBOUND_EVENT_DETAILS
1465 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1466 NamedEnum::string(sensorType).c_str());
1467#endif
1468 { // acquire lock
1469 std::scoped_lock _l(mLock);
1470
1471 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1472 std::shared_ptr<EventEntry> entry = *it;
1473 if (entry->type == EventEntry::Type::SENSOR) {
1474 it = mInboundQueue.erase(it);
1475 releaseInboundEventLocked(entry);
1476 }
1477 }
1478 }
1479 return true;
1480}
1481
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001482bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001484 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001486 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 entry->dispatchInProgress = true;
1488
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001489 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 }
1491
1492 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001493 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001494 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001495 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1496 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 return true;
1498 }
1499
1500 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1501
1502 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001503 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504
1505 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001506 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 if (isPointerEvent) {
1508 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001509 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001510 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001511 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 } else {
1513 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001514 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001515 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001517 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 return false;
1519 }
1520
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001522 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001523 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1524 return true;
1525 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001526 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001527 CancelationOptions::Mode mode(isPointerEvent
1528 ? CancelationOptions::CANCEL_POINTER_EVENTS
1529 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1530 CancelationOptions options(mode, "input event injection failed");
1531 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 return true;
1533 }
1534
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001535 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001536 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001538 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001539 std::unordered_map<int32_t, TouchState>::iterator it =
1540 mTouchStatesByDisplay.find(entry->displayId);
1541 if (it != mTouchStatesByDisplay.end()) {
1542 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001543 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001544 // The event has gone through these portal windows, so we add monitoring targets of
1545 // the corresponding displays as well.
1546 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001547 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001548 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001549 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001550 }
1551 }
1552 }
1553 }
1554
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 // Dispatch the motion.
1556 if (conflictingPointerActions) {
1557 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 synthesizeCancelationEventsForAllConnectionsLocked(options);
1560 }
1561 dispatchEventLocked(currentTime, entry, inputTargets);
1562 return true;
1563}
1564
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001567 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 ", policyFlags=0x%x, "
1569 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1570 "metaState=0x%x, buttonState=0x%x,"
1571 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001572 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1573 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1574 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001578 "x=%f, y=%f, pressure=%f, size=%f, "
1579 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1580 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1582 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1583 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1584 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1585 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1586 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1587 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1588 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1589 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1590 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 }
1592#endif
1593}
1594
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1596 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001598 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599#if DEBUG_DISPATCH_CYCLE
1600 ALOGD("dispatchEventToCurrentInputTargets");
1601#endif
1602
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001603 updateInteractionTokensLocked(*eventEntry, inputTargets);
1604
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1606
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001609 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001610 sp<Connection> connection =
1611 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001612 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001613 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001615 if (DEBUG_FOCUS) {
1616 ALOGD("Dropping event delivery to target with channel '%s' because it "
1617 "is no longer registered with the input dispatcher.",
1618 inputTarget.inputChannel->getName().c_str());
1619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 }
1621 }
1622}
1623
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001624void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1625 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1626 // If the policy decides to close the app, we will get a channel removal event via
1627 // unregisterInputChannel, and will clean up the connection that way. We are already not
1628 // sending new pointers to the connection when it blocked, but focused events will continue to
1629 // pile up.
1630 ALOGW("Canceling events for %s because it is unresponsive",
1631 connection->inputChannel->getName().c_str());
1632 if (connection->status == Connection::STATUS_NORMAL) {
1633 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1634 "application not responding");
1635 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 }
1637}
1638
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001639void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001640 if (DEBUG_FOCUS) {
1641 ALOGD("Resetting ANR timeouts.");
1642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643
1644 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001645 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001646 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647}
1648
Tiger Huang721e26f2018-07-24 22:26:19 +08001649/**
1650 * Get the display id that the given event should go to. If this event specifies a valid display id,
1651 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1652 * Focused display is the display that the user most recently interacted with.
1653 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001655 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001656 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001657 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001658 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1659 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001660 break;
1661 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001662 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001663 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1664 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 break;
1666 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001667 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001668 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001669 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001670 case EventEntry::Type::DEVICE_RESET:
1671 case EventEntry::Type::SENSOR: {
1672 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 return ADISPLAY_ID_NONE;
1674 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001675 }
1676 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1677}
1678
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001679bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1680 const char* focusedWindowName) {
1681 if (mAnrTracker.empty()) {
1682 // already processed all events that we waited for
1683 mKeyIsWaitingForEventsTimeout = std::nullopt;
1684 return false;
1685 }
1686
1687 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1688 // Start the timer
1689 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1690 "focus to change",
1691 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001692 mKeyIsWaitingForEventsTimeout = currentTime +
1693 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1694 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001695 return true;
1696 }
1697
1698 // We still have pending events, and already started the timer
1699 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1700 return true; // Still waiting
1701 }
1702
1703 // Waited too long, and some connection still hasn't processed all motions
1704 // Just send the key to the focused window
1705 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1706 focusedWindowName);
1707 mKeyIsWaitingForEventsTimeout = std::nullopt;
1708 return false;
1709}
1710
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001711InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1712 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1713 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001714 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715
Tiger Huang721e26f2018-07-24 22:26:19 +08001716 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001717 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001718 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001719 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1720
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // If there is no currently focused window and no focused application
1722 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001723 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1724 ALOGI("Dropping %s event because there is no focused window or focused application in "
1725 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001726 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001727 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 }
1729
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001730 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1731 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1732 // start interacting with another application via touch (app switch). This code can be removed
1733 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1734 // an app is expected to have a focused window.
1735 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1736 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1737 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001738 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1739 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1740 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001742 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001743 ALOGW("Waiting because no window has focus but %s may eventually add a "
1744 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001745 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001746 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001747 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001748 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1749 // Already raised ANR. Drop the event
1750 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001751 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001752 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001753 } else {
1754 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001755 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001756 }
1757 }
1758
1759 // we have a valid, non-null focused window
1760 resetNoFocusedWindowTimeoutLocked();
1761
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001763 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001764 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
1766
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001767 if (focusedWindowHandle->getInfo()->paused) {
1768 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001769 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001770 }
1771
1772 // If the event is a key event, then we must wait for all previous events to
1773 // complete before delivering it because previous events may have the
1774 // side-effect of transferring focus to a different window and we want to
1775 // ensure that the following keys are sent to the new window.
1776 //
1777 // Suppose the user touches a button in a window then immediately presses "A".
1778 // If the button causes a pop-up window to appear then we want to ensure that
1779 // the "A" key is delivered to the new pop-up window. This is because users
1780 // often anticipate pending UI changes when typing on a keyboard.
1781 // To obtain this behavior, we must serialize key events with respect to all
1782 // prior input events.
1783 if (entry.type == EventEntry::Type::KEY) {
1784 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1785 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 }
1789
1790 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001791 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001792 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1793 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794
1795 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001796 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797}
1798
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001799/**
1800 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1801 * that are currently unresponsive.
1802 */
1803std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1804 const std::vector<TouchedMonitor>& monitors) const {
1805 std::vector<TouchedMonitor> responsiveMonitors;
1806 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1807 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1808 sp<Connection> connection = getConnectionLocked(
1809 monitor.monitor.inputChannel->getConnectionToken());
1810 if (connection == nullptr) {
1811 ALOGE("Could not find connection for monitor %s",
1812 monitor.monitor.inputChannel->getName().c_str());
1813 return false;
1814 }
1815 if (!connection->responsive) {
1816 ALOGW("Unresponsive monitor %s will not get the new gesture",
1817 connection->inputChannel->getName().c_str());
1818 return false;
1819 }
1820 return true;
1821 });
1822 return responsiveMonitors;
1823}
1824
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001825InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1826 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1827 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001828 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 enum InjectionPermission {
1830 INJECTION_PERMISSION_UNKNOWN,
1831 INJECTION_PERMISSION_GRANTED,
1832 INJECTION_PERMISSION_DENIED
1833 };
1834
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 // For security reasons, we defer updating the touch state until we are sure that
1836 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001837 int32_t displayId = entry.displayId;
1838 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1840
1841 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001842 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001844 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1845 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 // Copy current touch state into tempTouchState.
1848 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1849 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001850 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001851 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001852 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1853 mTouchStatesByDisplay.find(displayId);
1854 if (oldStateIt != mTouchStatesByDisplay.end()) {
1855 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001856 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001857 }
1858
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001859 bool isSplit = tempTouchState.split;
1860 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1861 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1862 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1864 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1865 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1866 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1867 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001868 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 bool wrongDevice = false;
1870 if (newGesture) {
1871 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001872 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001873 ALOGI("Dropping event because a pointer for a different device is already down "
1874 "in display %" PRId32,
1875 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001876 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 switchedDevice = false;
1879 wrongDevice = true;
1880 goto Failed;
1881 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001882 tempTouchState.reset();
1883 tempTouchState.down = down;
1884 tempTouchState.deviceId = entry.deviceId;
1885 tempTouchState.source = entry.source;
1886 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001888 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001889 ALOGI("Dropping move event because a pointer for a different device is already active "
1890 "in display %" PRId32,
1891 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001892 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001894 switchedDevice = false;
1895 wrongDevice = true;
1896 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
1899 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1900 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1901
Garfield Tan00f511d2019-06-12 16:55:40 -07001902 int32_t x;
1903 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001905 // Always dispatch mouse events to cursor position.
1906 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001907 x = int32_t(entry.xCursorPosition);
1908 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001909 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001910 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1911 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001912 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001913 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001914 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1916 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001917
1918 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001919 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001920 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001923 if (newTouchedWindowHandle != nullptr &&
1924 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001925 // New window supports splitting, but we should never split mouse events.
1926 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 } else if (isSplit) {
1928 // New window does not support splitting but we have already split events.
1929 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001930 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932
1933 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001934 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001936 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001937 }
1938
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001939 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1940 ALOGI("Not sending touch event to %s because it is paused",
1941 newTouchedWindowHandle->getName().c_str());
1942 newTouchedWindowHandle = nullptr;
1943 }
1944
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001945 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001946 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001947 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1948 if (!isResponsive) {
1949 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1951 newTouchedWindowHandle = nullptr;
1952 }
1953 }
1954
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001955 // Drop events that can't be trusted due to occlusion
1956 if (newTouchedWindowHandle != nullptr &&
1957 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1958 TouchOcclusionInfo occlusionInfo =
1959 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001960 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001961 if (DEBUG_TOUCH_OCCLUSION) {
1962 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1963 for (const auto& log : occlusionInfo.debugInfo) {
1964 ALOGD("%s", log.c_str());
1965 }
1966 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001967 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1968 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1969 ALOGW("Dropping untrusted touch event due to %s/%d",
1970 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1971 newTouchedWindowHandle = nullptr;
1972 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001973 }
1974 }
1975
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001976 // Also don't send the new touch event to unresponsive gesture monitors
1977 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1978
Michael Wright3dd60e22019-03-27 22:06:44 +00001979 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1980 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001981 "(%d, %d) in display %" PRId32 ".",
1982 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001983 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001984 goto Failed;
1985 }
1986
1987 if (newTouchedWindowHandle != nullptr) {
1988 // Set target flags.
1989 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1990 if (isSplit) {
1991 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001993 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1994 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1995 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1996 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1997 }
1998
1999 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002000 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2001 newHoverWindowHandle = nullptr;
2002 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002003 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002004 }
2005
2006 // Update the temporary touch state.
2007 BitSet32 pointerIds;
2008 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002009 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002010 pointerIds.markBit(pointerId);
2011 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002012 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 }
2014
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002015 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 } else {
2017 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2018
2019 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002020 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002021 if (DEBUG_FOCUS) {
2022 ALOGD("Dropping event because the pointer is not down or we previously "
2023 "dropped the pointer down event in display %" PRId32,
2024 displayId);
2025 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002026 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 goto Failed;
2028 }
2029
2030 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002031 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002032 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002033 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2034 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035
2036 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002037 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002038 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002039 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2040 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002041 if (DEBUG_FOCUS) {
2042 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2043 oldTouchedWindowHandle->getName().c_str(),
2044 newTouchedWindowHandle->getName().c_str(), displayId);
2045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002047 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2048 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2049 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050
2051 // Make a slippery entrance into the new window.
2052 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2053 isSplit = true;
2054 }
2055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056 int32_t targetFlags =
2057 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 if (isSplit) {
2059 targetFlags |= InputTarget::FLAG_SPLIT;
2060 }
2061 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2062 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002063 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2064 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
2066
2067 BitSet32 pointerIds;
2068 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002069 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002071 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
2073 }
2074 }
2075
2076 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002077 // Let the previous window know that the hover sequence is over, unless we already did it
2078 // when dispatching it as is to newTouchedWindowHandle.
2079 if (mLastHoverWindowHandle != nullptr &&
2080 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2081 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082#if DEBUG_HOVER
2083 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002086 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2087 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
2089
Garfield Tandf26e862020-07-01 20:18:19 -07002090 // Let the new window know that the hover sequence is starting, unless we already did it
2091 // when dispatching it as is to newTouchedWindowHandle.
2092 if (newHoverWindowHandle != nullptr &&
2093 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2094 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095#if DEBUG_HOVER
2096 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002097 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002099 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2100 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2101 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
2103 }
2104
2105 // Check permission to inject into all touched foreground windows and ensure there
2106 // is at least one touched foreground window.
2107 {
2108 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002109 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2111 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002112 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002113 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 injectionPermission = INJECTION_PERMISSION_DENIED;
2115 goto Failed;
2116 }
2117 }
2118 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002119 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002120 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002121 ALOGI("Dropping event because there is no touched foreground window in display "
2122 "%" PRId32 " or gesture monitor to receive it.",
2123 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002124 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 goto Failed;
2126 }
2127
2128 // Permission granted to injection into all touched foreground windows.
2129 injectionPermission = INJECTION_PERMISSION_GRANTED;
2130 }
2131
2132 // Check whether windows listening for outside touches are owned by the same UID. If it is
2133 // set the policy flag that we will not reveal coordinate information to this window.
2134 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2135 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002136 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002137 if (foregroundWindowHandle) {
2138 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002139 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2141 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2142 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002143 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2144 InputTarget::FLAG_ZERO_COORDS,
2145 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 }
2148 }
2149 }
2150 }
2151
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 // If this is the first pointer going down and the touched window has a wallpaper
2153 // then also add the touched wallpaper windows so they are locked in for the duration
2154 // of the touch gesture.
2155 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2156 // engine only supports touch events. We would need to add a mechanism similar
2157 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2158 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2159 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002160 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002161 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002162 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002163 getWindowHandlesLocked(displayId);
2164 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002166 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002167 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 .addOrUpdateWindow(windowHandle,
2170 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2171 InputTarget::
2172 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2173 InputTarget::FLAG_DISPATCH_AS_IS,
2174 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 }
2176 }
2177 }
2178 }
2179
2180 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002181 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002183 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002185 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002189 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002191 }
2192
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 // Drop the outside or hover touch windows since we will not care about them
2194 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002195 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196
2197Failed:
2198 // Check injection permission once and for all.
2199 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002200 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 injectionPermission = INJECTION_PERMISSION_GRANTED;
2202 } else {
2203 injectionPermission = INJECTION_PERMISSION_DENIED;
2204 }
2205 }
2206
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002207 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2208 return injectionResult;
2209 }
2210
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002212 if (!wrongDevice) {
2213 if (switchedDevice) {
2214 if (DEBUG_FOCUS) {
2215 ALOGD("Conflicting pointer actions: Switched to a different device.");
2216 }
2217 *outConflictingPointerActions = true;
2218 }
2219
2220 if (isHoverAction) {
2221 // Started hovering, therefore no longer down.
2222 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002223 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002224 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2225 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 *outConflictingPointerActions = true;
2228 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002229 tempTouchState.reset();
2230 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2231 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2232 tempTouchState.deviceId = entry.deviceId;
2233 tempTouchState.source = entry.source;
2234 tempTouchState.displayId = displayId;
2235 }
2236 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2237 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2238 // All pointers up or canceled.
2239 tempTouchState.reset();
2240 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2241 // First pointer went down.
2242 if (oldState && oldState->down) {
2243 if (DEBUG_FOCUS) {
2244 ALOGD("Conflicting pointer actions: Down received while already down.");
2245 }
2246 *outConflictingPointerActions = true;
2247 }
2248 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2249 // One pointer went up.
2250 if (isSplit) {
2251 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2252 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002254 for (size_t i = 0; i < tempTouchState.windows.size();) {
2255 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2256 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2257 touchedWindow.pointerIds.clearBit(pointerId);
2258 if (touchedWindow.pointerIds.isEmpty()) {
2259 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2260 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002263 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002265 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002266 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002267
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002268 // Save changes unless the action was scroll in which case the temporary touch
2269 // state was only valid for this one action.
2270 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2271 if (tempTouchState.displayId >= 0) {
2272 mTouchStatesByDisplay[displayId] = tempTouchState;
2273 } else {
2274 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002278 // Update hover state.
2279 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 }
2281
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 return injectionResult;
2283}
2284
2285void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002286 int32_t targetFlags, BitSet32 pointerIds,
2287 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002288 std::vector<InputTarget>::iterator it =
2289 std::find_if(inputTargets.begin(), inputTargets.end(),
2290 [&windowHandle](const InputTarget& inputTarget) {
2291 return inputTarget.inputChannel->getConnectionToken() ==
2292 windowHandle->getToken();
2293 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002294
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002295 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002296
2297 if (it == inputTargets.end()) {
2298 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002299 std::shared_ptr<InputChannel> inputChannel =
2300 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002301 if (inputChannel == nullptr) {
2302 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2303 return;
2304 }
2305 inputTarget.inputChannel = inputChannel;
2306 inputTarget.flags = targetFlags;
2307 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2308 inputTargets.push_back(inputTarget);
2309 it = inputTargets.end() - 1;
2310 }
2311
2312 ALOG_ASSERT(it->flags == targetFlags);
2313 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2314
chaviw1ff3d1e2020-07-01 15:53:47 -07002315 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316}
2317
Michael Wright3dd60e22019-03-27 22:06:44 +00002318void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 int32_t displayId, float xOffset,
2320 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002321 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2322 mGlobalMonitorsByDisplay.find(displayId);
2323
2324 if (it != mGlobalMonitorsByDisplay.end()) {
2325 const std::vector<Monitor>& monitors = it->second;
2326 for (const Monitor& monitor : monitors) {
2327 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330}
2331
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2333 float yOffset,
2334 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002335 InputTarget target;
2336 target.inputChannel = monitor.inputChannel;
2337 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002338 ui::Transform t;
2339 t.set(xOffset, yOffset);
2340 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002341 inputTargets.push_back(target);
2342}
2343
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 const InjectionState* injectionState) {
2346 if (injectionState &&
2347 (windowHandle == nullptr ||
2348 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2349 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002350 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 "owned by uid %d",
2353 injectionState->injectorPid, injectionState->injectorUid,
2354 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 } else {
2356 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359 return false;
2360 }
2361 return true;
2362}
2363
Robert Carrc9bf1d32020-04-13 17:21:08 -07002364/**
2365 * Indicate whether one window handle should be considered as obscuring
2366 * another window handle. We only check a few preconditions. Actually
2367 * checking the bounds is left to the caller.
2368 */
2369static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2370 const sp<InputWindowHandle>& otherHandle) {
2371 // Compare by token so cloned layers aren't counted
2372 if (haveSameToken(windowHandle, otherHandle)) {
2373 return false;
2374 }
2375 auto info = windowHandle->getInfo();
2376 auto otherInfo = otherHandle->getInfo();
2377 if (!otherInfo->visible) {
2378 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002379 } else if (otherInfo->alpha == 0 &&
2380 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2381 // Those act as if they were invisible, so we don't need to flag them.
2382 // We do want to potentially flag touchable windows even if they have 0
2383 // opacity, since they can consume touches and alter the effects of the
2384 // user interaction (eg. apps that rely on
2385 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2386 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2387 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002388 } else if (info->ownerUid == otherInfo->ownerUid) {
2389 // If ownerUid is the same we don't generate occlusion events as there
2390 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002391 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002392 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002393 return false;
2394 } else if (otherInfo->displayId != info->displayId) {
2395 return false;
2396 }
2397 return true;
2398}
2399
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002400/**
2401 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2402 * untrusted, one should check:
2403 *
2404 * 1. If result.hasBlockingOcclusion is true.
2405 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2406 * BLOCK_UNTRUSTED.
2407 *
2408 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2409 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2410 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2411 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2412 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2413 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2414 *
2415 * If neither of those is true, then it means the touch can be allowed.
2416 */
2417InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2418 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002419 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2420 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002421 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2422 TouchOcclusionInfo info;
2423 info.hasBlockingOcclusion = false;
2424 info.obscuringOpacity = 0;
2425 info.obscuringUid = -1;
2426 std::map<int32_t, float> opacityByUid;
2427 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2428 if (windowHandle == otherHandle) {
2429 break; // All future windows are below us. Exit early.
2430 }
2431 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2432 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002433 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2434 if (DEBUG_TOUCH_OCCLUSION) {
2435 info.debugInfo.push_back(
2436 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2437 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002438 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2439 // we perform the checks below to see if the touch can be propagated or not based on the
2440 // window's touch occlusion mode
2441 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2442 info.hasBlockingOcclusion = true;
2443 info.obscuringUid = otherInfo->ownerUid;
2444 info.obscuringPackage = otherInfo->packageName;
2445 break;
2446 }
2447 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2448 uint32_t uid = otherInfo->ownerUid;
2449 float opacity =
2450 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2451 // Given windows A and B:
2452 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2453 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2454 opacityByUid[uid] = opacity;
2455 if (opacity > info.obscuringOpacity) {
2456 info.obscuringOpacity = opacity;
2457 info.obscuringUid = uid;
2458 info.obscuringPackage = otherInfo->packageName;
2459 }
2460 }
2461 }
2462 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002463 if (DEBUG_TOUCH_OCCLUSION) {
2464 info.debugInfo.push_back(
2465 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2466 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002467 return info;
2468}
2469
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002470std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2471 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002472 return StringPrintf(INDENT2
2473 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2474 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2475 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2476 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002477 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002478 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002479 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002480 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2481 info->frameTop, info->frameRight, info->frameBottom,
2482 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002483 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2484 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2485 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002486}
2487
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002488bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2489 if (occlusionInfo.hasBlockingOcclusion) {
2490 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2491 occlusionInfo.obscuringUid);
2492 return false;
2493 }
2494 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2495 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2496 "%.2f, maximum allowed = %.2f)",
2497 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2498 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2499 return false;
2500 }
2501 return true;
2502}
2503
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2505 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002507 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002508 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002509 if (windowHandle == otherHandle) {
2510 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002513 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002514 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 return true;
2516 }
2517 }
2518 return false;
2519}
2520
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002521bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2522 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002523 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002524 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002525 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002526 if (windowHandle == otherHandle) {
2527 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002528 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002529 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002530 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002531 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002532 return true;
2533 }
2534 }
2535 return false;
2536}
2537
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002538std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002539 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002541 if (applicationHandle != nullptr) {
2542 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002543 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 } else {
2545 return applicationHandle->getName();
2546 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002547 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002548 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002550 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 }
2552}
2553
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002554void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002555 if (eventEntry.type == EventEntry::Type::FOCUS ||
2556 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2557 // Focus or pointer capture changed events are passed to apps, but do not represent user
2558 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002559 return;
2560 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002561 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002562 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002563 if (focusedWindowHandle != nullptr) {
2564 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002565 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002567 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568#endif
2569 return;
2570 }
2571 }
2572
2573 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002574 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002575 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002576 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2577 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 return;
2579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002581 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002582 eventType = USER_ACTIVITY_EVENT_TOUCH;
2583 }
2584 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002586 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002587 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2588 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 return;
2590 }
2591 eventType = USER_ACTIVITY_EVENT_BUTTON;
2592 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002594 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002595 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002596 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002597 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002598 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002599 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002600 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002601 break;
2602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002605 std::unique_ptr<CommandEntry> commandEntry =
2606 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002607 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002609 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610}
2611
2612void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002614 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002615 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002616 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002617 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002618 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002619 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002620 ATRACE_NAME(message.c_str());
2621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622#if DEBUG_DISPATCH_CYCLE
2623 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002624 "globalScaleFactor=%f, pointerIds=0x%x %s",
2625 connection->getInputChannelName().c_str(), inputTarget.flags,
2626 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2627 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628#endif
2629
2630 // Skip this event if the connection status is not normal.
2631 // We don't want to enqueue additional outbound events if the connection is broken.
2632 if (connection->status != Connection::STATUS_NORMAL) {
2633#if DEBUG_DISPATCH_CYCLE
2634 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636#endif
2637 return;
2638 }
2639
2640 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002641 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2642 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2643 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002644 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002646 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002647 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002648 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002649 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 if (!splitMotionEntry) {
2651 return; // split event was dropped
2652 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002653 if (DEBUG_FOCUS) {
2654 ALOGD("channel '%s' ~ Split motion event.",
2655 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002656 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002657 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002658 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2659 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 return;
2661 }
2662 }
2663
2664 // Not splitting. Enqueue dispatch entries for the event as is.
2665 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2666}
2667
2668void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002670 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002671 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002672 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002673 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002674 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002675 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002676 ATRACE_NAME(message.c_str());
2677 }
2678
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002679 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680
2681 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002682 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002683 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002684 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002685 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002686 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002688 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002690 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002692 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694
2695 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002696 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 startDispatchCycleLocked(currentTime, connection);
2698 }
2699}
2700
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002702 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002703 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002705 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002706 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2707 connection->getInputChannelName().c_str(),
2708 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002709 ATRACE_NAME(message.c_str());
2710 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002711 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 if (!(inputTargetFlags & dispatchMode)) {
2713 return;
2714 }
2715 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2716
2717 // This is a new event.
2718 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002719 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002720 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002722 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2723 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002724 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002726 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002727 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002728 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002729 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002730 dispatchEntry->resolvedAction = keyEntry.action;
2731 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2734 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2737 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 return; // skip the inconsistent event
2740 }
2741 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002744 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002745 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002746 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2747 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2748 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2749 static_cast<int32_t>(IdGenerator::Source::OTHER);
2750 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2752 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2753 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2754 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2755 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2756 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2757 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2758 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2759 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2760 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2761 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002762 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002763 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764 }
2765 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002766 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2767 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2770 "event",
2771 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002776 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2778 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2779 }
2780 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2781 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2785 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2788 "event",
2789 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 return; // skip the inconsistent event
2792 }
2793
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002794 dispatchEntry->resolvedEventId =
2795 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2796 ? mIdGenerator.nextId()
2797 : motionEntry.id;
2798 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2799 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2800 ") to MotionEvent(id=0x%" PRIx32 ").",
2801 motionEntry.id, dispatchEntry->resolvedEventId);
2802 ATRACE_NAME(message.c_str());
2803 }
2804
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002805 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002806 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807
2808 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002810 case EventEntry::Type::FOCUS:
2811 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002812 break;
2813 }
Chris Yef59a2f42020-10-16 12:55:26 -07002814 case EventEntry::Type::SENSOR: {
2815 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2816 break;
2817 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002818 case EventEntry::Type::CONFIGURATION_CHANGED:
2819 case EventEntry::Type::DEVICE_RESET: {
2820 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002821 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002822 break;
2823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825
2826 // Remember that we are waiting for this dispatch to complete.
2827 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002828 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830
2831 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002832 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002833 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002834}
2835
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002836/**
2837 * This function is purely for debugging. It helps us understand where the user interaction
2838 * was taking place. For example, if user is touching launcher, we will see a log that user
2839 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2840 * We will see both launcher and wallpaper in that list.
2841 * Once the interaction with a particular set of connections starts, no new logs will be printed
2842 * until the set of interacted connections changes.
2843 *
2844 * The following items are skipped, to reduce the logspam:
2845 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2846 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2847 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2848 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2849 * Both of those ACTION_UP events would not be logged
2850 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2851 * will not be logged. This is omitted to reduce the amount of data printed.
2852 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2853 * gesture monitor is the only connection receiving the remainder of the gesture.
2854 */
2855void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2856 const std::vector<InputTarget>& targets) {
2857 // Skip ACTION_UP events, and all events other than keys and motions
2858 if (entry.type == EventEntry::Type::KEY) {
2859 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2860 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2861 return;
2862 }
2863 } else if (entry.type == EventEntry::Type::MOTION) {
2864 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2865 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2866 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2867 return;
2868 }
2869 } else {
2870 return; // Not a key or a motion
2871 }
2872
2873 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2874 std::vector<sp<Connection>> newConnections;
2875 for (const InputTarget& target : targets) {
2876 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2877 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2878 continue; // Skip windows that receive ACTION_OUTSIDE
2879 }
2880
2881 sp<IBinder> token = target.inputChannel->getConnectionToken();
2882 sp<Connection> connection = getConnectionLocked(token);
2883 if (connection == nullptr || connection->monitor) {
2884 continue; // We only need to keep track of the non-monitor connections.
2885 }
2886 newConnectionTokens.insert(std::move(token));
2887 newConnections.emplace_back(connection);
2888 }
2889 if (newConnectionTokens == mInteractionConnectionTokens) {
2890 return; // no change
2891 }
2892 mInteractionConnectionTokens = newConnectionTokens;
2893
2894 std::string windowList;
2895 for (const sp<Connection>& connection : newConnections) {
2896 windowList += connection->getWindowName() + ", ";
2897 }
2898 std::string message = "Interaction with windows: " + windowList;
2899 if (windowList.empty()) {
2900 message += "<none>";
2901 }
2902 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2903}
2904
chaviwfd6d3512019-03-25 13:23:49 -07002905void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002906 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002907 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002908 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2909 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002910 return;
2911 }
2912
Vishnu Nairad321cd2020-08-20 16:40:21 -07002913 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2914 if (focusedToken == token) {
2915 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002916 return;
2917 }
2918
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002919 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2920 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002921 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002922 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923}
2924
2925void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002927 if (ATRACE_ENABLED()) {
2928 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002930 ATRACE_NAME(message.c_str());
2931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934#endif
2935
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002936 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2937 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002939 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002940 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002941 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942
2943 // Publish the event.
2944 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002945 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2946 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002947 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002948 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2949 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 status = connection->inputPublisher
2953 .publishKeyEvent(dispatchEntry->seq,
2954 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2955 keyEntry.source, keyEntry.displayId,
2956 std::move(hmac), dispatchEntry->resolvedAction,
2957 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2958 keyEntry.scanCode, keyEntry.metaState,
2959 keyEntry.repeatCount, keyEntry.downTime,
2960 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 }
2963
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002964 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002965 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002968 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969
chaviw82357092020-01-28 13:13:06 -08002970 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002971 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2973 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002974 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002975 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2976 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002977 // Don't apply window scale here since we don't want scale to affect raw
2978 // coordinates. The scale will be sent back to the client and applied
2979 // later when requesting relative coordinates.
2980 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2981 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 }
2983 usingCoords = scaledCoords;
2984 }
2985 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 // We don't want the dispatch target to know.
2987 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 scaledCoords[i].clear();
2990 }
2991 usingCoords = scaledCoords;
2992 }
2993 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002994
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002995 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996
2997 // Publish the motion event.
2998 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002999 .publishMotionEvent(dispatchEntry->seq,
3000 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003001 motionEntry.deviceId, motionEntry.source,
3002 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003003 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003004 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 motionEntry.edgeFlags, motionEntry.metaState,
3007 motionEntry.buttonState,
3008 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003009 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003010 motionEntry.xPrecision, motionEntry.yPrecision,
3011 motionEntry.xCursorPosition,
3012 motionEntry.yCursorPosition,
3013 motionEntry.downTime, motionEntry.eventTime,
3014 motionEntry.pointerCount,
3015 motionEntry.pointerProperties, usingCoords);
3016 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 break;
3018 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003019
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003020 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003021 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003022 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003023 focusEntry.id,
3024 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003025 mInTouchMode);
3026 break;
3027 }
3028
Prabir Pradhan99987712020-11-10 18:43:05 -08003029 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3030 const auto& captureEntry =
3031 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3032 status = connection->inputPublisher
3033 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3034 captureEntry.pointerCaptureEnabled);
3035 break;
3036 }
3037
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003038 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003039 case EventEntry::Type::DEVICE_RESET:
3040 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003041 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003042 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003043 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
3046
3047 // Check the result.
3048 if (status) {
3049 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003050 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 "This is unexpected because the wait queue is empty, so the pipe "
3053 "should be empty and we shouldn't have any problems writing an "
3054 "event to it, status=%d",
3055 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3057 } else {
3058 // Pipe is full and we are waiting for the app to finish process some events
3059 // before sending more events to it.
3060#if DEBUG_DISPATCH_CYCLE
3061 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 "waiting for the application to catch up",
3063 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
3066 } else {
3067 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003068 "status=%d",
3069 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3071 }
3072 return;
3073 }
3074
3075 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003076 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3077 connection->outboundQueue.end(),
3078 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003079 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003080 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003081 if (connection->responsive) {
3082 mAnrTracker.insert(dispatchEntry->timeoutTime,
3083 connection->inputChannel->getConnectionToken());
3084 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003085 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087}
3088
chaviw09c8d2d2020-08-24 15:48:26 -07003089std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3090 size_t size;
3091 switch (event.type) {
3092 case VerifiedInputEvent::Type::KEY: {
3093 size = sizeof(VerifiedKeyEvent);
3094 break;
3095 }
3096 case VerifiedInputEvent::Type::MOTION: {
3097 size = sizeof(VerifiedMotionEvent);
3098 break;
3099 }
3100 }
3101 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3102 return mHmacKeyManager.sign(start, size);
3103}
3104
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003105const std::array<uint8_t, 32> InputDispatcher::getSignature(
3106 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3107 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3108 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3109 // Only sign events up and down events as the purely move events
3110 // are tied to their up/down counterparts so signing would be redundant.
3111 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3112 verifiedEvent.actionMasked = actionMasked;
3113 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003114 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003115 }
3116 return INVALID_HMAC;
3117}
3118
3119const std::array<uint8_t, 32> InputDispatcher::getSignature(
3120 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3121 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3122 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3123 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003124 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003125}
3126
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 const sp<Connection>& connection, uint32_t seq,
3129 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130#if DEBUG_DISPATCH_CYCLE
3131 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133#endif
3134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 if (connection->status == Connection::STATUS_BROKEN ||
3136 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 return;
3138 }
3139
3140 // Notify other system components and prepare to start the next dispatch cycle.
3141 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3142}
3143
3144void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 const sp<Connection>& connection,
3146 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147#if DEBUG_DISPATCH_CYCLE
3148 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150#endif
3151
3152 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003153 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003154 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003155 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003156 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
3158 // The connection appears to be unrecoverably broken.
3159 // Ignore already broken or zombie connections.
3160 if (connection->status == Connection::STATUS_NORMAL) {
3161 connection->status = Connection::STATUS_BROKEN;
3162
3163 if (notify) {
3164 // Notify other system components.
3165 onDispatchCycleBrokenLocked(currentTime, connection);
3166 }
3167 }
3168}
3169
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003170void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3171 while (!queue.empty()) {
3172 DispatchEntry* dispatchEntry = queue.front();
3173 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003174 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
3176}
3177
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003178void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182 delete dispatchEntry;
3183}
3184
3185int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3186 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3187
3188 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003189 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003191 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 "fd=%d, events=0x%x",
3194 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 return 0; // remove the callback
3196 }
3197
3198 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003199 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3201 if (!(events & ALOOPER_EVENT_INPUT)) {
3202 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 "events=0x%x",
3204 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 return 1;
3206 }
3207
3208 nsecs_t currentTime = now();
3209 bool gotOne = false;
3210 status_t status;
3211 for (;;) {
3212 uint32_t seq;
3213 bool handled;
3214 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3215 if (status) {
3216 break;
3217 }
3218 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3219 gotOne = true;
3220 }
3221 if (gotOne) {
3222 d->runCommandsLockedInterruptible();
3223 if (status == WOULD_BLOCK) {
3224 return 1;
3225 }
3226 }
3227
3228 notify = status != DEAD_OBJECT || !connection->monitor;
3229 if (notify) {
3230 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 }
3233 } else {
3234 // Monitor channels are never explicitly unregistered.
3235 // We do it automatically when the remote endpoint is closed so don't warn
3236 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003237 const bool stillHaveWindowHandle =
3238 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3239 nullptr;
3240 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 if (notify) {
3242 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 "events=0x%x",
3244 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
3246 }
3247
Garfield Tan15601662020-09-22 15:32:38 -07003248 // Remove the channel.
3249 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252}
3253
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003256 for (const auto& [fd, connection] : mConnectionsByFd) {
3257 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 }
3259}
3260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003262 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003263 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3264 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3265}
3266
3267void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3268 const CancelationOptions& options,
3269 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3270 for (const auto& it : monitorsByDisplay) {
3271 const std::vector<Monitor>& monitors = it.second;
3272 for (const Monitor& monitor : monitors) {
3273 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003274 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003275 }
3276}
3277
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003279 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003280 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003281 if (connection == nullptr) {
3282 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003284
3285 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286}
3287
3288void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3289 const sp<Connection>& connection, const CancelationOptions& options) {
3290 if (connection->status == Connection::STATUS_BROKEN) {
3291 return;
3292 }
3293
3294 nsecs_t currentTime = now();
3295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003297 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003299 if (cancelationEvents.empty()) {
3300 return;
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003303 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3304 "with reality: %s, mode=%d.",
3305 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3306 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003308
3309 InputTarget target;
3310 sp<InputWindowHandle> windowHandle =
3311 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3312 if (windowHandle != nullptr) {
3313 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003314 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003315 target.globalScaleFactor = windowInfo->globalScaleFactor;
3316 }
3317 target.inputChannel = connection->inputChannel;
3318 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3319
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003320 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003322 switch (cancelationEventEntry->type) {
3323 case EventEntry::Type::KEY: {
3324 logOutboundKeyDetails("cancel - ",
3325 static_cast<const KeyEntry&>(*cancelationEventEntry));
3326 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003328 case EventEntry::Type::MOTION: {
3329 logOutboundMotionDetails("cancel - ",
3330 static_cast<const MotionEntry&>(*cancelationEventEntry));
3331 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003333 case EventEntry::Type::FOCUS:
3334 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3335 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003336 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003337 break;
3338 }
3339 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003340 case EventEntry::Type::DEVICE_RESET:
3341 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003342 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003343 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003344 break;
3345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
3347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3349 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003351
3352 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353}
3354
Svet Ganov5d3bc372020-01-26 23:11:07 -08003355void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3356 const sp<Connection>& connection) {
3357 if (connection->status == Connection::STATUS_BROKEN) {
3358 return;
3359 }
3360
3361 nsecs_t currentTime = now();
3362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003363 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003364 connection->inputState.synthesizePointerDownEvents(currentTime);
3365
3366 if (downEvents.empty()) {
3367 return;
3368 }
3369
3370#if DEBUG_OUTBOUND_EVENT_DETAILS
3371 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3372 connection->getInputChannelName().c_str(), downEvents.size());
3373#endif
3374
3375 InputTarget target;
3376 sp<InputWindowHandle> windowHandle =
3377 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3378 if (windowHandle != nullptr) {
3379 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003380 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003381 target.globalScaleFactor = windowInfo->globalScaleFactor;
3382 }
3383 target.inputChannel = connection->inputChannel;
3384 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003386 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003387 switch (downEventEntry->type) {
3388 case EventEntry::Type::MOTION: {
3389 logOutboundMotionDetails("down - ",
3390 static_cast<const MotionEntry&>(*downEventEntry));
3391 break;
3392 }
3393
3394 case EventEntry::Type::KEY:
3395 case EventEntry::Type::FOCUS:
3396 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003397 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003398 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3399 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003400 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003401 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003402 break;
3403 }
3404 }
3405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003406 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3407 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003408 }
3409
3410 startDispatchCycleLocked(currentTime, connection);
3411}
3412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003413std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3414 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 ALOG_ASSERT(pointerIds.value != 0);
3416
3417 uint32_t splitPointerIndexMap[MAX_POINTERS];
3418 PointerProperties splitPointerProperties[MAX_POINTERS];
3419 PointerCoords splitPointerCoords[MAX_POINTERS];
3420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003421 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 uint32_t splitPointerCount = 0;
3423
3424 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003425 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003427 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 uint32_t pointerId = uint32_t(pointerProperties.id);
3429 if (pointerIds.hasBit(pointerId)) {
3430 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3431 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3432 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003433 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 splitPointerCount += 1;
3435 }
3436 }
3437
3438 if (splitPointerCount != pointerIds.count()) {
3439 // This is bad. We are missing some of the pointers that we expected to deliver.
3440 // Most likely this indicates that we received an ACTION_MOVE events that has
3441 // different pointer ids than we expected based on the previous ACTION_DOWN
3442 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3443 // in this way.
3444 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 "we expected there to be %d pointers. This probably means we received "
3446 "a broken sequence of pointer ids from the input device.",
3447 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003448 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003451 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3454 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3456 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003457 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 uint32_t pointerId = uint32_t(pointerProperties.id);
3459 if (pointerIds.hasBit(pointerId)) {
3460 if (pointerIds.count() == 1) {
3461 // The first/last pointer went down/up.
3462 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003464 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3465 ? AMOTION_EVENT_ACTION_CANCEL
3466 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 } else {
3468 // A secondary pointer went down/up.
3469 uint32_t splitPointerIndex = 0;
3470 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3471 splitPointerIndex += 1;
3472 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 action = maskedAction |
3474 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
3476 } else {
3477 // An unrelated pointer changed.
3478 action = AMOTION_EVENT_ACTION_MOVE;
3479 }
3480 }
3481
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003482 int32_t newId = mIdGenerator.nextId();
3483 if (ATRACE_ENABLED()) {
3484 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3485 ") to MotionEvent(id=0x%" PRIx32 ").",
3486 originalMotionEntry.id, newId);
3487 ATRACE_NAME(message.c_str());
3488 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003489 std::unique_ptr<MotionEntry> splitMotionEntry =
3490 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3491 originalMotionEntry.deviceId, originalMotionEntry.source,
3492 originalMotionEntry.displayId,
3493 originalMotionEntry.policyFlags, action,
3494 originalMotionEntry.actionButton,
3495 originalMotionEntry.flags, originalMotionEntry.metaState,
3496 originalMotionEntry.buttonState,
3497 originalMotionEntry.classification,
3498 originalMotionEntry.edgeFlags,
3499 originalMotionEntry.xPrecision,
3500 originalMotionEntry.yPrecision,
3501 originalMotionEntry.xCursorPosition,
3502 originalMotionEntry.yCursorPosition,
3503 originalMotionEntry.downTime, splitPointerCount,
3504 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003506 if (originalMotionEntry.injectionState) {
3507 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 splitMotionEntry->injectionState->refCount += 1;
3509 }
3510
3511 return splitMotionEntry;
3512}
3513
3514void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3515#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003516 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517#endif
3518
3519 bool needWake;
3520 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003521 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003523 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3524 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3525 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 } // release lock
3527
3528 if (needWake) {
3529 mLooper->wake();
3530 }
3531}
3532
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003533/**
3534 * If one of the meta shortcuts is detected, process them here:
3535 * Meta + Backspace -> generate BACK
3536 * Meta + Enter -> generate HOME
3537 * This will potentially overwrite keyCode and metaState.
3538 */
3539void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003540 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003541 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3542 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3543 if (keyCode == AKEYCODE_DEL) {
3544 newKeyCode = AKEYCODE_BACK;
3545 } else if (keyCode == AKEYCODE_ENTER) {
3546 newKeyCode = AKEYCODE_HOME;
3547 }
3548 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003549 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003550 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003551 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003552 keyCode = newKeyCode;
3553 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3554 }
3555 } else if (action == AKEY_EVENT_ACTION_UP) {
3556 // In order to maintain a consistent stream of up and down events, check to see if the key
3557 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3558 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003559 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003560 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003561 auto replacementIt = mReplacedKeys.find(replacement);
3562 if (replacementIt != mReplacedKeys.end()) {
3563 keyCode = replacementIt->second;
3564 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003565 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3566 }
3567 }
3568}
3569
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3571#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3573 "policyFlags=0x%x, action=0x%x, "
3574 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3575 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3576 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3577 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578#endif
3579 if (!validateKeyEvent(args->action)) {
3580 return;
3581 }
3582
3583 uint32_t policyFlags = args->policyFlags;
3584 int32_t flags = args->flags;
3585 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003586 // InputDispatcher tracks and generates key repeats on behalf of
3587 // whatever notifies it, so repeatCount should always be set to 0
3588 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3590 policyFlags |= POLICY_FLAG_VIRTUAL;
3591 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 if (policyFlags & POLICY_FLAG_FUNCTION) {
3594 metaState |= AMETA_FUNCTION_ON;
3595 }
3596
3597 policyFlags |= POLICY_FLAG_TRUSTED;
3598
Michael Wright78f24442014-08-06 15:55:28 -07003599 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003600 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003601
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003603 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003604 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3605 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Michael Wright2b3c3302018-03-02 17:19:13 +00003607 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003609 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3610 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 bool needWake;
3615 { // acquire lock
3616 mLock.lock();
3617
3618 if (shouldSendKeyToInputFilterLocked(args)) {
3619 mLock.unlock();
3620
3621 policyFlags |= POLICY_FLAG_FILTERED;
3622 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3623 return; // event was consumed by the filter
3624 }
3625
3626 mLock.lock();
3627 }
3628
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003629 std::unique_ptr<KeyEntry> newEntry =
3630 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3631 args->displayId, policyFlags, args->action, flags,
3632 keyCode, args->scanCode, metaState, repeatCount,
3633 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003635 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 mLock.unlock();
3637 } // release lock
3638
3639 if (needWake) {
3640 mLooper->wake();
3641 }
3642}
3643
3644bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3645 return mInputFilterEnabled;
3646}
3647
3648void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3649#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003650 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3651 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003652 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3653 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003654 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003655 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3656 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3657 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3658 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 for (uint32_t i = 0; i < args->pointerCount; i++) {
3660 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 "x=%f, y=%f, pressure=%f, size=%f, "
3662 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3663 "orientation=%f",
3664 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3665 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3666 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3667 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3668 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3669 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3670 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3671 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3672 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3673 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3677 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 return;
3679 }
3680
3681 uint32_t policyFlags = args->policyFlags;
3682 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003683
3684 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003685 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003686 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3687 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003688 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690
3691 bool needWake;
3692 { // acquire lock
3693 mLock.lock();
3694
3695 if (shouldSendMotionToInputFilterLocked(args)) {
3696 mLock.unlock();
3697
3698 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003699 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003700 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3701 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003702 args->metaState, args->buttonState, args->classification, transform,
3703 args->xPrecision, args->yPrecision, args->xCursorPosition,
3704 args->yCursorPosition, args->downTime, args->eventTime,
3705 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706
3707 policyFlags |= POLICY_FLAG_FILTERED;
3708 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3709 return; // event was consumed by the filter
3710 }
3711
3712 mLock.lock();
3713 }
3714
3715 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003716 std::unique_ptr<MotionEntry> newEntry =
3717 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3718 args->source, args->displayId, policyFlags,
3719 args->action, args->actionButton, args->flags,
3720 args->metaState, args->buttonState,
3721 args->classification, args->edgeFlags,
3722 args->xPrecision, args->yPrecision,
3723 args->xCursorPosition, args->yCursorPosition,
3724 args->downTime, args->pointerCount,
3725 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003727 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 mLock.unlock();
3729 } // release lock
3730
3731 if (needWake) {
3732 mLooper->wake();
3733 }
3734}
3735
Chris Yef59a2f42020-10-16 12:55:26 -07003736void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3737#if DEBUG_INBOUND_EVENT_DETAILS
3738 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3739 " sensorType=%s",
3740 args->id, args->eventTime, args->deviceId, args->source,
3741 NamedEnum::string(args->sensorType).c_str());
3742#endif
3743
3744 bool needWake;
3745 { // acquire lock
3746 mLock.lock();
3747
3748 // Just enqueue a new sensor event.
3749 std::unique_ptr<SensorEntry> newEntry =
3750 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3751 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3752 args->sensorType, args->accuracy,
3753 args->accuracyChanged, args->values);
3754
3755 needWake = enqueueInboundEventLocked(std::move(newEntry));
3756 mLock.unlock();
3757 } // release lock
3758
3759 if (needWake) {
3760 mLooper->wake();
3761 }
3762}
3763
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003765 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766}
3767
3768void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3769#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003770 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 "switchMask=0x%08x",
3772 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773#endif
3774
3775 uint32_t policyFlags = args->policyFlags;
3776 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778}
3779
3780void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3781#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3783 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784#endif
3785
3786 bool needWake;
3787 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003788 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003790 std::unique_ptr<DeviceResetEntry> newEntry =
3791 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3792 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 } // release lock
3794
3795 if (needWake) {
3796 mLooper->wake();
3797 }
3798}
3799
Prabir Pradhan7e186182020-11-10 13:56:45 -08003800void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3801#if DEBUG_INBOUND_EVENT_DETAILS
3802 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3803 args->enabled ? "true" : "false");
3804#endif
3805
Prabir Pradhan99987712020-11-10 18:43:05 -08003806 bool needWake;
3807 { // acquire lock
3808 std::scoped_lock _l(mLock);
3809 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3810 args->enabled);
3811 needWake = enqueueInboundEventLocked(std::move(entry));
3812 } // release lock
3813
3814 if (needWake) {
3815 mLooper->wake();
3816 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003817}
3818
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003819InputEventInjectionResult InputDispatcher::injectInputEvent(
3820 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3821 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822#if DEBUG_INBOUND_EVENT_DETAILS
3823 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003824 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3825 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003827 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
3829 policyFlags |= POLICY_FLAG_INJECTED;
3830 if (hasInjectionPermission(injectorPid, injectorUid)) {
3831 policyFlags |= POLICY_FLAG_TRUSTED;
3832 }
3833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003834 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003836 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003837 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3838 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003839 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003840 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003843 int32_t flags = incomingKey.getFlags();
3844 int32_t keyCode = incomingKey.getKeyCode();
3845 int32_t metaState = incomingKey.getMetaState();
3846 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003847 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003848 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003849 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003850 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3851 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3852 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3855 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003856 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857
3858 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3859 android::base::Timer t;
3860 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3861 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3862 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3863 std::to_string(t.duration().count()).c_str());
3864 }
3865 }
3866
3867 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003868 std::unique_ptr<KeyEntry> injectedEntry =
3869 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3870 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3871 incomingKey.getDisplayId(), policyFlags, action,
3872 flags, keyCode, incomingKey.getScanCode(), metaState,
3873 incomingKey.getRepeatCount(),
3874 incomingKey.getDownTime());
3875 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003876 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 }
3878
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003879 case AINPUT_EVENT_TYPE_MOTION: {
3880 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3881 int32_t action = motionEvent->getAction();
3882 size_t pointerCount = motionEvent->getPointerCount();
3883 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3884 int32_t actionButton = motionEvent->getActionButton();
3885 int32_t displayId = motionEvent->getDisplayId();
3886 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003887 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003888 }
3889
3890 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3891 nsecs_t eventTime = motionEvent->getEventTime();
3892 android::base::Timer t;
3893 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3894 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3895 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3896 std::to_string(t.duration().count()).c_str());
3897 }
3898 }
3899
3900 mLock.lock();
3901 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3902 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003903 std::unique_ptr<MotionEntry> injectedEntry =
3904 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3905 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3906 motionEvent->getDisplayId(), policyFlags, action,
3907 actionButton, motionEvent->getFlags(),
3908 motionEvent->getMetaState(),
3909 motionEvent->getButtonState(),
3910 motionEvent->getClassification(),
3911 motionEvent->getEdgeFlags(),
3912 motionEvent->getXPrecision(),
3913 motionEvent->getYPrecision(),
3914 motionEvent->getRawXCursorPosition(),
3915 motionEvent->getRawYCursorPosition(),
3916 motionEvent->getDownTime(),
3917 uint32_t(pointerCount), pointerProperties,
3918 samplePointerCoords, motionEvent->getXOffset(),
3919 motionEvent->getYOffset());
3920 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3922 sampleEventTimes += 1;
3923 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003924 std::unique_ptr<MotionEntry> nextInjectedEntry =
3925 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3926 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3927 motionEvent->getDisplayId(), policyFlags,
3928 action, actionButton, motionEvent->getFlags(),
3929 motionEvent->getMetaState(),
3930 motionEvent->getButtonState(),
3931 motionEvent->getClassification(),
3932 motionEvent->getEdgeFlags(),
3933 motionEvent->getXPrecision(),
3934 motionEvent->getYPrecision(),
3935 motionEvent->getRawXCursorPosition(),
3936 motionEvent->getRawYCursorPosition(),
3937 motionEvent->getDownTime(),
3938 uint32_t(pointerCount), pointerProperties,
3939 samplePointerCoords,
3940 motionEvent->getXOffset(),
3941 motionEvent->getYOffset());
3942 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003943 }
3944 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003947 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003948 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003949 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 }
3951
3952 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 injectionState->injectionIsAsync = true;
3955 }
3956
3957 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003958 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003961 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003962 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003963 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 }
3965
3966 mLock.unlock();
3967
3968 if (needWake) {
3969 mLooper->wake();
3970 }
3971
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003972 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003974 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003976 if (syncMode == InputEventInjectionSync::NONE) {
3977 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 } else {
3979 for (;;) {
3980 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003981 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 break;
3983 }
3984
3985 nsecs_t remainingTimeout = endTime - now();
3986 if (remainingTimeout <= 0) {
3987#if DEBUG_INJECTION
3988 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003991 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 break;
3993 }
3994
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003995 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003998 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3999 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 while (injectionState->pendingForegroundDispatches != 0) {
4001#if DEBUG_INJECTION
4002 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004#endif
4005 nsecs_t remainingTimeout = endTime - now();
4006 if (remainingTimeout <= 0) {
4007#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4009 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004011 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 break;
4013 }
4014
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004015 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 }
4017 }
4018 }
4019
4020 injectionState->release();
4021 } // release lock
4022
4023#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004024 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026#endif
4027
4028 return injectionResult;
4029}
4030
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004031std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004032 std::array<uint8_t, 32> calculatedHmac;
4033 std::unique_ptr<VerifiedInputEvent> result;
4034 switch (event.getType()) {
4035 case AINPUT_EVENT_TYPE_KEY: {
4036 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4037 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4038 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004039 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004040 break;
4041 }
4042 case AINPUT_EVENT_TYPE_MOTION: {
4043 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4044 VerifiedMotionEvent verifiedMotionEvent =
4045 verifiedMotionEventFromMotionEvent(motionEvent);
4046 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004047 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004048 break;
4049 }
4050 default: {
4051 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4052 return nullptr;
4053 }
4054 }
4055 if (calculatedHmac == INVALID_HMAC) {
4056 return nullptr;
4057 }
4058 if (calculatedHmac != event.getHmac()) {
4059 return nullptr;
4060 }
4061 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004062}
4063
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 return injectorUid == 0 ||
4066 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067}
4068
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004070 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004071 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 if (injectionState) {
4073#if DEBUG_INJECTION
4074 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 "injectorPid=%d, injectorUid=%d",
4076 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077#endif
4078
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 // Log the outcome since the injector did not wait for the injection result.
4081 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004082 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 ALOGV("Asynchronous input event injection succeeded.");
4084 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004085 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 ALOGW("Asynchronous input event injection failed.");
4087 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 ALOGW("Asynchronous input event injection permission denied.");
4090 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004091 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 ALOGW("Asynchronous input event injection timed out.");
4093 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004094 case InputEventInjectionResult::PENDING:
4095 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4096 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 }
4099
4100 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004101 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103}
4104
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004105void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4106 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 if (injectionState) {
4108 injectionState->pendingForegroundDispatches += 1;
4109 }
4110}
4111
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004112void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4113 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 if (injectionState) {
4115 injectionState->pendingForegroundDispatches -= 1;
4116
4117 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004118 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 }
4120 }
4121}
4122
Vishnu Nairad321cd2020-08-20 16:40:21 -07004123const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004124 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004125 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4126 auto it = mWindowHandlesByDisplay.find(displayId);
4127 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004128}
4129
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004131 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004132 if (windowHandleToken == nullptr) {
4133 return nullptr;
4134 }
4135
Arthur Hungb92218b2018-08-14 12:00:21 +08004136 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004137 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004138 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004139 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004140 return windowHandle;
4141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004144 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145}
4146
Vishnu Nairad321cd2020-08-20 16:40:21 -07004147sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4148 int displayId) const {
4149 if (windowHandleToken == nullptr) {
4150 return nullptr;
4151 }
4152
4153 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4154 if (windowHandle->getToken() == windowHandleToken) {
4155 return windowHandle;
4156 }
4157 }
4158 return nullptr;
4159}
4160
4161sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4162 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4163 return getWindowHandleLocked(focusedToken, displayId);
4164}
4165
Mady Mellor017bcd12020-06-23 19:12:00 +00004166bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4167 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004168 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004169 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004170 if (handle->getId() == windowHandle->getId() &&
4171 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004172 if (windowHandle->getInfo()->displayId != it.first) {
4173 ALOGE("Found window %s in display %" PRId32
4174 ", but it should belong to display %" PRId32,
4175 windowHandle->getName().c_str(), it.first,
4176 windowHandle->getInfo()->displayId);
4177 }
4178 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181 }
4182 return false;
4183}
4184
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004185bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4186 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4187 const bool noInputChannel =
4188 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4189 if (connection != nullptr && noInputChannel) {
4190 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4191 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4192 return false;
4193 }
4194
4195 if (connection == nullptr) {
4196 if (!noInputChannel) {
4197 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4198 }
4199 return false;
4200 }
4201 if (!connection->responsive) {
4202 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4203 return false;
4204 }
4205 return true;
4206}
4207
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004208std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4209 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004210 size_t count = mInputChannelsByToken.count(token);
4211 if (count == 0) {
4212 return nullptr;
4213 }
4214 return mInputChannelsByToken.at(token);
4215}
4216
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004217void InputDispatcher::updateWindowHandlesForDisplayLocked(
4218 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4219 if (inputWindowHandles.empty()) {
4220 // Remove all handles on a display if there are no windows left.
4221 mWindowHandlesByDisplay.erase(displayId);
4222 return;
4223 }
4224
4225 // Since we compare the pointer of input window handles across window updates, we need
4226 // to make sure the handle object for the same window stays unchanged across updates.
4227 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004228 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004229 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004230 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004231 }
4232
4233 std::vector<sp<InputWindowHandle>> newHandles;
4234 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4235 if (!handle->updateInfo()) {
4236 // handle no longer valid
4237 continue;
4238 }
4239
4240 const InputWindowInfo* info = handle->getInfo();
4241 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4242 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4243 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004244 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4245 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4246 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004247 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004248 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004249 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004250 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004251 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004252 }
4253
4254 if (info->displayId != displayId) {
4255 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4256 handle->getName().c_str(), displayId, info->displayId);
4257 continue;
4258 }
4259
Robert Carredd13602020-04-13 17:24:34 -07004260 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4261 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004262 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004263 oldHandle->updateFrom(handle);
4264 newHandles.push_back(oldHandle);
4265 } else {
4266 newHandles.push_back(handle);
4267 }
4268 }
4269
4270 // Insert or replace
4271 mWindowHandlesByDisplay[displayId] = newHandles;
4272}
4273
Arthur Hung72d8dc32020-03-28 00:48:39 +00004274void InputDispatcher::setInputWindows(
4275 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4276 { // acquire lock
4277 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004278 for (const auto& [displayId, handles] : handlesPerDisplay) {
4279 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004280 }
4281 }
4282 // Wake up poll loop since it may need to make new input dispatching choices.
4283 mLooper->wake();
4284}
4285
Arthur Hungb92218b2018-08-14 12:00:21 +08004286/**
4287 * Called from InputManagerService, update window handle list by displayId that can receive input.
4288 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4289 * If set an empty list, remove all handles from the specific display.
4290 * For focused handle, check if need to change and send a cancel event to previous one.
4291 * For removed handle, check if need to send a cancel event if already in touch.
4292 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004293void InputDispatcher::setInputWindowsLocked(
4294 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004295 if (DEBUG_FOCUS) {
4296 std::string windowList;
4297 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4298 windowList += iwh->getName() + " ";
4299 }
4300 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004303 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4304 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4305 const bool noInputWindow =
4306 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4307 if (noInputWindow && window->getToken() != nullptr) {
4308 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4309 window->getName().c_str());
4310 window->releaseChannel();
4311 }
4312 }
4313
Arthur Hung72d8dc32020-03-28 00:48:39 +00004314 // Copy old handles for release if they are no longer present.
4315 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
Arthur Hung72d8dc32020-03-28 00:48:39 +00004317 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004318
Vishnu Nair958da932020-08-21 17:12:37 -07004319 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4320 if (mLastHoverWindowHandle &&
4321 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4322 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004323 mLastHoverWindowHandle = nullptr;
4324 }
4325
Vishnu Nair958da932020-08-21 17:12:37 -07004326 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4327 if (focusedToken) {
4328 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4329 if (result != FocusResult::OK) {
4330 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4331 }
4332 }
4333
4334 std::optional<FocusRequest> focusRequest =
4335 getOptionalValueByKey(mPendingFocusRequests, displayId);
4336 if (focusRequest) {
4337 // If the window from the pending request is now visible, provide it focus.
4338 FocusResult result = handleFocusRequestLocked(*focusRequest);
4339 if (result != FocusResult::NOT_VISIBLE) {
4340 // Drop the request if we were able to change the focus or we cannot change
4341 // it for another reason.
4342 mPendingFocusRequests.erase(displayId);
4343 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004346 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4347 mTouchStatesByDisplay.find(displayId);
4348 if (stateIt != mTouchStatesByDisplay.end()) {
4349 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004350 for (size_t i = 0; i < state.windows.size();) {
4351 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004352 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004353 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004354 ALOGD("Touched window was removed: %s in display %" PRId32,
4355 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004356 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004357 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004358 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4359 if (touchedInputChannel != nullptr) {
4360 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4361 "touched window was removed");
4362 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004364 state.windows.erase(state.windows.begin() + i);
4365 } else {
4366 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 }
4368 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004369 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004370
Arthur Hung72d8dc32020-03-28 00:48:39 +00004371 // Release information for windows that are no longer present.
4372 // This ensures that unused input channels are released promptly.
4373 // Otherwise, they might stick around until the window handle is destroyed
4374 // which might not happen until the next GC.
4375 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004376 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004377 if (DEBUG_FOCUS) {
4378 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004379 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004380 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004381 // To avoid making too many calls into the compat framework, only
4382 // check for window flags when windows are going away.
4383 // TODO(b/157929241) : delete this. This is only needed temporarily
4384 // in order to gather some data about the flag usage
4385 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4386 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4387 oldWindowHandle->getName().c_str());
4388 if (mCompatService != nullptr) {
4389 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4390 oldWindowHandle->getInfo()->ownerUid);
4391 }
4392 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004393 }
chaviw291d88a2019-02-14 10:33:58 -08004394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395}
4396
4397void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004398 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004399 if (DEBUG_FOCUS) {
4400 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4401 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4402 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004403 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004404 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
Chris Yea209fde2020-07-22 13:54:51 -07004406 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004407 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004408
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004409 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4410 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004411 }
4412
Chris Yea209fde2020-07-22 13:54:51 -07004413 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004414 if (inputApplicationHandle != nullptr) {
4415 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4416 } else {
4417 mFocusedApplicationHandlesByDisplay.erase(displayId);
4418 }
4419
4420 // No matter what the old focused application was, stop waiting on it because it is
4421 // no longer focused.
4422 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 } // release lock
4424
4425 // Wake up poll loop since it may need to make new input dispatching choices.
4426 mLooper->wake();
4427}
4428
Tiger Huang721e26f2018-07-24 22:26:19 +08004429/**
4430 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4431 * the display not specified.
4432 *
4433 * We track any unreleased events for each window. If a window loses the ability to receive the
4434 * released event, we will send a cancel event to it. So when the focused display is changed, we
4435 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4436 * display. The display-specified events won't be affected.
4437 */
4438void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004439 if (DEBUG_FOCUS) {
4440 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4441 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004442 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004443 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004444
4445 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004446 sp<IBinder> oldFocusedWindowToken =
4447 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4448 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004449 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004450 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004451 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 CancelationOptions
4453 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4454 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004455 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004456 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4457 }
4458 }
4459 mFocusedDisplayId = displayId;
4460
Chris Ye3c2d6f52020-08-09 10:39:48 -07004461 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004462 sp<IBinder> newFocusedWindowToken =
4463 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4464 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004465
Vishnu Nairad321cd2020-08-20 16:40:21 -07004466 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004467 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004468 if (!mFocusedWindowTokenByDisplay.empty()) {
4469 ALOGE("But another display has a focused window\n%s",
4470 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004471 }
4472 }
4473 }
4474
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004475 if (DEBUG_FOCUS) {
4476 logDispatchStateLocked();
4477 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004478 } // release lock
4479
4480 // Wake up poll loop since it may need to make new input dispatching choices.
4481 mLooper->wake();
4482}
4483
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004485 if (DEBUG_FOCUS) {
4486 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488
4489 bool changed;
4490 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004491 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492
4493 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4494 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 }
4497
4498 if (mDispatchEnabled && !enabled) {
4499 resetAndDropEverythingLocked("dispatcher is being disabled");
4500 }
4501
4502 mDispatchEnabled = enabled;
4503 mDispatchFrozen = frozen;
4504 changed = true;
4505 } else {
4506 changed = false;
4507 }
4508
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004509 if (DEBUG_FOCUS) {
4510 logDispatchStateLocked();
4511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 } // release lock
4513
4514 if (changed) {
4515 // Wake up poll loop since it may need to make new input dispatching choices.
4516 mLooper->wake();
4517 }
4518}
4519
4520void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004521 if (DEBUG_FOCUS) {
4522 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
4525 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004526 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
4528 if (mInputFilterEnabled == enabled) {
4529 return;
4530 }
4531
4532 mInputFilterEnabled = enabled;
4533 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4534 } // release lock
4535
4536 // Wake up poll loop since there might be work to do to drop everything.
4537 mLooper->wake();
4538}
4539
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004540void InputDispatcher::setInTouchMode(bool inTouchMode) {
4541 std::scoped_lock lock(mLock);
4542 mInTouchMode = inTouchMode;
4543}
4544
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004545void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4546 if (opacity < 0 || opacity > 1) {
4547 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4548 return;
4549 }
4550
4551 std::scoped_lock lock(mLock);
4552 mMaximumObscuringOpacityForTouch = opacity;
4553}
4554
4555void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4556 std::scoped_lock lock(mLock);
4557 mBlockUntrustedTouchesMode = mode;
4558}
4559
chaviwfbe5d9c2018-12-26 12:23:37 -08004560bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4561 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004562 if (DEBUG_FOCUS) {
4563 ALOGD("Trivial transfer to same window.");
4564 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004565 return true;
4566 }
4567
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004569 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
chaviwfbe5d9c2018-12-26 12:23:37 -08004571 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4572 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004573 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004574 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 return false;
4576 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004577 if (DEBUG_FOCUS) {
4578 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4579 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004582 if (DEBUG_FOCUS) {
4583 ALOGD("Cannot transfer focus because windows are on different displays.");
4584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 return false;
4586 }
4587
4588 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004589 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4590 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004591 for (size_t i = 0; i < state.windows.size(); i++) {
4592 const TouchedWindow& touchedWindow = state.windows[i];
4593 if (touchedWindow.windowHandle == fromWindowHandle) {
4594 int32_t oldTargetFlags = touchedWindow.targetFlags;
4595 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004597 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004599 int32_t newTargetFlags = oldTargetFlags &
4600 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4601 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004602 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603
Jeff Brownf086ddb2014-02-11 14:28:48 -08004604 found = true;
4605 goto Found;
4606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 }
4608 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004609 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004611 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004612 if (DEBUG_FOCUS) {
4613 ALOGD("Focus transfer failed because from window did not have focus.");
4614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 return false;
4616 }
4617
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004618 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4619 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004620 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004621 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 CancelationOptions
4623 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4624 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004626 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 }
4628
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004629 if (DEBUG_FOCUS) {
4630 logDispatchStateLocked();
4631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 } // release lock
4633
4634 // Wake up poll loop since it may need to make new input dispatching choices.
4635 mLooper->wake();
4636 return true;
4637}
4638
4639void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004640 if (DEBUG_FOCUS) {
4641 ALOGD("Resetting and dropping all events (%s).", reason);
4642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643
4644 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4645 synthesizeCancelationEventsForAllConnectionsLocked(options);
4646
4647 resetKeyRepeatLocked();
4648 releasePendingEventLocked();
4649 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004650 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004653 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004655 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656}
4657
4658void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004659 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 dumpDispatchStateLocked(dump);
4661
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004662 std::istringstream stream(dump);
4663 std::string line;
4664
4665 while (std::getline(stream, line, '\n')) {
4666 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 }
4668}
4669
Vishnu Nairad321cd2020-08-20 16:40:21 -07004670std::string InputDispatcher::dumpFocusedWindowsLocked() {
4671 if (mFocusedWindowTokenByDisplay.empty()) {
4672 return INDENT "FocusedWindows: <none>\n";
4673 }
4674
4675 std::string dump;
4676 dump += INDENT "FocusedWindows:\n";
4677 for (auto& it : mFocusedWindowTokenByDisplay) {
4678 const int32_t displayId = it.first;
4679 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4680 if (windowHandle) {
4681 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4682 windowHandle->getName().c_str());
4683 } else {
4684 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4685 " has focused token without a window'\n",
4686 displayId);
4687 }
4688 }
4689 return dump;
4690}
4691
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004692std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4693 if (mPendingFocusRequests.empty()) {
4694 return INDENT "mPendingFocusRequests: <none>\n";
4695 }
4696
4697 std::string dump;
4698 dump += INDENT "mPendingFocusRequests:\n";
4699 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4700 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4701 // try to resolve them to actual windows.
4702 std::string windowName = getConnectionNameLocked(focusRequest.token);
4703 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4704 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4705 displayId, windowName.c_str(), focusedWindowName.c_str());
4706 }
4707 return dump;
4708}
4709
Prabir Pradhan99987712020-11-10 18:43:05 -08004710std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4711 std::string dump;
4712
4713 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4714 toString(mFocusedWindowRequestedPointerCapture));
4715
4716 std::string windowName = "None";
4717 if (mWindowTokenWithPointerCapture) {
4718 const sp<InputWindowHandle> captureWindowHandle =
4719 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4720 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4721 : "token has capture without window";
4722 }
4723 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4724
4725 return dump;
4726}
4727
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004728void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004729 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4730 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4731 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004732 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733
Tiger Huang721e26f2018-07-24 22:26:19 +08004734 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4735 dump += StringPrintf(INDENT "FocusedApplications:\n");
4736 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4737 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004738 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004739 const std::chrono::duration timeout =
4740 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004742 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004743 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004746 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004748
Vishnu Nairad321cd2020-08-20 16:40:21 -07004749 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004750 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004751 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004753 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004754 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004755 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4756 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004757 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 state.displayId, toString(state.down), toString(state.split),
4759 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004760 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004761 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004762 for (size_t i = 0; i < state.windows.size(); i++) {
4763 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 dump += StringPrintf(INDENT4
4765 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4766 i, touchedWindow.windowHandle->getName().c_str(),
4767 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004768 }
4769 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004770 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004771 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004772 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004773 dump += INDENT3 "Portal windows:\n";
4774 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004775 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004776 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4777 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004778 }
4779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 }
4781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004782 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
4784
Arthur Hungb92218b2018-08-14 12:00:21 +08004785 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004786 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004787 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004788 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004789 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004790 dump += INDENT2 "Windows:\n";
4791 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004792 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004793 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004795 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004796 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004797 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004798 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004800 "applicationInfo.name=%s, "
4801 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004802 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004803 i, windowInfo->name.c_str(), windowInfo->id,
4804 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004806 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004807 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004808 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004809 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004810 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004811 windowInfo->frameLeft, windowInfo->frameTop,
4812 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004813 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004814 windowInfo->applicationInfo.name.c_str(),
4815 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004816 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004817 dump += StringPrintf(", inputFeatures=%s",
4818 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004819 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004820 "ms, trustedOverlay=%s, hasToken=%s, "
4821 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004823 millis(windowInfo->dispatchingTimeout),
4824 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004825 toString(windowInfo->token != nullptr),
4826 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004827 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004828 }
4829 } else {
4830 dump += INDENT2 "Windows: <none>\n";
4831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 }
4833 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004834 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
4836
Michael Wright3dd60e22019-03-27 22:06:44 +00004837 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004838 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004839 const std::vector<Monitor>& monitors = it.second;
4840 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4841 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 }
4843 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004844 const std::vector<Monitor>& monitors = it.second;
4845 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4846 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004849 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 }
4851
4852 nsecs_t currentTime = now();
4853
4854 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004855 if (!mRecentQueue.empty()) {
4856 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004857 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004858 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004859 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004860 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
4862 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004863 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 }
4865
4866 // Dump event currently being dispatched.
4867 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004868 dump += INDENT "PendingEvent:\n";
4869 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004870 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004871 dump += StringPrintf(", age=%" PRId64 "ms\n",
4872 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004874 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876
4877 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004878 if (!mInboundQueue.empty()) {
4879 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004880 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004881 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004882 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004883 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 }
4885 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004886 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 }
4888
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004889 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004890 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004891 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4892 const KeyReplacement& replacement = pair.first;
4893 int32_t newKeyCode = pair.second;
4894 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004895 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004896 }
4897 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004898 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004899 }
4900
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004901 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004902 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004903 for (const auto& pair : mConnectionsByFd) {
4904 const sp<Connection>& connection = pair.second;
4905 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004907 pair.first, connection->getInputChannelName().c_str(),
4908 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004909 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004911 if (!connection->outboundQueue.empty()) {
4912 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4913 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004914 dump += dumpQueue(connection->outboundQueue, currentTime);
4915
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004917 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 }
4919
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004920 if (!connection->waitQueue.empty()) {
4921 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4922 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004923 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004925 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 }
4927 }
4928 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004929 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 }
4931
4932 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004933 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4934 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004936 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937 }
4938
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004939 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004940 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4941 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4942 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943}
4944
Michael Wright3dd60e22019-03-27 22:06:44 +00004945void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4946 const size_t numMonitors = monitors.size();
4947 for (size_t i = 0; i < numMonitors; i++) {
4948 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004949 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004950 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4951 dump += "\n";
4952 }
4953}
4954
Garfield Tan15601662020-09-22 15:32:38 -07004955base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4956 const std::string& name) {
4957#if DEBUG_CHANNEL_CREATION
4958 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959#endif
4960
Garfield Tan15601662020-09-22 15:32:38 -07004961 std::shared_ptr<InputChannel> serverChannel;
4962 std::unique_ptr<InputChannel> clientChannel;
4963 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4964
4965 if (result) {
4966 return base::Error(result) << "Failed to open input channel pair with name " << name;
4967 }
4968
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004970 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004971 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
Garfield Tan15601662020-09-22 15:32:38 -07004973 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004974 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004975 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4978 } // release lock
4979
4980 // Wake the looper because some connections have changed.
4981 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004982 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983}
4984
Garfield Tan15601662020-09-22 15:32:38 -07004985base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004986 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004987 std::shared_ptr<InputChannel> serverChannel;
4988 std::unique_ptr<InputChannel> clientChannel;
4989 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4990 if (result) {
4991 return base::Error(result) << "Failed to open input channel pair with name " << name;
4992 }
4993
Michael Wright3dd60e22019-03-27 22:06:44 +00004994 { // acquire lock
4995 std::scoped_lock _l(mLock);
4996
4997 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004998 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4999 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005000 }
5001
Garfield Tan15601662020-09-22 15:32:38 -07005002 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00005003
Garfield Tan15601662020-09-22 15:32:38 -07005004 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005005 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005006 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005007
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005008 auto& monitorsByDisplay =
5009 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005010 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005011
5012 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00005013 }
Garfield Tan15601662020-09-22 15:32:38 -07005014
Michael Wright3dd60e22019-03-27 22:06:44 +00005015 // Wake the looper because some connections have changed.
5016 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005017 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005018}
5019
Garfield Tan15601662020-09-22 15:32:38 -07005020status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023
Garfield Tan15601662020-09-22 15:32:38 -07005024 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 if (status) {
5026 return status;
5027 }
5028 } // release lock
5029
5030 // Wake the poll loop because removing the connection may have changed the current
5031 // synchronization state.
5032 mLooper->wake();
5033 return OK;
5034}
5035
Garfield Tan15601662020-09-22 15:32:38 -07005036status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5037 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005038 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005039 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005040 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 return BAD_VALUE;
5042 }
5043
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005044 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005045 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005046
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005048 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049 }
5050
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005051 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052
5053 nsecs_t currentTime = now();
5054 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5055
5056 connection->status = Connection::STATUS_ZOMBIE;
5057 return OK;
5058}
5059
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005060void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5061 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5062 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005063}
5064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005065void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005066 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005067 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005068 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005069 std::vector<Monitor>& monitors = it->second;
5070 const size_t numMonitors = monitors.size();
5071 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005072 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 monitors.erase(monitors.begin() + i);
5074 break;
5075 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005076 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005077 if (monitors.empty()) {
5078 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005079 } else {
5080 ++it;
5081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082 }
5083}
5084
Michael Wright3dd60e22019-03-27 22:06:44 +00005085status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5086 { // acquire lock
5087 std::scoped_lock _l(mLock);
5088 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5089
5090 if (!foundDisplayId) {
5091 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5092 return BAD_VALUE;
5093 }
5094 int32_t displayId = foundDisplayId.value();
5095
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005096 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5097 mTouchStatesByDisplay.find(displayId);
5098 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005099 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5100 return BAD_VALUE;
5101 }
5102
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005103 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005104 std::optional<int32_t> foundDeviceId;
5105 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005106 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005107 foundDeviceId = state.deviceId;
5108 }
5109 }
5110 if (!foundDeviceId || !state.down) {
5111 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005112 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005113 return BAD_VALUE;
5114 }
5115 int32_t deviceId = foundDeviceId.value();
5116
5117 // Send cancel events to all the input channels we're stealing from.
5118 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005119 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005120 options.deviceId = deviceId;
5121 options.displayId = displayId;
5122 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005123 std::shared_ptr<InputChannel> channel =
5124 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005125 if (channel != nullptr) {
5126 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5127 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005128 }
5129 // Then clear the current touch state so we stop dispatching to them as well.
5130 state.filterNonMonitors();
5131 }
5132 return OK;
5133}
5134
Prabir Pradhan99987712020-11-10 18:43:05 -08005135void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5136 { // acquire lock
5137 std::scoped_lock _l(mLock);
5138 if (DEBUG_FOCUS) {
5139 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5140 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5141 windowHandle != nullptr ? windowHandle->getName().c_str()
5142 : "token without window");
5143 }
5144
5145 const sp<IBinder> focusedToken =
5146 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5147 if (focusedToken != windowToken) {
5148 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5149 enabled ? "enable" : "disable");
5150 return;
5151 }
5152
5153 if (enabled == mFocusedWindowRequestedPointerCapture) {
5154 ALOGW("Ignoring request to %s Pointer Capture: "
5155 "window has %s requested pointer capture.",
5156 enabled ? "enable" : "disable", enabled ? "already" : "not");
5157 return;
5158 }
5159
5160 mFocusedWindowRequestedPointerCapture = enabled;
5161 setPointerCaptureLocked(enabled);
5162 } // release lock
5163
5164 // Wake the thread to process command entries.
5165 mLooper->wake();
5166}
5167
Michael Wright3dd60e22019-03-27 22:06:44 +00005168std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5169 const sp<IBinder>& token) {
5170 for (const auto& it : mGestureMonitorsByDisplay) {
5171 const std::vector<Monitor>& monitors = it.second;
5172 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005173 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005174 return it.first;
5175 }
5176 }
5177 }
5178 return std::nullopt;
5179}
5180
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005181std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5182 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5183 if (gesturePid.has_value()) {
5184 return gesturePid;
5185 }
5186 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5187}
5188
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005189sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005190 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005191 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005192 }
5193
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005194 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005195 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005196 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005197 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 }
5199 }
Robert Carr4e670e52018-08-15 13:26:12 -07005200
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005201 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202}
5203
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005204std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5205 sp<Connection> connection = getConnectionLocked(connectionToken);
5206 if (connection == nullptr) {
5207 return "<nullptr>";
5208 }
5209 return connection->getInputChannelName();
5210}
5211
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005212void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005213 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005214 removeByValue(mConnectionsByFd, connection);
5215}
5216
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005217void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5218 const sp<Connection>& connection, uint32_t seq,
5219 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005220 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5221 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 commandEntry->connection = connection;
5223 commandEntry->eventTime = currentTime;
5224 commandEntry->seq = seq;
5225 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005226 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227}
5228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005229void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5230 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005232 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005234 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5235 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005237 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238}
5239
Vishnu Nairad321cd2020-08-20 16:40:21 -07005240void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5241 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005242 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5243 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005244 commandEntry->oldToken = oldToken;
5245 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005246 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005247}
5248
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005249void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5250 if (connection == nullptr) {
5251 LOG_ALWAYS_FATAL("Caller must check for nullness");
5252 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005253 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5254 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005255 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005257 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005258 return;
5259 }
5260 /**
5261 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5262 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5263 * has changed. This could cause newer entries to time out before the already dispatched
5264 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5265 * processes the events linearly. So providing information about the oldest entry seems to be
5266 * most useful.
5267 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005268 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005269 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5270 std::string reason =
5271 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005272 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005273 ns2ms(currentWait),
5274 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005275 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005276 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005277
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005278 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5279
5280 // Stop waking up for events on this connection, it is already unresponsive
5281 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005282}
5283
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005284void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5285 std::string reason =
5286 StringPrintf("%s does not have a focused window", application->getName().c_str());
5287 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005288
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005289 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5290 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5291 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005292 postCommandLocked(std::move(commandEntry));
5293}
5294
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005295void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5296 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5297 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5298 commandEntry->obscuringPackage = obscuringPackage;
5299 postCommandLocked(std::move(commandEntry));
5300}
5301
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005302void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5303 const std::string& reason) {
5304 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5305 updateLastAnrStateLocked(windowLabel, reason);
5306}
5307
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005308void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5309 const std::string& reason) {
5310 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005311 updateLastAnrStateLocked(windowLabel, reason);
5312}
5313
5314void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5315 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005317 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 struct tm tm;
5319 localtime_r(&t, &tm);
5320 char timestr[64];
5321 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005322 mLastAnrState.clear();
5323 mLastAnrState += INDENT "ANR:\n";
5324 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005325 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5326 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005327 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328}
5329
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005330void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 mLock.unlock();
5332
5333 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5334
5335 mLock.lock();
5336}
5337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005338void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 sp<Connection> connection = commandEntry->connection;
5340
5341 if (connection->status != Connection::STATUS_ZOMBIE) {
5342 mLock.unlock();
5343
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005344 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345
5346 mLock.lock();
5347 }
5348}
5349
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005350void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005351 sp<IBinder> oldToken = commandEntry->oldToken;
5352 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005353 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005354 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005355 mLock.lock();
5356}
5357
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005358void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005360
5361 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5362
5363 mLock.lock();
5364}
5365
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005366void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005367 mLock.unlock();
5368
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005369 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370
5371 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005372}
5373
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005374void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005375 mLock.unlock();
5376
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005377 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5378
5379 mLock.lock();
5380}
5381
5382void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5383 mLock.unlock();
5384
5385 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5386
5387 mLock.lock();
5388}
5389
5390void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5391 mLock.unlock();
5392
5393 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005394
5395 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005396}
5397
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005398void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5399 mLock.unlock();
5400
5401 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5402
5403 mLock.lock();
5404}
5405
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5407 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005408 KeyEntry& entry = *(commandEntry->keyEntry);
5409 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
5411 mLock.unlock();
5412
Michael Wright2b3c3302018-03-02 17:19:13 +00005413 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005414 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005415 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005416 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5417 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005418 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420
5421 mLock.lock();
5422
5423 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005424 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005426 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005428 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5429 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431}
5432
chaviwfd6d3512019-03-25 13:23:49 -07005433void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5434 mLock.unlock();
5435 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5436 mLock.lock();
5437}
5438
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005439/**
5440 * Connection is responsive if it has no events in the waitQueue that are older than the
5441 * current time.
5442 */
5443static bool isConnectionResponsive(const Connection& connection) {
5444 const nsecs_t currentTime = now();
5445 for (const DispatchEntry* entry : connection.waitQueue) {
5446 if (entry->timeoutTime < currentTime) {
5447 return false;
5448 }
5449 }
5450 return true;
5451}
5452
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005453void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005455 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005457 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
5459 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005460 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005461 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005462 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005464 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005465 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005466 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005467 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5468 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005469 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005470 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005471
5472 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005473 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005474 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005475 restartEvent =
5476 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005477 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005478 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005479 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5480 handled);
5481 } else {
5482 restartEvent = false;
5483 }
5484
5485 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005486 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005487 // contents of the wait queue to have been drained, so we need to double-check
5488 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005489 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5490 if (dispatchEntryIt != connection->waitQueue.end()) {
5491 dispatchEntry = *dispatchEntryIt;
5492 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005493 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5494 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005495 if (!connection->responsive) {
5496 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005497 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005498 // The connection was unresponsive, and now it's responsive.
5499 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005500 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005501 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005502 traceWaitQueueLength(connection);
5503 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005504 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005505 traceOutboundQueueLength(connection);
5506 } else {
5507 releaseDispatchEntry(dispatchEntry);
5508 }
5509 }
5510
5511 // Start the next dispatch cycle for this connection.
5512 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513}
5514
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005515void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5516 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5517 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5518 monitorUnresponsiveCommand->pid = pid;
5519 monitorUnresponsiveCommand->reason = std::move(reason);
5520 postCommandLocked(std::move(monitorUnresponsiveCommand));
5521}
5522
5523void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5524 std::string reason) {
5525 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5526 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5527 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5528 windowUnresponsiveCommand->reason = std::move(reason);
5529 postCommandLocked(std::move(windowUnresponsiveCommand));
5530}
5531
5532void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5533 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5534 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5535 monitorResponsiveCommand->pid = pid;
5536 postCommandLocked(std::move(monitorResponsiveCommand));
5537}
5538
5539void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5540 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5541 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5542 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5543 postCommandLocked(std::move(windowResponsiveCommand));
5544}
5545
5546/**
5547 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5548 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5549 * command entry to the command queue.
5550 */
5551void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5552 std::string reason) {
5553 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5554 if (connection.monitor) {
5555 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5556 reason.c_str());
5557 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5558 if (!pid.has_value()) {
5559 ALOGE("Could not find unresponsive monitor for connection %s",
5560 connection.inputChannel->getName().c_str());
5561 return;
5562 }
5563 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5564 return;
5565 }
5566 // If not a monitor, must be a window
5567 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5568 reason.c_str());
5569 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5570}
5571
5572/**
5573 * Tell the policy that a connection has become responsive so that it can stop ANR.
5574 */
5575void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5576 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5577 if (connection.monitor) {
5578 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5579 if (!pid.has_value()) {
5580 ALOGE("Could not find responsive monitor for connection %s",
5581 connection.inputChannel->getName().c_str());
5582 return;
5583 }
5584 sendMonitorResponsiveCommandLocked(pid.value());
5585 return;
5586 }
5587 // If not a monitor, must be a window
5588 sendWindowResponsiveCommandLocked(connectionToken);
5589}
5590
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005592 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005593 KeyEntry& keyEntry, bool handled) {
5594 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005595 if (!handled) {
5596 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005597 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005598 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005599 return false;
5600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005602 // Get the fallback key state.
5603 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005604 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005605 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005606 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005607 connection->inputState.removeFallbackKey(originalKeyCode);
5608 }
5609
5610 if (handled || !dispatchEntry->hasForegroundTarget()) {
5611 // If the application handles the original key for which we previously
5612 // generated a fallback or if the window is not a foreground window,
5613 // then cancel the associated fallback key, if any.
5614 if (fallbackKeyCode != -1) {
5615 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005617 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005618 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005619 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005621 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005622 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623
5624 mLock.unlock();
5625
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005626 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005627 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628
5629 mLock.lock();
5630
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005631 // Cancel the fallback key.
5632 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005634 "application handled the original non-fallback key "
5635 "or is no longer a foreground target, "
5636 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 options.keyCode = fallbackKeyCode;
5638 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005640 connection->inputState.removeFallbackKey(originalKeyCode);
5641 }
5642 } else {
5643 // If the application did not handle a non-fallback key, first check
5644 // that we are in a good state to perform unhandled key event processing
5645 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005646 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005647 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005649 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005650 "since this is not an initial down. "
5651 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005652 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005654 return false;
5655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005657 // Dispatch the unhandled key to the policy.
5658#if DEBUG_OUTBOUND_EVENT_DETAILS
5659 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005660 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005661 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005662#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005663 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005664
5665 mLock.unlock();
5666
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005667 bool fallback =
5668 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005669 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005670
5671 mLock.lock();
5672
5673 if (connection->status != Connection::STATUS_NORMAL) {
5674 connection->inputState.removeFallbackKey(originalKeyCode);
5675 return false;
5676 }
5677
5678 // Latch the fallback keycode for this key on an initial down.
5679 // The fallback keycode cannot change at any other point in the lifecycle.
5680 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005682 fallbackKeyCode = event.getKeyCode();
5683 } else {
5684 fallbackKeyCode = AKEYCODE_UNKNOWN;
5685 }
5686 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5687 }
5688
5689 ALOG_ASSERT(fallbackKeyCode != -1);
5690
5691 // Cancel the fallback key if the policy decides not to send it anymore.
5692 // We will continue to dispatch the key to the policy but we will no
5693 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005694 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5695 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005696#if DEBUG_OUTBOUND_EVENT_DETAILS
5697 if (fallback) {
5698 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005699 "as a fallback for %d, but on the DOWN it had requested "
5700 "to send %d instead. Fallback canceled.",
5701 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005702 } else {
5703 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005704 "but on the DOWN it had requested to send %d. "
5705 "Fallback canceled.",
5706 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005707 }
5708#endif
5709
5710 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5711 "canceling fallback, policy no longer desires it");
5712 options.keyCode = fallbackKeyCode;
5713 synthesizeCancelationEventsForConnectionLocked(connection, options);
5714
5715 fallback = false;
5716 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005717 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005718 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005719 }
5720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721
5722#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005723 {
5724 std::string msg;
5725 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5726 connection->inputState.getFallbackKeys();
5727 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005728 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005730 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005731 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005732 }
5733#endif
5734
5735 if (fallback) {
5736 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005737 keyEntry.eventTime = event.getEventTime();
5738 keyEntry.deviceId = event.getDeviceId();
5739 keyEntry.source = event.getSource();
5740 keyEntry.displayId = event.getDisplayId();
5741 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5742 keyEntry.keyCode = fallbackKeyCode;
5743 keyEntry.scanCode = event.getScanCode();
5744 keyEntry.metaState = event.getMetaState();
5745 keyEntry.repeatCount = event.getRepeatCount();
5746 keyEntry.downTime = event.getDownTime();
5747 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005748
5749#if DEBUG_OUTBOUND_EVENT_DETAILS
5750 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005751 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005752 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005753#endif
5754 return true; // restart the event
5755 } else {
5756#if DEBUG_OUTBOUND_EVENT_DETAILS
5757 ALOGD("Unhandled key event: No fallback key.");
5758#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005759
5760 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005761 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763 }
5764 return false;
5765}
5766
5767bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005768 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005769 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 return false;
5771}
5772
5773void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5774 mLock.unlock();
5775
5776 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5777
5778 mLock.lock();
5779}
5780
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005781void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5782 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 // TODO Write some statistics about how long we spend waiting.
5784}
5785
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005786/**
5787 * Report the touch event latency to the statsd server.
5788 * Input events are reported for statistics if:
5789 * - This is a touchscreen event
5790 * - InputFilter is not enabled
5791 * - Event is not injected or synthesized
5792 *
5793 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5794 * from getting aggregated with the "old" data.
5795 */
5796void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5797 REQUIRES(mLock) {
5798 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5799 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5800 if (!reportForStatistics) {
5801 return;
5802 }
5803
5804 if (mTouchStatistics.shouldReport()) {
5805 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5806 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5807 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5808 mTouchStatistics.reset();
5809 }
5810 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5811 mTouchStatistics.addValue(latencyMicros);
5812}
5813
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814void InputDispatcher::traceInboundQueueLengthLocked() {
5815 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005816 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 }
5818}
5819
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005820void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005821 if (ATRACE_ENABLED()) {
5822 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005823 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005824 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 }
5826}
5827
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005828void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829 if (ATRACE_ENABLED()) {
5830 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005831 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005832 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005833 }
5834}
5835
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005836void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005837 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005839 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 dumpDispatchStateLocked(dump);
5841
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005842 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005843 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005844 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 }
5846}
5847
5848void InputDispatcher::monitor() {
5849 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005850 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005852 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853}
5854
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005855/**
5856 * Wake up the dispatcher and wait until it processes all events and commands.
5857 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5858 * this method can be safely called from any thread, as long as you've ensured that
5859 * the work you are interested in completing has already been queued.
5860 */
5861bool InputDispatcher::waitForIdle() {
5862 /**
5863 * Timeout should represent the longest possible time that a device might spend processing
5864 * events and commands.
5865 */
5866 constexpr std::chrono::duration TIMEOUT = 100ms;
5867 std::unique_lock lock(mLock);
5868 mLooper->wake();
5869 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5870 return result == std::cv_status::no_timeout;
5871}
5872
Vishnu Naire798b472020-07-23 13:52:21 -07005873/**
5874 * Sets focus to the window identified by the token. This must be called
5875 * after updating any input window handles.
5876 *
5877 * Params:
5878 * request.token - input channel token used to identify the window that should gain focus.
5879 * request.focusedToken - the token that the caller expects currently to be focused. If the
5880 * specified token does not match the currently focused window, this request will be dropped.
5881 * If the specified focused token matches the currently focused window, the call will succeed.
5882 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5883 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5884 * when requesting the focus change. This determines which request gets
5885 * precedence if there is a focus change request from another source such as pointer down.
5886 */
Vishnu Nair958da932020-08-21 17:12:37 -07005887void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5888 { // acquire lock
5889 std::scoped_lock _l(mLock);
5890
5891 const int32_t displayId = request.displayId;
5892 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5893 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5894 ALOGD_IF(DEBUG_FOCUS,
5895 "setFocusedWindow on display %" PRId32
5896 " ignored, reason: focusedToken is not focused",
5897 displayId);
5898 return;
5899 }
5900
5901 mPendingFocusRequests.erase(displayId);
5902 FocusResult result = handleFocusRequestLocked(request);
5903 if (result == FocusResult::NOT_VISIBLE) {
5904 // The requested window is not currently visible. Wait for the window to become visible
5905 // and then provide it focus. This is to handle situations where a user action triggers
5906 // a new window to appear. We want to be able to queue any key events after the user
5907 // action and deliver it to the newly focused window. In order for this to happen, we
5908 // take focus from the currently focused window so key events can be queued.
5909 ALOGD_IF(DEBUG_FOCUS,
5910 "setFocusedWindow on display %" PRId32
5911 " pending, reason: window is not visible",
5912 displayId);
5913 mPendingFocusRequests[displayId] = request;
5914 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5915 "setFocusedWindow_AwaitingWindowVisibility");
5916 } else if (result != FocusResult::OK) {
5917 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5918 typeToString(result));
5919 }
5920 } // release lock
5921 // Wake up poll loop since it may need to make new input dispatching choices.
5922 mLooper->wake();
5923}
5924
5925InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5926 const FocusRequest& request) {
5927 const int32_t displayId = request.displayId;
5928 const sp<IBinder> newFocusedToken = request.token;
5929 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5930
5931 if (oldFocusedToken == request.token) {
5932 ALOGD_IF(DEBUG_FOCUS,
5933 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5934 displayId);
5935 return FocusResult::OK;
5936 }
5937
5938 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5939 if (result != FocusResult::OK) {
5940 return result;
5941 }
5942
5943 std::string_view reason =
5944 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5945 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5946 return FocusResult::OK;
5947}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005948
Vishnu Nairad321cd2020-08-20 16:40:21 -07005949void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5950 const sp<IBinder>& newFocusedToken, int32_t displayId,
5951 std::string_view reason) {
5952 if (oldFocusedToken) {
5953 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005954 if (focusedInputChannel) {
5955 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5956 "focus left window");
5957 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005958 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005959 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005960 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005961 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005962 if (newFocusedToken) {
5963 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5964 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005965 }
5966
Prabir Pradhan99987712020-11-10 18:43:05 -08005967 // If a window has pointer capture, then it must have focus. We need to ensure that this
5968 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5969 // If the window loses focus before it loses pointer capture, then the window can be in a state
5970 // where it has pointer capture but not focus, violating the contract. Therefore we must
5971 // dispatch the pointer capture event before the focus event. Since focus events are added to
5972 // the front of the queue (above), we add the pointer capture event to the front of the queue
5973 // after the focus events are added. This ensures the pointer capture event ends up at the
5974 // front.
5975 disablePointerCaptureForcedLocked();
5976
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005977 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005978 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005979 }
5980}
Vishnu Nair958da932020-08-21 17:12:37 -07005981
Prabir Pradhan99987712020-11-10 18:43:05 -08005982void InputDispatcher::disablePointerCaptureForcedLocked() {
5983 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5984 return;
5985 }
5986
5987 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5988
5989 if (mFocusedWindowRequestedPointerCapture) {
5990 mFocusedWindowRequestedPointerCapture = false;
5991 setPointerCaptureLocked(false);
5992 }
5993
5994 if (!mWindowTokenWithPointerCapture) {
5995 // No need to send capture changes because no window has capture.
5996 return;
5997 }
5998
5999 if (mPendingEvent != nullptr) {
6000 // Move the pending event to the front of the queue. This will give the chance
6001 // for the pending event to be dropped if it is a captured event.
6002 mInboundQueue.push_front(mPendingEvent);
6003 mPendingEvent = nullptr;
6004 }
6005
6006 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6007 false /* hasCapture */);
6008 mInboundQueue.push_front(std::move(entry));
6009}
6010
Vishnu Nair958da932020-08-21 17:12:37 -07006011/**
6012 * Checks if the window token can be focused on a display. The token can be focused if there is
6013 * at least one window handle that is visible with the same token and all window handles with the
6014 * same token are focusable.
6015 *
6016 * In the case of mirroring, two windows may share the same window token and their visibility
6017 * might be different. Example, the mirrored window can cover the window its mirroring. However,
6018 * we expect the focusability of the windows to match since its hard to reason why one window can
6019 * receive focus events and the other cannot when both are backed by the same input channel.
6020 */
6021InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
6022 int32_t displayId) const {
6023 bool allWindowsAreFocusable = true;
6024 bool visibleWindowFound = false;
6025 bool windowFound = false;
6026 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
6027 if (window->getToken() != token) {
6028 continue;
6029 }
6030 windowFound = true;
6031 if (window->getInfo()->visible) {
6032 // Check if at least a single window is visible.
6033 visibleWindowFound = true;
6034 }
6035 if (!window->getInfo()->focusable) {
6036 // Check if all windows with the window token are focusable.
6037 allWindowsAreFocusable = false;
6038 break;
6039 }
6040 }
6041
6042 if (!windowFound) {
6043 return FocusResult::NO_WINDOW;
6044 }
6045 if (!allWindowsAreFocusable) {
6046 return FocusResult::NOT_FOCUSABLE;
6047 }
6048 if (!visibleWindowFound) {
6049 return FocusResult::NOT_VISIBLE;
6050 }
6051
6052 return FocusResult::OK;
6053}
Prabir Pradhan99987712020-11-10 18:43:05 -08006054
6055void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6056 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6057 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6058 commandEntry->enabled = enabled;
6059 postCommandLocked(std::move(commandEntry));
6060}
6061
6062void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6063 android::inputdispatcher::CommandEntry* commandEntry) {
6064 mLock.unlock();
6065
6066 mPolicy->setPointerCapture(commandEntry->enabled);
6067
6068 mLock.lock();
6069}
6070
Garfield Tane84e6f92019-08-29 17:28:41 -07006071} // namespace android::inputdispatcher