blob: 2f2ce98e18223f3581a286684b5a310659e15bc6 [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
50#include "InputDispatcher.h"
51
Michael Wright2b3c3302018-03-02 17:19:13 +000052#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050054#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070055#include <binder/Binder.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"
74
Michael Wrightd02c5b62014-02-10 15:10:22 -080075#define INDENT " "
76#define INDENT2 " "
77#define INDENT3 " "
78#define INDENT4 " "
79
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080080using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080081using android::os::BlockUntrustedTouchesMode;
82using android::os::InputEventInjectionResult;
83using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080084
Garfield Tane84e6f92019-08-29 17:28:41 -070085namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
87// Default input dispatching timeout if there is no focused application or paused window
88// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050089constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
90 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow for all pending events to be processed when an app switch
93// key is on the way. This is used to preempt input dispatch and drop input events
94// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Amount of time to allow for an event to be dispatched (measured since its eventTime)
98// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// 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 +0000102constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
103
104// Log a warning when an interception call takes longer than this to process.
105constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700107// Additional key latency in case a connection is still processing some motion events.
108// This will help with the case when a user touched a button that opens a new window,
109// and gives us the chance to dispatch the key to this new window.
110constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000113constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
114
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115// Event log tags. See EventLogTags.logtags for reference
116constexpr int LOGTAG_INPUT_INTERACTION = 62000;
117constexpr int LOGTAG_INPUT_FOCUS = 62001;
118
Michael Wrightd02c5b62014-02-10 15:10:22 -0800119static inline nsecs_t now() {
120 return systemTime(SYSTEM_TIME_MONOTONIC);
121}
122
123static inline const char* toString(bool value) {
124 return value ? "true" : "false";
125}
126
127static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
129 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130}
131
132static bool isValidKeyAction(int32_t action) {
133 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 case AKEY_EVENT_ACTION_DOWN:
135 case AKEY_EVENT_ACTION_UP:
136 return true;
137 default:
138 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 }
140}
141
142static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 ALOGE("Key event has invalid action code 0x%x", action);
145 return false;
146 }
147 return true;
148}
149
Michael Wright7b159c92015-05-14 14:48:03 +0100150static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700152 case AMOTION_EVENT_ACTION_DOWN:
153 case AMOTION_EVENT_ACTION_UP:
154 case AMOTION_EVENT_ACTION_CANCEL:
155 case AMOTION_EVENT_ACTION_MOVE:
156 case AMOTION_EVENT_ACTION_OUTSIDE:
157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
159 case AMOTION_EVENT_ACTION_HOVER_EXIT:
160 case AMOTION_EVENT_ACTION_SCROLL:
161 return true;
162 case AMOTION_EVENT_ACTION_POINTER_DOWN:
163 case AMOTION_EVENT_ACTION_POINTER_UP: {
164 int32_t index = getMotionEventActionPointerIndex(action);
165 return index >= 0 && index < pointerCount;
166 }
167 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
168 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
169 return actionButton != 0;
170 default:
171 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 }
173}
174
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500175static int64_t millis(std::chrono::nanoseconds t) {
176 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
177}
178
Michael Wright7b159c92015-05-14 14:48:03 +0100179static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 const PointerProperties* pointerProperties) {
181 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 ALOGE("Motion event has invalid action code 0x%x", action);
183 return false;
184 }
185 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000186 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 return false;
189 }
190 BitSet32 pointerIdBits;
191 for (size_t i = 0; i < pointerCount; i++) {
192 int32_t id = pointerProperties[i].id;
193 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
195 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 return false;
197 }
198 if (pointerIdBits.hasBit(id)) {
199 ALOGE("Motion event has duplicate pointer id %d", id);
200 return false;
201 }
202 pointerIdBits.markBit(id);
203 }
204 return true;
205}
206
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000207static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000209 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 }
211
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 bool first = true;
214 Region::const_iterator cur = region.begin();
215 Region::const_iterator const tail = region.end();
216 while (cur != tail) {
217 if (first) {
218 first = false;
219 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 cur++;
224 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000225 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226}
227
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500228static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
229 constexpr size_t maxEntries = 50; // max events to print
230 constexpr size_t skipBegin = maxEntries / 2;
231 const size_t skipEnd = queue.size() - maxEntries / 2;
232 // skip from maxEntries / 2 ... size() - maxEntries/2
233 // only print from 0 .. skipBegin and then from skipEnd .. size()
234
235 std::string dump;
236 for (size_t i = 0; i < queue.size(); i++) {
237 const DispatchEntry& entry = *queue[i];
238 if (i >= skipBegin && i < skipEnd) {
239 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
240 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
241 continue;
242 }
243 dump.append(INDENT4);
244 dump += entry.eventEntry->getDescription();
245 dump += StringPrintf(", seq=%" PRIu32
246 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
247 entry.seq, entry.targetFlags, entry.resolvedAction,
248 ns2ms(currentTime - entry.eventEntry->eventTime));
249 if (entry.deliveryTime != 0) {
250 // This entry was delivered, so add information on how long we've been waiting
251 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
252 }
253 dump.append("\n");
254 }
255 return dump;
256}
257
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700258/**
259 * Find the entry in std::unordered_map by key, and return it.
260 * If the entry is not found, return a default constructed entry.
261 *
262 * Useful when the entries are vectors, since an empty vector will be returned
263 * if the entry is not found.
264 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
265 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700266template <typename K, typename V>
267static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700268 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800270}
271
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272/**
273 * Find the entry in std::unordered_map by value, and remove it.
274 * If more than one entry has the same value, then all matching
275 * key-value pairs will be removed.
276 *
277 * Return true if at least one value has been removed.
278 */
279template <typename K, typename V>
280static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
281 bool removed = false;
282 for (auto it = map.begin(); it != map.end();) {
283 if (it->second == value) {
284 it = map.erase(it);
285 removed = true;
286 } else {
287 it++;
288 }
289 }
290 return removed;
291}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292
Vishnu Nair958da932020-08-21 17:12:37 -0700293/**
294 * Find the entry in std::unordered_map by key and return the value as an optional.
295 */
296template <typename K, typename V>
297static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
298 auto it = map.find(key);
299 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
300}
301
chaviwaf87b3e2019-10-01 16:59:28 -0700302static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
303 if (first == second) {
304 return true;
305 }
306
307 if (first == nullptr || second == nullptr) {
308 return false;
309 }
310
311 return first->getToken() == second->getToken();
312}
313
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800314static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
315 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
316}
317
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000318static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700319 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000320 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700321 if (inputTarget.useDefaultPointerTransform()) {
322 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700323 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700324 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000325 }
326
327 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
328 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700330 std::vector<PointerCoords> pointerCoords;
331 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000332
333 // Use the first pointer information to normalize all other pointers. This could be any pointer
334 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 // uses the transform for the normalized pointer.
336 const ui::Transform& firstPointerTransform =
337 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
338 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000339
340 // Iterate through all pointers in the event to normalize against the first.
341 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
342 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
343 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700344 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 // First, apply the current pointer's transform to update the coordinates into
348 // window space.
349 pointerCoords[pointerIndex].transform(currTransform);
350 // Next, apply the inverse transform of the normalized coordinates so the
351 // current coordinates are transformed into the normalized coordinate space.
352 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000353 }
354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700355 std::unique_ptr<MotionEntry> combinedMotionEntry =
356 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
357 motionEntry.deviceId, motionEntry.source,
358 motionEntry.displayId, motionEntry.policyFlags,
359 motionEntry.action, motionEntry.actionButton,
360 motionEntry.flags, motionEntry.metaState,
361 motionEntry.buttonState, motionEntry.classification,
362 motionEntry.edgeFlags, motionEntry.xPrecision,
363 motionEntry.yPrecision, motionEntry.xCursorPosition,
364 motionEntry.yCursorPosition, motionEntry.downTime,
365 motionEntry.pointerCount, motionEntry.pointerProperties,
366 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 if (motionEntry.injectionState) {
369 combinedMotionEntry->injectionState = motionEntry.injectionState;
370 combinedMotionEntry->injectionState->refCount += 1;
371 }
372
373 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700374 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
375 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376 return dispatchEntry;
377}
378
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700379static void addGestureMonitors(const std::vector<Monitor>& monitors,
380 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
381 float yOffset = 0) {
382 if (monitors.empty()) {
383 return;
384 }
385 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
386 for (const Monitor& monitor : monitors) {
387 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
388 }
389}
390
Garfield Tan15601662020-09-22 15:32:38 -0700391static status_t openInputChannelPair(const std::string& name,
392 std::shared_ptr<InputChannel>& serverChannel,
393 std::unique_ptr<InputChannel>& clientChannel) {
394 std::unique_ptr<InputChannel> uniqueServerChannel;
395 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
396
397 serverChannel = std::move(uniqueServerChannel);
398 return result;
399}
400
Vishnu Nair958da932020-08-21 17:12:37 -0700401const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
402 switch (result) {
403 case InputDispatcher::FocusResult::OK:
404 return "Ok";
405 case InputDispatcher::FocusResult::NO_WINDOW:
406 return "Window not found";
407 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
408 return "Window not focusable";
409 case InputDispatcher::FocusResult::NOT_VISIBLE:
410 return "Window not visible";
411 }
412}
413
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500414template <typename T>
415static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
416 if (lhs == nullptr && rhs == nullptr) {
417 return true;
418 }
419 if (lhs == nullptr || rhs == nullptr) {
420 return false;
421 }
422 return *lhs == *rhs;
423}
424
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425// --- InputDispatcher ---
426
Garfield Tan00f511d2019-06-12 16:55:40 -0700427InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
428 : mPolicy(policy),
429 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700430 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800431 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700432 mAppSwitchSawKeyDown(false),
433 mAppSwitchDueTime(LONG_LONG_MAX),
434 mNextUnblockedEvent(nullptr),
435 mDispatchEnabled(false),
436 mDispatchFrozen(false),
437 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800438 // mInTouchMode will be initialized by the WindowManager to the default device config.
439 // To avoid leaking stack in case that call never comes, and for tests,
440 // initialize it here anyways.
441 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100442 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700443 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800445 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446
Yi Kong9b14ac62018-07-17 13:48:38 -0700447 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
449 policy->getDispatcherConfiguration(&mConfig);
450}
451
452InputDispatcher::~InputDispatcher() {
453 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800454 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 resetKeyRepeatLocked();
457 releasePendingEventLocked();
458 drainInboundQueueLocked();
459 }
460
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700461 while (!mConnectionsByFd.empty()) {
462 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700463 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 }
465}
466
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700467status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700468 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700469 return ALREADY_EXISTS;
470 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700471 mThread = std::make_unique<InputThread>(
472 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
473 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700474}
475
476status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700477 if (mThread && mThread->isCallingThread()) {
478 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700479 return INVALID_OPERATION;
480 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700481 mThread.reset();
482 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700483}
484
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485void InputDispatcher::dispatchOnce() {
486 nsecs_t nextWakeupTime = LONG_LONG_MAX;
487 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800488 std::scoped_lock _l(mLock);
489 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
491 // Run a dispatch loop if there are no pending commands.
492 // The dispatch loop might enqueue commands to run afterwards.
493 if (!haveCommandsLocked()) {
494 dispatchOnceInnerLocked(&nextWakeupTime);
495 }
496
497 // Run all pending commands if there are any.
498 // If any commands were run then force the next poll to wake up immediately.
499 if (runCommandsLockedInterruptible()) {
500 nextWakeupTime = LONG_LONG_MIN;
501 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800502
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700503 // If we are still waiting for ack on some events,
504 // we might have to wake up earlier to check if an app is anr'ing.
505 const nsecs_t nextAnrCheck = processAnrsLocked();
506 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
507
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800508 // We are about to enter an infinitely long sleep, because we have no commands or
509 // pending or queued events
510 if (nextWakeupTime == LONG_LONG_MAX) {
511 mDispatcherEnteredIdle.notify_all();
512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 } // release lock
514
515 // Wait for callback or timeout or wake. (make sure we round up, not down)
516 nsecs_t currentTime = now();
517 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
518 mLooper->pollOnce(timeoutMillis);
519}
520
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700521/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500522 * Raise ANR if there is no focused window.
523 * Before the ANR is raised, do a final state check:
524 * 1. The currently focused application must be the same one we are waiting for.
525 * 2. Ensure we still don't have a focused window.
526 */
527void InputDispatcher::processNoFocusedWindowAnrLocked() {
528 // Check if the application that we are waiting for is still focused.
529 std::shared_ptr<InputApplicationHandle> focusedApplication =
530 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
531 if (focusedApplication == nullptr ||
532 focusedApplication->getApplicationToken() !=
533 mAwaitedFocusedApplication->getApplicationToken()) {
534 // Unexpected because we should have reset the ANR timer when focused application changed
535 ALOGE("Waited for a focused window, but focused application has already changed to %s",
536 focusedApplication->getName().c_str());
537 return; // The focused application has changed.
538 }
539
540 const sp<InputWindowHandle>& focusedWindowHandle =
541 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
542 if (focusedWindowHandle != nullptr) {
543 return; // We now have a focused window. No need for ANR.
544 }
545 onAnrLocked(mAwaitedFocusedApplication);
546}
547
548/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700549 * Check if any of the connections' wait queues have events that are too old.
550 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
551 * Return the time at which we should wake up next.
552 */
553nsecs_t InputDispatcher::processAnrsLocked() {
554 const nsecs_t currentTime = now();
555 nsecs_t nextAnrCheck = LONG_LONG_MAX;
556 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
557 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
558 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500559 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700560 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500561 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700562 return LONG_LONG_MIN;
563 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500564 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700565 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
566 }
567 }
568
569 // Check if any connection ANRs are due
570 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
571 if (currentTime < nextAnrCheck) { // most likely scenario
572 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
573 }
574
575 // If we reached here, we have an unresponsive connection.
576 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
577 if (connection == nullptr) {
578 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
579 return nextAnrCheck;
580 }
581 connection->responsive = false;
582 // Stop waking up for this unresponsive connection
583 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500584 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700585 return LONG_LONG_MIN;
586}
587
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500588std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700589 sp<InputWindowHandle> window = getWindowHandleLocked(token);
590 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500591 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700592 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500593 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700594}
595
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
597 nsecs_t currentTime = now();
598
Jeff Browndc5992e2014-04-11 01:27:26 -0700599 // Reset the key repeat timer whenever normal dispatch is suspended while the
600 // device is in a non-interactive state. This is to ensure that we abort a key
601 // repeat if the device is just coming out of sleep.
602 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 resetKeyRepeatLocked();
604 }
605
606 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
607 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100608 if (DEBUG_FOCUS) {
609 ALOGD("Dispatch frozen. Waiting some more.");
610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 return;
612 }
613
614 // Optimize latency of app switches.
615 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
616 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
617 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
618 if (mAppSwitchDueTime < *nextWakeupTime) {
619 *nextWakeupTime = mAppSwitchDueTime;
620 }
621
622 // Ready to start a new event.
623 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700624 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700625 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 if (isAppSwitchDue) {
627 // The inbound queue is empty so the app switch key we were waiting
628 // for will never arrive. Stop waiting for it.
629 resetPendingAppSwitchLocked(false);
630 isAppSwitchDue = false;
631 }
632
633 // Synthesize a key repeat if appropriate.
634 if (mKeyRepeatState.lastKeyEntry) {
635 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
636 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
637 } else {
638 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
639 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
640 }
641 }
642 }
643
644 // Nothing to do if there is no pending event.
645 if (!mPendingEvent) {
646 return;
647 }
648 } else {
649 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700650 mPendingEvent = mInboundQueue.front();
651 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 traceInboundQueueLengthLocked();
653 }
654
655 // Poke user activity for this event.
656 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700657 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 }
660
661 // Now we have an event to dispatch.
662 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700663 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700669 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
671
672 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700673 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675
676 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700677 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700678 const ConfigurationChangedEntry& typedEntry =
679 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700681 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700682 break;
683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700685 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700686 const DeviceResetEntry& typedEntry =
687 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700688 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700689 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700690 break;
691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100693 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700694 std::shared_ptr<FocusEntry> typedEntry =
695 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100696 dispatchFocusLocked(currentTime, typedEntry);
697 done = true;
698 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
699 break;
700 }
701
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700702 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700703 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700704 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700705 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700706 resetPendingAppSwitchLocked(true);
707 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700708 } else if (dropReason == DropReason::NOT_DROPPED) {
709 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700710 }
711 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700712 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700713 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700714 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700715 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
716 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700717 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700718 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700719 break;
720 }
721
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700722 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700723 std::shared_ptr<MotionEntry> motionEntry =
724 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700725 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
726 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700728 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700729 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700730 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700731 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
732 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700734 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700735 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
738
739 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700740 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700741 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 }
Michael Wright3a981722015-06-10 15:26:13 +0100743 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744
745 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 }
748}
749
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700750/**
751 * Return true if the events preceding this incoming motion event should be dropped
752 * Return false otherwise (the default behaviour)
753 */
754bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700755 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700756 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700757
758 // Optimize case where the current application is unresponsive and the user
759 // decides to touch a window in a different application.
760 // If the application takes too long to catch up then we drop all events preceding
761 // the touch into the other window.
762 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700763 int32_t displayId = motionEntry.displayId;
764 int32_t x = static_cast<int32_t>(
765 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
766 int32_t y = static_cast<int32_t>(
767 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
768 sp<InputWindowHandle> touchedWindowHandle =
769 findTouchedWindowAtLocked(displayId, x, y, nullptr);
770 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700771 touchedWindowHandle->getApplicationToken() !=
772 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700773 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700774 ALOGI("Pruning input queue because user touched a different application while waiting "
775 "for %s",
776 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700777 return true;
778 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700779
780 // Alternatively, maybe there's a gesture monitor that could handle this event
781 std::vector<TouchedMonitor> gestureMonitors =
782 findTouchedGestureMonitorsLocked(displayId, {});
783 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
784 sp<Connection> connection =
785 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000786 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700787 // This monitor could take more input. Drop all events preceding this
788 // event, so that gesture monitor could get a chance to receive the stream
789 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
790 "responsive gesture monitor that may handle the event",
791 mAwaitedFocusedApplication->getName().c_str());
792 return true;
793 }
794 }
795 }
796
797 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
798 // yet been processed by some connections, the dispatcher will wait for these motion
799 // events to be processed before dispatching the key event. This is because these motion events
800 // may cause a new window to be launched, which the user might expect to receive focus.
801 // To prevent waiting forever for such events, just send the key to the currently focused window
802 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
803 ALOGD("Received a new pointer down event, stop waiting for events to process and "
804 "just send the pending key event to the focused window.");
805 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700806 }
807 return false;
808}
809
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700810bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700811 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700812 mInboundQueue.push_back(std::move(newEntry));
813 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 traceInboundQueueLengthLocked();
815
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700817 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 // Optimize app switch latency.
819 // If the application takes too long to catch up then we drop all events preceding
820 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700821 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700823 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700825 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700830 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 mAppSwitchSawKeyDown = false;
832 needWake = true;
833 }
834 }
835 }
836 break;
837 }
838
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700839 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700840 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
841 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700842 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100846 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700847 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
848 break;
849 }
850 case EventEntry::Type::CONFIGURATION_CHANGED:
851 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700852 // nothing to do
853 break;
854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 }
856
857 return needWake;
858}
859
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700860void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700861 mRecentQueue.push_back(entry);
862 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700863 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 }
865}
866
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700868 int32_t y, TouchState* touchState,
869 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700871 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
872 LOG_ALWAYS_FATAL(
873 "Must provide a valid touch state if adding portal windows or outside targets");
874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700876 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800877 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 const InputWindowInfo* windowInfo = windowHandle->getInfo();
879 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100880 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881
882 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100883 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
884 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
885 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800887 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 if (portalToDisplayId != ADISPLAY_ID_NONE &&
889 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800890 if (addPortalWindows) {
891 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700892 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800893 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700894 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 // Found window.
898 return windowHandle;
899 }
900 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800901
Michael Wright44753b12020-07-08 13:48:11 +0100902 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700903 touchState->addOrUpdateWindow(windowHandle,
904 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
905 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
909 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700910 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911}
912
Garfield Tane84e6f92019-08-29 17:28:41 -0700913std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700914 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000915 std::vector<TouchedMonitor> touchedMonitors;
916
917 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
918 addGestureMonitors(monitors, touchedMonitors);
919 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
920 const InputWindowInfo* windowInfo = portalWindow->getInfo();
921 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
923 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000924 }
925 return touchedMonitors;
926}
927
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700928void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 const char* reason;
930 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700931 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 reason = "inbound event was dropped because the policy consumed it";
936 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700937 case DropReason::DISABLED:
938 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 ALOGI("Dropped event because input dispatch is disabled.");
940 }
941 reason = "inbound event was dropped because input dispatch is disabled";
942 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700943 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 ALOGI("Dropped event because of pending overdue app switch.");
945 reason = "inbound event was dropped because of pending overdue app switch";
946 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700947 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 ALOGI("Dropped event because the current application is not responding and the user "
949 "has started interacting with a different application.");
950 reason = "inbound event was dropped because the current application is not responding "
951 "and the user has started interacting with a different application";
952 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 ALOGI("Dropped event because it is stale.");
955 reason = "inbound event was dropped because it is stale";
956 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700957 case DropReason::NOT_DROPPED: {
958 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 }
962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700963 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700964 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
966 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700969 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700970 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
971 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
973 synthesizeCancelationEventsForAllConnectionsLocked(options);
974 } else {
975 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
976 synthesizeCancelationEventsForAllConnectionsLocked(options);
977 }
978 break;
979 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100980 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700981 case EventEntry::Type::CONFIGURATION_CHANGED:
982 case EventEntry::Type::DEVICE_RESET: {
983 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
984 break;
985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 }
987}
988
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800989static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
991 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992}
993
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700994bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
995 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
996 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
997 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998}
999
1000bool InputDispatcher::isAppSwitchPendingLocked() {
1001 return mAppSwitchDueTime != LONG_LONG_MAX;
1002}
1003
1004void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1005 mAppSwitchDueTime = LONG_LONG_MAX;
1006
1007#if DEBUG_APP_SWITCH
1008 if (handled) {
1009 ALOGD("App switch has arrived.");
1010 } else {
1011 ALOGD("App switch was abandoned.");
1012 }
1013#endif
1014}
1015
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001017 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018}
1019
1020bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001021 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 return false;
1023 }
1024
1025 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001026 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001027 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001029 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030
1031 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001032 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 return true;
1034}
1035
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001036void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1037 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038}
1039
1040void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001041 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001042 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001043 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 releaseInboundEventLocked(entry);
1045 }
1046 traceInboundQueueLengthLocked();
1047}
1048
1049void InputDispatcher::releasePendingEventLocked() {
1050 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001052 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
1054}
1055
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001056void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001058 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059#if DEBUG_DISPATCH_CYCLE
1060 ALOGD("Injected inbound event was dropped.");
1061#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001062 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 }
1064 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001065 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 }
1067 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068}
1069
1070void InputDispatcher::resetKeyRepeatLocked() {
1071 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001072 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074}
1075
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1077 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078
Michael Wright2e732952014-09-24 13:26:59 -07001079 uint32_t policyFlags = entry->policyFlags &
1080 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001082 std::shared_ptr<KeyEntry> newEntry =
1083 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1084 entry->source, entry->displayId, policyFlags, entry->action,
1085 entry->flags, entry->keyCode, entry->scanCode,
1086 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001088 newEntry->syntheticRepeat = true;
1089 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001091 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092}
1093
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001095 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001097 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098#endif
1099
1100 // Reset key repeating in case a keyboard device was added or removed or something.
1101 resetKeyRepeatLocked();
1102
1103 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001104 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1105 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001106 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001107 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 return true;
1109}
1110
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001111bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1112 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001114 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1115 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116#endif
1117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001119 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 synthesizeCancelationEventsForAllConnectionsLocked(options);
1121 return true;
1122}
1123
Vishnu Nairad321cd2020-08-20 16:40:21 -07001124void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001125 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001126 if (mPendingEvent != nullptr) {
1127 // Move the pending event to the front of the queue. This will give the chance
1128 // for the pending event to get dispatched to the newly focused window
1129 mInboundQueue.push_front(mPendingEvent);
1130 mPendingEvent = nullptr;
1131 }
1132
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001133 std::unique_ptr<FocusEntry> focusEntry =
1134 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1135 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001136
1137 // This event should go to the front of the queue, but behind all other focus events
1138 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001139 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001140 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001141 [](const std::shared_ptr<EventEntry>& event) {
1142 return event->type == EventEntry::Type::FOCUS;
1143 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001144
1145 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001147}
1148
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001149void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001150 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001151 if (channel == nullptr) {
1152 return; // Window has gone away
1153 }
1154 InputTarget target;
1155 target.inputChannel = channel;
1156 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1157 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001158 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1159 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001160 std::string reason = std::string("reason=").append(entry->reason);
1161 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001162 dispatchEventLocked(currentTime, entry, {target});
1163}
1164
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001165bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 if (!entry->dispatchInProgress) {
1169 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1170 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1171 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1172 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001173 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 // We have seen two identical key downs in a row which indicates that the device
1175 // driver is automatically generating key repeats itself. We take note of the
1176 // repeat here, but we disable our own next key repeat timer since it is clear that
1177 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001178 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1179 // Make sure we don't get key down from a different device. If a different
1180 // device Id has same key pressed down, the new device Id will replace the
1181 // current one to hold the key repeat with repeat count reset.
1182 // In the future when got a KEY_UP on the device id, drop it and do not
1183 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1185 resetKeyRepeatLocked();
1186 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1187 } else {
1188 // Not a repeat. Save key down state in case we do see a repeat later.
1189 resetKeyRepeatLocked();
1190 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1191 }
1192 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001193 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1194 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001196#if DEBUG_INBOUND_EVENT_DETAILS
1197 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1198#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 resetKeyRepeatLocked();
1201 }
1202
1203 if (entry->repeatCount == 1) {
1204 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1205 } else {
1206 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1207 }
1208
1209 entry->dispatchInProgress = true;
1210
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 }
1213
1214 // Handle case where the policy asked us to try again later last time.
1215 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1216 if (currentTime < entry->interceptKeyWakeupTime) {
1217 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1218 *nextWakeupTime = entry->interceptKeyWakeupTime;
1219 }
1220 return false; // wait until next wakeup
1221 }
1222 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1223 entry->interceptKeyWakeupTime = 0;
1224 }
1225
1226 // Give the policy a chance to intercept the key.
1227 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1228 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001229 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001230 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001231 sp<IBinder> focusedWindowToken =
1232 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1233 if (focusedWindowToken != nullptr) {
1234 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
1236 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001237 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 return false; // wait for the command to run
1239 } else {
1240 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1241 }
1242 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001243 if (*dropReason == DropReason::NOT_DROPPED) {
1244 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246 }
1247
1248 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001249 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001251 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1252 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001253 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 return true;
1255 }
1256
1257 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001258 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001259 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001261 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 return false;
1263 }
1264
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001266 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 return true;
1268 }
1269
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001270 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001271 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
1273 // Dispatch the key.
1274 dispatchEventLocked(currentTime, entry, inputTargets);
1275 return true;
1276}
1277
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001278void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001280 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1282 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1284 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1285 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286#endif
1287}
1288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001291 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 entry->dispatchInProgress = true;
1295
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001296 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 }
1298
1299 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001300 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001302 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1303 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 return true;
1305 }
1306
1307 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1308
1309 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001310 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311
1312 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001313 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 if (isPointerEvent) {
1315 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001317 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001318 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 } else {
1320 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001324 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 return false;
1326 }
1327
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001328 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001329 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001330 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1331 return true;
1332 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001333 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001334 CancelationOptions::Mode mode(isPointerEvent
1335 ? CancelationOptions::CANCEL_POINTER_EVENTS
1336 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1337 CancelationOptions options(mode, "input event injection failed");
1338 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 return true;
1340 }
1341
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001342 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001343 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001345 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001346 std::unordered_map<int32_t, TouchState>::iterator it =
1347 mTouchStatesByDisplay.find(entry->displayId);
1348 if (it != mTouchStatesByDisplay.end()) {
1349 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001350 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001351 // The event has gone through these portal windows, so we add monitoring targets of
1352 // the corresponding displays as well.
1353 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001354 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001355 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001357 }
1358 }
1359 }
1360 }
1361
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 // Dispatch the motion.
1363 if (conflictingPointerActions) {
1364 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 synthesizeCancelationEventsForAllConnectionsLocked(options);
1367 }
1368 dispatchEventLocked(currentTime, entry, inputTargets);
1369 return true;
1370}
1371
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001372void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001374 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001375 ", policyFlags=0x%x, "
1376 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1377 "metaState=0x%x, buttonState=0x%x,"
1378 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1380 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1381 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001383 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001385 "x=%f, y=%f, pressure=%f, size=%f, "
1386 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1387 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001388 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1389 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1390 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1391 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1392 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1393 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1394 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1395 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1396 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1397 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 }
1399#endif
1400}
1401
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001402void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1403 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001405 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406#if DEBUG_DISPATCH_CYCLE
1407 ALOGD("dispatchEventToCurrentInputTargets");
1408#endif
1409
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001410 updateInteractionTokensLocked(*eventEntry, inputTargets);
1411
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1413
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001414 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001416 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001417 sp<Connection> connection =
1418 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001419 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001420 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001422 if (DEBUG_FOCUS) {
1423 ALOGD("Dropping event delivery to target with channel '%s' because it "
1424 "is no longer registered with the input dispatcher.",
1425 inputTarget.inputChannel->getName().c_str());
1426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428 }
1429}
1430
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001431void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1432 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1433 // If the policy decides to close the app, we will get a channel removal event via
1434 // unregisterInputChannel, and will clean up the connection that way. We are already not
1435 // sending new pointers to the connection when it blocked, but focused events will continue to
1436 // pile up.
1437 ALOGW("Canceling events for %s because it is unresponsive",
1438 connection->inputChannel->getName().c_str());
1439 if (connection->status == Connection::STATUS_NORMAL) {
1440 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1441 "application not responding");
1442 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
1444}
1445
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001446void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001447 if (DEBUG_FOCUS) {
1448 ALOGD("Resetting ANR timeouts.");
1449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450
1451 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001452 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001453 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454}
1455
Tiger Huang721e26f2018-07-24 22:26:19 +08001456/**
1457 * Get the display id that the given event should go to. If this event specifies a valid display id,
1458 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1459 * Focused display is the display that the user most recently interacted with.
1460 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001461int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001462 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001463 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001464 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001465 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1466 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001467 break;
1468 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001469 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001470 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1471 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 break;
1473 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001474 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001475 case EventEntry::Type::CONFIGURATION_CHANGED:
1476 case EventEntry::Type::DEVICE_RESET: {
1477 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 return ADISPLAY_ID_NONE;
1479 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001480 }
1481 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1482}
1483
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001484bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1485 const char* focusedWindowName) {
1486 if (mAnrTracker.empty()) {
1487 // already processed all events that we waited for
1488 mKeyIsWaitingForEventsTimeout = std::nullopt;
1489 return false;
1490 }
1491
1492 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1493 // Start the timer
1494 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1495 "focus to change",
1496 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001497 mKeyIsWaitingForEventsTimeout = currentTime +
1498 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1499 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001500 return true;
1501 }
1502
1503 // We still have pending events, and already started the timer
1504 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1505 return true; // Still waiting
1506 }
1507
1508 // Waited too long, and some connection still hasn't processed all motions
1509 // Just send the key to the focused window
1510 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1511 focusedWindowName);
1512 mKeyIsWaitingForEventsTimeout = std::nullopt;
1513 return false;
1514}
1515
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001516InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1517 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1518 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001519 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520
Tiger Huang721e26f2018-07-24 22:26:19 +08001521 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001522 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001523 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001524 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1525
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 // If there is no currently focused window and no focused application
1527 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001528 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1529 ALOGI("Dropping %s event because there is no focused window or focused application in "
1530 "display %" PRId32 ".",
1531 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001535 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1536 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1537 // start interacting with another application via touch (app switch). This code can be removed
1538 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1539 // an app is expected to have a focused window.
1540 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1541 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1542 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001543 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1544 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1545 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001546 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001547 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001548 ALOGW("Waiting because no window has focus but %s may eventually add a "
1549 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001550 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001551 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001552 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001553 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1554 // Already raised ANR. Drop the event
1555 ALOGE("Dropping %s event because there is no focused window",
1556 EventEntry::typeToString(entry.type));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001558 } else {
1559 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001561 }
1562 }
1563
1564 // we have a valid, non-null focused window
1565 resetNoFocusedWindowTimeoutLocked();
1566
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001568 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001572 if (focusedWindowHandle->getInfo()->paused) {
1573 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001575 }
1576
1577 // If the event is a key event, then we must wait for all previous events to
1578 // complete before delivering it because previous events may have the
1579 // side-effect of transferring focus to a different window and we want to
1580 // ensure that the following keys are sent to the new window.
1581 //
1582 // Suppose the user touches a button in a window then immediately presses "A".
1583 // If the button causes a pop-up window to appear then we want to ensure that
1584 // the "A" key is delivered to the new pop-up window. This is because users
1585 // often anticipate pending UI changes when typing on a keyboard.
1586 // To obtain this behavior, we must serialize key events with respect to all
1587 // prior input events.
1588 if (entry.type == EventEntry::Type::KEY) {
1589 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1590 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594
1595 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001596 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1598 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599
1600 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001601 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602}
1603
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001604/**
1605 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1606 * that are currently unresponsive.
1607 */
1608std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1609 const std::vector<TouchedMonitor>& monitors) const {
1610 std::vector<TouchedMonitor> responsiveMonitors;
1611 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1612 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1613 sp<Connection> connection = getConnectionLocked(
1614 monitor.monitor.inputChannel->getConnectionToken());
1615 if (connection == nullptr) {
1616 ALOGE("Could not find connection for monitor %s",
1617 monitor.monitor.inputChannel->getName().c_str());
1618 return false;
1619 }
1620 if (!connection->responsive) {
1621 ALOGW("Unresponsive monitor %s will not get the new gesture",
1622 connection->inputChannel->getName().c_str());
1623 return false;
1624 }
1625 return true;
1626 });
1627 return responsiveMonitors;
1628}
1629
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001630InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1631 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1632 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001633 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 enum InjectionPermission {
1635 INJECTION_PERMISSION_UNKNOWN,
1636 INJECTION_PERMISSION_GRANTED,
1637 INJECTION_PERMISSION_DENIED
1638 };
1639
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 // For security reasons, we defer updating the touch state until we are sure that
1641 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001642 int32_t displayId = entry.displayId;
1643 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1645
1646 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001647 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001649 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1650 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001652 // Copy current touch state into tempTouchState.
1653 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1654 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001655 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001656 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001657 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1658 mTouchStatesByDisplay.find(displayId);
1659 if (oldStateIt != mTouchStatesByDisplay.end()) {
1660 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001661 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001662 }
1663
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001664 bool isSplit = tempTouchState.split;
1665 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1666 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1667 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1669 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1670 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1671 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1672 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001673 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 bool wrongDevice = false;
1675 if (newGesture) {
1676 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001677 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001678 ALOGI("Dropping event because a pointer for a different device is already down "
1679 "in display %" PRId32,
1680 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001681 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001682 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 switchedDevice = false;
1684 wrongDevice = true;
1685 goto Failed;
1686 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001687 tempTouchState.reset();
1688 tempTouchState.down = down;
1689 tempTouchState.deviceId = entry.deviceId;
1690 tempTouchState.source = entry.source;
1691 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001693 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001694 ALOGI("Dropping move event because a pointer for a different device is already active "
1695 "in display %" PRId32,
1696 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001697 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001698 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001699 switchedDevice = false;
1700 wrongDevice = true;
1701 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 }
1703
1704 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1705 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1706
Garfield Tan00f511d2019-06-12 16:55:40 -07001707 int32_t x;
1708 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001710 // Always dispatch mouse events to cursor position.
1711 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001712 x = int32_t(entry.xCursorPosition);
1713 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001714 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001715 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1716 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001717 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001719 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001720 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1721 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001722
1723 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001724 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001725 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 if (newTouchedWindowHandle != nullptr &&
1729 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001730 // New window supports splitting, but we should never split mouse events.
1731 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 } else if (isSplit) {
1733 // New window does not support splitting but we have already split events.
1734 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001735 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737
1738 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001739 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001741 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001742 }
1743
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001744 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1745 ALOGI("Not sending touch event to %s because it is paused",
1746 newTouchedWindowHandle->getName().c_str());
1747 newTouchedWindowHandle = nullptr;
1748 }
1749
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001750 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001751 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001752 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1753 if (!isResponsive) {
1754 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1756 newTouchedWindowHandle = nullptr;
1757 }
1758 }
1759
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001760 // Drop events that can't be trusted due to occlusion
1761 if (newTouchedWindowHandle != nullptr &&
1762 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1763 TouchOcclusionInfo occlusionInfo =
1764 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001765 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001766 if (DEBUG_TOUCH_OCCLUSION) {
1767 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1768 for (const auto& log : occlusionInfo.debugInfo) {
1769 ALOGD("%s", log.c_str());
1770 }
1771 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001772 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1773 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1774 ALOGW("Dropping untrusted touch event due to %s/%d",
1775 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1776 newTouchedWindowHandle = nullptr;
1777 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001778 }
1779 }
1780
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001781 // Also don't send the new touch event to unresponsive gesture monitors
1782 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1783
Michael Wright3dd60e22019-03-27 22:06:44 +00001784 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1785 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 "(%d, %d) in display %" PRId32 ".",
1787 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001788 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001789 goto Failed;
1790 }
1791
1792 if (newTouchedWindowHandle != nullptr) {
1793 // Set target flags.
1794 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1795 if (isSplit) {
1796 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001798 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1799 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1800 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1801 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1802 }
1803
1804 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001805 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1806 newHoverWindowHandle = nullptr;
1807 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001808 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001809 }
1810
1811 // Update the temporary touch state.
1812 BitSet32 pointerIds;
1813 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001815 pointerIds.markBit(pointerId);
1816 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001817 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 }
1819
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001820 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 } else {
1822 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1823
1824 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001825 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001826 if (DEBUG_FOCUS) {
1827 ALOGD("Dropping event because the pointer is not down or we previously "
1828 "dropped the pointer down event in display %" PRId32,
1829 displayId);
1830 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 goto Failed;
1833 }
1834
1835 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001837 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1839 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
1841 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001842 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001843 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001844 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1845 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001846 if (DEBUG_FOCUS) {
1847 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1848 oldTouchedWindowHandle->getName().c_str(),
1849 newTouchedWindowHandle->getName().c_str(), displayId);
1850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001852 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1853 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1854 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855
1856 // Make a slippery entrance into the new window.
1857 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1858 isSplit = true;
1859 }
1860
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001861 int32_t targetFlags =
1862 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 if (isSplit) {
1864 targetFlags |= InputTarget::FLAG_SPLIT;
1865 }
1866 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1867 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1868 }
1869
1870 BitSet32 pointerIds;
1871 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001872 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001874 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876 }
1877 }
1878
1879 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001880 // Let the previous window know that the hover sequence is over, unless we already did it
1881 // when dispatching it as is to newTouchedWindowHandle.
1882 if (mLastHoverWindowHandle != nullptr &&
1883 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1884 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885#if DEBUG_HOVER
1886 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001887 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001889 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1890 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 }
1892
Garfield Tandf26e862020-07-01 20:18:19 -07001893 // Let the new window know that the hover sequence is starting, unless we already did it
1894 // when dispatching it as is to newTouchedWindowHandle.
1895 if (newHoverWindowHandle != nullptr &&
1896 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1897 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898#if DEBUG_HOVER
1899 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001900 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001902 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1903 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1904 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 }
1906 }
1907
1908 // Check permission to inject into all touched foreground windows and ensure there
1909 // is at least one touched foreground window.
1910 {
1911 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001912 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1914 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001915 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 injectionPermission = INJECTION_PERMISSION_DENIED;
1918 goto Failed;
1919 }
1920 }
1921 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001922 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001923 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001924 ALOGI("Dropping event because there is no touched foreground window in display "
1925 "%" PRId32 " or gesture monitor to receive it.",
1926 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 goto Failed;
1929 }
1930
1931 // Permission granted to injection into all touched foreground windows.
1932 injectionPermission = INJECTION_PERMISSION_GRANTED;
1933 }
1934
1935 // Check whether windows listening for outside touches are owned by the same UID. If it is
1936 // set the policy flag that we will not reveal coordinate information to this window.
1937 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1938 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001939 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001940 if (foregroundWindowHandle) {
1941 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001942 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001943 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1944 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1945 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001946 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1947 InputTarget::FLAG_ZERO_COORDS,
1948 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 }
1951 }
1952 }
1953 }
1954
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 // If this is the first pointer going down and the touched window has a wallpaper
1956 // then also add the touched wallpaper windows so they are locked in for the duration
1957 // of the touch gesture.
1958 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1959 // engine only supports touch events. We would need to add a mechanism similar
1960 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1961 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1962 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001963 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001965 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001966 getWindowHandlesLocked(displayId);
1967 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001970 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001971 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001972 .addOrUpdateWindow(windowHandle,
1973 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1974 InputTarget::
1975 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1976 InputTarget::FLAG_DISPATCH_AS_IS,
1977 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
1979 }
1980 }
1981 }
1982
1983 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001984 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001988 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
1990
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001994 }
1995
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 // Drop the outside or hover touch windows since we will not care about them
1997 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001998 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
2000Failed:
2001 // Check injection permission once and for all.
2002 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002003 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 injectionPermission = INJECTION_PERMISSION_GRANTED;
2005 } else {
2006 injectionPermission = INJECTION_PERMISSION_DENIED;
2007 }
2008 }
2009
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002010 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2011 return injectionResult;
2012 }
2013
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002015 if (!wrongDevice) {
2016 if (switchedDevice) {
2017 if (DEBUG_FOCUS) {
2018 ALOGD("Conflicting pointer actions: Switched to a different device.");
2019 }
2020 *outConflictingPointerActions = true;
2021 }
2022
2023 if (isHoverAction) {
2024 // Started hovering, therefore no longer down.
2025 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002026 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002027 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2028 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 *outConflictingPointerActions = true;
2031 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002032 tempTouchState.reset();
2033 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2034 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2035 tempTouchState.deviceId = entry.deviceId;
2036 tempTouchState.source = entry.source;
2037 tempTouchState.displayId = displayId;
2038 }
2039 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2040 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2041 // All pointers up or canceled.
2042 tempTouchState.reset();
2043 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2044 // First pointer went down.
2045 if (oldState && oldState->down) {
2046 if (DEBUG_FOCUS) {
2047 ALOGD("Conflicting pointer actions: Down received while already down.");
2048 }
2049 *outConflictingPointerActions = true;
2050 }
2051 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2052 // One pointer went up.
2053 if (isSplit) {
2054 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2055 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002057 for (size_t i = 0; i < tempTouchState.windows.size();) {
2058 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2059 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2060 touchedWindow.pointerIds.clearBit(pointerId);
2061 if (touchedWindow.pointerIds.isEmpty()) {
2062 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2063 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002066 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002068 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002069 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002070
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002071 // Save changes unless the action was scroll in which case the temporary touch
2072 // state was only valid for this one action.
2073 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2074 if (tempTouchState.displayId >= 0) {
2075 mTouchStatesByDisplay[displayId] = tempTouchState;
2076 } else {
2077 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002081 // Update hover state.
2082 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 }
2084
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 return injectionResult;
2086}
2087
2088void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 int32_t targetFlags, BitSet32 pointerIds,
2090 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002091 std::vector<InputTarget>::iterator it =
2092 std::find_if(inputTargets.begin(), inputTargets.end(),
2093 [&windowHandle](const InputTarget& inputTarget) {
2094 return inputTarget.inputChannel->getConnectionToken() ==
2095 windowHandle->getToken();
2096 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002097
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002098 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002099
2100 if (it == inputTargets.end()) {
2101 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002102 std::shared_ptr<InputChannel> inputChannel =
2103 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002104 if (inputChannel == nullptr) {
2105 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2106 return;
2107 }
2108 inputTarget.inputChannel = inputChannel;
2109 inputTarget.flags = targetFlags;
2110 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2111 inputTargets.push_back(inputTarget);
2112 it = inputTargets.end() - 1;
2113 }
2114
2115 ALOG_ASSERT(it->flags == targetFlags);
2116 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2117
chaviw1ff3d1e2020-07-01 15:53:47 -07002118 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119}
2120
Michael Wright3dd60e22019-03-27 22:06:44 +00002121void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002122 int32_t displayId, float xOffset,
2123 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002124 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2125 mGlobalMonitorsByDisplay.find(displayId);
2126
2127 if (it != mGlobalMonitorsByDisplay.end()) {
2128 const std::vector<Monitor>& monitors = it->second;
2129 for (const Monitor& monitor : monitors) {
2130 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133}
2134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002135void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2136 float yOffset,
2137 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002138 InputTarget target;
2139 target.inputChannel = monitor.inputChannel;
2140 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002141 ui::Transform t;
2142 t.set(xOffset, yOffset);
2143 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 inputTargets.push_back(target);
2145}
2146
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002148 const InjectionState* injectionState) {
2149 if (injectionState &&
2150 (windowHandle == nullptr ||
2151 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2152 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002153 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002155 "owned by uid %d",
2156 injectionState->injectorPid, injectionState->injectorUid,
2157 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 } else {
2159 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 }
2162 return false;
2163 }
2164 return true;
2165}
2166
Robert Carrc9bf1d32020-04-13 17:21:08 -07002167/**
2168 * Indicate whether one window handle should be considered as obscuring
2169 * another window handle. We only check a few preconditions. Actually
2170 * checking the bounds is left to the caller.
2171 */
2172static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2173 const sp<InputWindowHandle>& otherHandle) {
2174 // Compare by token so cloned layers aren't counted
2175 if (haveSameToken(windowHandle, otherHandle)) {
2176 return false;
2177 }
2178 auto info = windowHandle->getInfo();
2179 auto otherInfo = otherHandle->getInfo();
2180 if (!otherInfo->visible) {
2181 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002182 } else if (otherInfo->alpha == 0 &&
2183 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2184 // Those act as if they were invisible, so we don't need to flag them.
2185 // We do want to potentially flag touchable windows even if they have 0
2186 // opacity, since they can consume touches and alter the effects of the
2187 // user interaction (eg. apps that rely on
2188 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2189 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2190 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002191 } else if (info->ownerUid == otherInfo->ownerUid) {
2192 // If ownerUid is the same we don't generate occlusion events as there
2193 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002194 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002195 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002196 return false;
2197 } else if (otherInfo->displayId != info->displayId) {
2198 return false;
2199 }
2200 return true;
2201}
2202
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002203/**
2204 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2205 * untrusted, one should check:
2206 *
2207 * 1. If result.hasBlockingOcclusion is true.
2208 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2209 * BLOCK_UNTRUSTED.
2210 *
2211 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2212 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2213 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2214 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2215 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2216 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2217 *
2218 * If neither of those is true, then it means the touch can be allowed.
2219 */
2220InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2221 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002222 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2223 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002224 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2225 TouchOcclusionInfo info;
2226 info.hasBlockingOcclusion = false;
2227 info.obscuringOpacity = 0;
2228 info.obscuringUid = -1;
2229 std::map<int32_t, float> opacityByUid;
2230 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2231 if (windowHandle == otherHandle) {
2232 break; // All future windows are below us. Exit early.
2233 }
2234 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2235 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002236 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2237 if (DEBUG_TOUCH_OCCLUSION) {
2238 info.debugInfo.push_back(
2239 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2240 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002241 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2242 // we perform the checks below to see if the touch can be propagated or not based on the
2243 // window's touch occlusion mode
2244 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2245 info.hasBlockingOcclusion = true;
2246 info.obscuringUid = otherInfo->ownerUid;
2247 info.obscuringPackage = otherInfo->packageName;
2248 break;
2249 }
2250 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2251 uint32_t uid = otherInfo->ownerUid;
2252 float opacity =
2253 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2254 // Given windows A and B:
2255 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2256 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2257 opacityByUid[uid] = opacity;
2258 if (opacity > info.obscuringOpacity) {
2259 info.obscuringOpacity = opacity;
2260 info.obscuringUid = uid;
2261 info.obscuringPackage = otherInfo->packageName;
2262 }
2263 }
2264 }
2265 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002266 if (DEBUG_TOUCH_OCCLUSION) {
2267 info.debugInfo.push_back(
2268 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2269 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002270 return info;
2271}
2272
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002273std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2274 bool isTouchedWindow) const {
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002275 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", mode=%s, alpha=%.2f, "
2276 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2277 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2278 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002279 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002280 NamedEnum::string(info->type, "%" PRId32).c_str(),
2281 info->packageName.c_str(), info->ownerUid,
2282 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2283 info->frameTop, info->frameRight, info->frameBottom,
2284 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002285 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2286 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002287}
2288
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002289bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2290 if (occlusionInfo.hasBlockingOcclusion) {
2291 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2292 occlusionInfo.obscuringUid);
2293 return false;
2294 }
2295 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2296 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2297 "%.2f, maximum allowed = %.2f)",
2298 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2299 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2300 return false;
2301 }
2302 return true;
2303}
2304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002305bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2306 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002308 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002309 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002310 if (windowHandle == otherHandle) {
2311 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002314 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002315 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 return true;
2317 }
2318 }
2319 return false;
2320}
2321
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002322bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2323 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002324 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002325 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002326 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002327 if (windowHandle == otherHandle) {
2328 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002329 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002330 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002331 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002332 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002333 return true;
2334 }
2335 }
2336 return false;
2337}
2338
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002339std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002340 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002342 if (applicationHandle != nullptr) {
2343 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002344 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 } else {
2346 return applicationHandle->getName();
2347 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002348 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002349 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002351 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353}
2354
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002355void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002356 if (eventEntry.type == EventEntry::Type::FOCUS) {
2357 // Focus events are passed to apps, but do not represent user activity.
2358 return;
2359 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002360 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002361 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002362 if (focusedWindowHandle != nullptr) {
2363 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002364 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002366 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367#endif
2368 return;
2369 }
2370 }
2371
2372 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002373 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002374 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002375 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2376 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002377 return;
2378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002380 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 eventType = USER_ACTIVITY_EVENT_TOUCH;
2382 }
2383 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002385 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002386 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2387 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 return;
2389 }
2390 eventType = USER_ACTIVITY_EVENT_BUTTON;
2391 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002393 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002394 case EventEntry::Type::CONFIGURATION_CHANGED:
2395 case EventEntry::Type::DEVICE_RESET: {
2396 LOG_ALWAYS_FATAL("%s events are not user activity",
2397 EventEntry::typeToString(eventEntry.type));
2398 break;
2399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 }
2401
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002402 std::unique_ptr<CommandEntry> commandEntry =
2403 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002404 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002406 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407}
2408
2409void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002410 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002411 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002413 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002415 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002416 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002417 ATRACE_NAME(message.c_str());
2418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419#if DEBUG_DISPATCH_CYCLE
2420 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002421 "globalScaleFactor=%f, pointerIds=0x%x %s",
2422 connection->getInputChannelName().c_str(), inputTarget.flags,
2423 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2424 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425#endif
2426
2427 // Skip this event if the connection status is not normal.
2428 // We don't want to enqueue additional outbound events if the connection is broken.
2429 if (connection->status != Connection::STATUS_NORMAL) {
2430#if DEBUG_DISPATCH_CYCLE
2431 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433#endif
2434 return;
2435 }
2436
2437 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002438 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2439 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2440 "Entry type %s should not have FLAG_SPLIT",
2441 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002443 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002444 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002445 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002446 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 if (!splitMotionEntry) {
2448 return; // split event was dropped
2449 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002450 if (DEBUG_FOCUS) {
2451 ALOGD("channel '%s' ~ Split motion event.",
2452 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002453 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002454 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002455 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2456 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 return;
2458 }
2459 }
2460
2461 // Not splitting. Enqueue dispatch entries for the event as is.
2462 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2463}
2464
2465void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002466 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002467 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002468 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002469 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002470 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002471 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002472 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002473 ATRACE_NAME(message.c_str());
2474 }
2475
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002476 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477
2478 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002479 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002480 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002481 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002483 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002484 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002485 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002487 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002489 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491
2492 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002493 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 startDispatchCycleLocked(currentTime, connection);
2495 }
2496}
2497
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002499 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002500 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002501 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002502 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002503 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2504 connection->getInputChannelName().c_str(),
2505 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002506 ATRACE_NAME(message.c_str());
2507 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002508 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 if (!(inputTargetFlags & dispatchMode)) {
2510 return;
2511 }
2512 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2513
2514 // This is a new event.
2515 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002516 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002517 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002519 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2520 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002521 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002523 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002524 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002525 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002526 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002527 dispatchEntry->resolvedAction = keyEntry.action;
2528 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2531 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2534 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536 return; // skip the inconsistent event
2537 }
2538 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002541 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002542 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002543 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2544 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2545 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2546 static_cast<int32_t>(IdGenerator::Source::OTHER);
2547 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002548 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2549 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2550 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2551 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2552 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2553 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2554 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2555 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2556 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2557 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2558 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002559 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002560 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 }
2562 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002563 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2564 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2567 "event",
2568 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002573 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2575 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2576 }
2577 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2578 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2582 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2585 "event",
2586 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 return; // skip the inconsistent event
2589 }
2590
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002591 dispatchEntry->resolvedEventId =
2592 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2593 ? mIdGenerator.nextId()
2594 : motionEntry.id;
2595 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2596 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2597 ") to MotionEvent(id=0x%" PRIx32 ").",
2598 motionEntry.id, dispatchEntry->resolvedEventId);
2599 ATRACE_NAME(message.c_str());
2600 }
2601
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002602 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002603 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002604
2605 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002607 case EventEntry::Type::FOCUS: {
2608 break;
2609 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002610 case EventEntry::Type::CONFIGURATION_CHANGED:
2611 case EventEntry::Type::DEVICE_RESET: {
2612 LOG_ALWAYS_FATAL("%s events should not go to apps",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002613 EventEntry::typeToString(newEntry.type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002614 break;
2615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 }
2617
2618 // Remember that we are waiting for this dispatch to complete.
2619 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002620 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
2622
2623 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002624 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002625 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002626}
2627
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002628/**
2629 * This function is purely for debugging. It helps us understand where the user interaction
2630 * was taking place. For example, if user is touching launcher, we will see a log that user
2631 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2632 * We will see both launcher and wallpaper in that list.
2633 * Once the interaction with a particular set of connections starts, no new logs will be printed
2634 * until the set of interacted connections changes.
2635 *
2636 * The following items are skipped, to reduce the logspam:
2637 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2638 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2639 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2640 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2641 * Both of those ACTION_UP events would not be logged
2642 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2643 * will not be logged. This is omitted to reduce the amount of data printed.
2644 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2645 * gesture monitor is the only connection receiving the remainder of the gesture.
2646 */
2647void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2648 const std::vector<InputTarget>& targets) {
2649 // Skip ACTION_UP events, and all events other than keys and motions
2650 if (entry.type == EventEntry::Type::KEY) {
2651 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2652 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2653 return;
2654 }
2655 } else if (entry.type == EventEntry::Type::MOTION) {
2656 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2657 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2658 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2659 return;
2660 }
2661 } else {
2662 return; // Not a key or a motion
2663 }
2664
2665 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2666 std::vector<sp<Connection>> newConnections;
2667 for (const InputTarget& target : targets) {
2668 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2669 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2670 continue; // Skip windows that receive ACTION_OUTSIDE
2671 }
2672
2673 sp<IBinder> token = target.inputChannel->getConnectionToken();
2674 sp<Connection> connection = getConnectionLocked(token);
2675 if (connection == nullptr || connection->monitor) {
2676 continue; // We only need to keep track of the non-monitor connections.
2677 }
2678 newConnectionTokens.insert(std::move(token));
2679 newConnections.emplace_back(connection);
2680 }
2681 if (newConnectionTokens == mInteractionConnectionTokens) {
2682 return; // no change
2683 }
2684 mInteractionConnectionTokens = newConnectionTokens;
2685
2686 std::string windowList;
2687 for (const sp<Connection>& connection : newConnections) {
2688 windowList += connection->getWindowName() + ", ";
2689 }
2690 std::string message = "Interaction with windows: " + windowList;
2691 if (windowList.empty()) {
2692 message += "<none>";
2693 }
2694 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2695}
2696
chaviwfd6d3512019-03-25 13:23:49 -07002697void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002698 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002699 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002700 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2701 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002702 return;
2703 }
2704
Vishnu Nairad321cd2020-08-20 16:40:21 -07002705 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2706 if (focusedToken == token) {
2707 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002708 return;
2709 }
2710
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002711 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2712 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002713 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002714 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715}
2716
2717void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002719 if (ATRACE_ENABLED()) {
2720 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002722 ATRACE_NAME(message.c_str());
2723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726#endif
2727
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002728 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2729 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002731 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002732 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002733 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
2735 // Publish the event.
2736 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002737 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2738 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002739 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002740 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2741 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002744 status = connection->inputPublisher
2745 .publishKeyEvent(dispatchEntry->seq,
2746 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2747 keyEntry.source, keyEntry.displayId,
2748 std::move(hmac), dispatchEntry->resolvedAction,
2749 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2750 keyEntry.scanCode, keyEntry.metaState,
2751 keyEntry.repeatCount, keyEntry.downTime,
2752 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754 }
2755
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002756 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002757 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002760 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761
chaviw82357092020-01-28 13:13:06 -08002762 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002763 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2765 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002766 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002767 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2768 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002769 // Don't apply window scale here since we don't want scale to affect raw
2770 // coordinates. The scale will be sent back to the client and applied
2771 // later when requesting relative coordinates.
2772 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2773 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002774 }
2775 usingCoords = scaledCoords;
2776 }
2777 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 // We don't want the dispatch target to know.
2779 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002780 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781 scaledCoords[i].clear();
2782 }
2783 usingCoords = scaledCoords;
2784 }
2785 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002786
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002787 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002788
2789 // Publish the motion event.
2790 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002791 .publishMotionEvent(dispatchEntry->seq,
2792 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002793 motionEntry.deviceId, motionEntry.source,
2794 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002795 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002796 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002797 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002798 motionEntry.edgeFlags, motionEntry.metaState,
2799 motionEntry.buttonState,
2800 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002801 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002802 motionEntry.xPrecision, motionEntry.yPrecision,
2803 motionEntry.xCursorPosition,
2804 motionEntry.yCursorPosition,
2805 motionEntry.downTime, motionEntry.eventTime,
2806 motionEntry.pointerCount,
2807 motionEntry.pointerProperties, usingCoords);
2808 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809 break;
2810 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002811 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002812 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002813 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002814 focusEntry.id,
2815 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002816 mInTouchMode);
2817 break;
2818 }
2819
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002820 case EventEntry::Type::CONFIGURATION_CHANGED:
2821 case EventEntry::Type::DEVICE_RESET: {
2822 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002823 EventEntry::typeToString(eventEntry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 }
2827
2828 // Check the result.
2829 if (status) {
2830 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002831 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002833 "This is unexpected because the wait queue is empty, so the pipe "
2834 "should be empty and we shouldn't have any problems writing an "
2835 "event to it, status=%d",
2836 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2838 } else {
2839 // Pipe is full and we are waiting for the app to finish process some events
2840 // before sending more events to it.
2841#if DEBUG_DISPATCH_CYCLE
2842 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 "waiting for the application to catch up",
2844 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 }
2847 } else {
2848 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 "status=%d",
2850 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2852 }
2853 return;
2854 }
2855
2856 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002857 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2858 connection->outboundQueue.end(),
2859 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002860 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002861 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002862 if (connection->responsive) {
2863 mAnrTracker.insert(dispatchEntry->timeoutTime,
2864 connection->inputChannel->getConnectionToken());
2865 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002866 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
2868}
2869
chaviw09c8d2d2020-08-24 15:48:26 -07002870std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2871 size_t size;
2872 switch (event.type) {
2873 case VerifiedInputEvent::Type::KEY: {
2874 size = sizeof(VerifiedKeyEvent);
2875 break;
2876 }
2877 case VerifiedInputEvent::Type::MOTION: {
2878 size = sizeof(VerifiedMotionEvent);
2879 break;
2880 }
2881 }
2882 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2883 return mHmacKeyManager.sign(start, size);
2884}
2885
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002886const std::array<uint8_t, 32> InputDispatcher::getSignature(
2887 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2888 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2889 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2890 // Only sign events up and down events as the purely move events
2891 // are tied to their up/down counterparts so signing would be redundant.
2892 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2893 verifiedEvent.actionMasked = actionMasked;
2894 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002895 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002896 }
2897 return INVALID_HMAC;
2898}
2899
2900const std::array<uint8_t, 32> InputDispatcher::getSignature(
2901 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2902 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2903 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2904 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002905 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002906}
2907
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 const sp<Connection>& connection, uint32_t seq,
2910 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911#if DEBUG_DISPATCH_CYCLE
2912 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#endif
2915
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 if (connection->status == Connection::STATUS_BROKEN ||
2917 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 return;
2919 }
2920
2921 // Notify other system components and prepare to start the next dispatch cycle.
2922 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2923}
2924
2925void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926 const sp<Connection>& connection,
2927 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928#if DEBUG_DISPATCH_CYCLE
2929 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931#endif
2932
2933 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002934 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002935 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002936 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002937 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938
2939 // The connection appears to be unrecoverably broken.
2940 // Ignore already broken or zombie connections.
2941 if (connection->status == Connection::STATUS_NORMAL) {
2942 connection->status = Connection::STATUS_BROKEN;
2943
2944 if (notify) {
2945 // Notify other system components.
2946 onDispatchCycleBrokenLocked(currentTime, connection);
2947 }
2948 }
2949}
2950
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002951void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2952 while (!queue.empty()) {
2953 DispatchEntry* dispatchEntry = queue.front();
2954 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002955 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 }
2957}
2958
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002959void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002961 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 }
2963 delete dispatchEntry;
2964}
2965
2966int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2967 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2968
2969 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002970 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002972 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 "fd=%d, events=0x%x",
2975 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 return 0; // remove the callback
2977 }
2978
2979 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002980 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2982 if (!(events & ALOOPER_EVENT_INPUT)) {
2983 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 "events=0x%x",
2985 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 return 1;
2987 }
2988
2989 nsecs_t currentTime = now();
2990 bool gotOne = false;
2991 status_t status;
2992 for (;;) {
2993 uint32_t seq;
2994 bool handled;
2995 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2996 if (status) {
2997 break;
2998 }
2999 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3000 gotOne = true;
3001 }
3002 if (gotOne) {
3003 d->runCommandsLockedInterruptible();
3004 if (status == WOULD_BLOCK) {
3005 return 1;
3006 }
3007 }
3008
3009 notify = status != DEAD_OBJECT || !connection->monitor;
3010 if (notify) {
3011 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 }
3014 } else {
3015 // Monitor channels are never explicitly unregistered.
3016 // We do it automatically when the remote endpoint is closed so don't warn
3017 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003018 const bool stillHaveWindowHandle =
3019 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3020 nullptr;
3021 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 if (notify) {
3023 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 "events=0x%x",
3025 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 }
3027 }
3028
Garfield Tan15601662020-09-22 15:32:38 -07003029 // Remove the channel.
3030 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033}
3034
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003037 for (const auto& pair : mConnectionsByFd) {
3038 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 }
3040}
3041
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003043 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003044 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3045 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3046}
3047
3048void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3049 const CancelationOptions& options,
3050 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3051 for (const auto& it : monitorsByDisplay) {
3052 const std::vector<Monitor>& monitors = it.second;
3053 for (const Monitor& monitor : monitors) {
3054 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003055 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003056 }
3057}
3058
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003060 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003061 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003062 if (connection == nullptr) {
3063 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003065
3066 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067}
3068
3069void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3070 const sp<Connection>& connection, const CancelationOptions& options) {
3071 if (connection->status == Connection::STATUS_BROKEN) {
3072 return;
3073 }
3074
3075 nsecs_t currentTime = now();
3076
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003077 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003078 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003080 if (cancelationEvents.empty()) {
3081 return;
3082 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003084 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3085 "with reality: %s, mode=%d.",
3086 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3087 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003089
3090 InputTarget target;
3091 sp<InputWindowHandle> windowHandle =
3092 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3093 if (windowHandle != nullptr) {
3094 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003095 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003096 target.globalScaleFactor = windowInfo->globalScaleFactor;
3097 }
3098 target.inputChannel = connection->inputChannel;
3099 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3100
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003101 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003102 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003103 switch (cancelationEventEntry->type) {
3104 case EventEntry::Type::KEY: {
3105 logOutboundKeyDetails("cancel - ",
3106 static_cast<const KeyEntry&>(*cancelationEventEntry));
3107 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003109 case EventEntry::Type::MOTION: {
3110 logOutboundMotionDetails("cancel - ",
3111 static_cast<const MotionEntry&>(*cancelationEventEntry));
3112 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003114 case EventEntry::Type::FOCUS: {
3115 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
3116 break;
3117 }
3118 case EventEntry::Type::CONFIGURATION_CHANGED:
3119 case EventEntry::Type::DEVICE_RESET: {
3120 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3121 EventEntry::typeToString(cancelationEventEntry->type));
3122 break;
3123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
3125
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3127 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003129
3130 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131}
3132
Svet Ganov5d3bc372020-01-26 23:11:07 -08003133void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3134 const sp<Connection>& connection) {
3135 if (connection->status == Connection::STATUS_BROKEN) {
3136 return;
3137 }
3138
3139 nsecs_t currentTime = now();
3140
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003141 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003142 connection->inputState.synthesizePointerDownEvents(currentTime);
3143
3144 if (downEvents.empty()) {
3145 return;
3146 }
3147
3148#if DEBUG_OUTBOUND_EVENT_DETAILS
3149 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3150 connection->getInputChannelName().c_str(), downEvents.size());
3151#endif
3152
3153 InputTarget target;
3154 sp<InputWindowHandle> windowHandle =
3155 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3156 if (windowHandle != nullptr) {
3157 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003158 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003159 target.globalScaleFactor = windowInfo->globalScaleFactor;
3160 }
3161 target.inputChannel = connection->inputChannel;
3162 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3163
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003165 switch (downEventEntry->type) {
3166 case EventEntry::Type::MOTION: {
3167 logOutboundMotionDetails("down - ",
3168 static_cast<const MotionEntry&>(*downEventEntry));
3169 break;
3170 }
3171
3172 case EventEntry::Type::KEY:
3173 case EventEntry::Type::FOCUS:
3174 case EventEntry::Type::CONFIGURATION_CHANGED:
3175 case EventEntry::Type::DEVICE_RESET: {
3176 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3177 EventEntry::typeToString(downEventEntry->type));
3178 break;
3179 }
3180 }
3181
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003182 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3183 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003184 }
3185
3186 startDispatchCycleLocked(currentTime, connection);
3187}
3188
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003189std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3190 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 ALOG_ASSERT(pointerIds.value != 0);
3192
3193 uint32_t splitPointerIndexMap[MAX_POINTERS];
3194 PointerProperties splitPointerProperties[MAX_POINTERS];
3195 PointerCoords splitPointerCoords[MAX_POINTERS];
3196
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003197 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 uint32_t splitPointerCount = 0;
3199
3200 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003203 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 uint32_t pointerId = uint32_t(pointerProperties.id);
3205 if (pointerIds.hasBit(pointerId)) {
3206 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3207 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3208 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003209 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 splitPointerCount += 1;
3211 }
3212 }
3213
3214 if (splitPointerCount != pointerIds.count()) {
3215 // This is bad. We are missing some of the pointers that we expected to deliver.
3216 // Most likely this indicates that we received an ACTION_MOVE events that has
3217 // different pointer ids than we expected based on the previous ACTION_DOWN
3218 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3219 // in this way.
3220 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 "we expected there to be %d pointers. This probably means we received "
3222 "a broken sequence of pointer ids from the input device.",
3223 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003224 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 }
3226
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003227 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3230 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3232 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003233 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 uint32_t pointerId = uint32_t(pointerProperties.id);
3235 if (pointerIds.hasBit(pointerId)) {
3236 if (pointerIds.count() == 1) {
3237 // The first/last pointer went down/up.
3238 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 ? AMOTION_EVENT_ACTION_DOWN
3240 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 } else {
3242 // A secondary pointer went down/up.
3243 uint32_t splitPointerIndex = 0;
3244 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3245 splitPointerIndex += 1;
3246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 action = maskedAction |
3248 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250 } else {
3251 // An unrelated pointer changed.
3252 action = AMOTION_EVENT_ACTION_MOVE;
3253 }
3254 }
3255
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003256 int32_t newId = mIdGenerator.nextId();
3257 if (ATRACE_ENABLED()) {
3258 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3259 ") to MotionEvent(id=0x%" PRIx32 ").",
3260 originalMotionEntry.id, newId);
3261 ATRACE_NAME(message.c_str());
3262 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003263 std::unique_ptr<MotionEntry> splitMotionEntry =
3264 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3265 originalMotionEntry.deviceId, originalMotionEntry.source,
3266 originalMotionEntry.displayId,
3267 originalMotionEntry.policyFlags, action,
3268 originalMotionEntry.actionButton,
3269 originalMotionEntry.flags, originalMotionEntry.metaState,
3270 originalMotionEntry.buttonState,
3271 originalMotionEntry.classification,
3272 originalMotionEntry.edgeFlags,
3273 originalMotionEntry.xPrecision,
3274 originalMotionEntry.yPrecision,
3275 originalMotionEntry.xCursorPosition,
3276 originalMotionEntry.yCursorPosition,
3277 originalMotionEntry.downTime, splitPointerCount,
3278 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003280 if (originalMotionEntry.injectionState) {
3281 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 splitMotionEntry->injectionState->refCount += 1;
3283 }
3284
3285 return splitMotionEntry;
3286}
3287
3288void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3289#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003290 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291#endif
3292
3293 bool needWake;
3294 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003295 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003297 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3298 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3299 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 } // release lock
3301
3302 if (needWake) {
3303 mLooper->wake();
3304 }
3305}
3306
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003307/**
3308 * If one of the meta shortcuts is detected, process them here:
3309 * Meta + Backspace -> generate BACK
3310 * Meta + Enter -> generate HOME
3311 * This will potentially overwrite keyCode and metaState.
3312 */
3313void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003315 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3316 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3317 if (keyCode == AKEYCODE_DEL) {
3318 newKeyCode = AKEYCODE_BACK;
3319 } else if (keyCode == AKEYCODE_ENTER) {
3320 newKeyCode = AKEYCODE_HOME;
3321 }
3322 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003323 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003324 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003325 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003326 keyCode = newKeyCode;
3327 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3328 }
3329 } else if (action == AKEY_EVENT_ACTION_UP) {
3330 // In order to maintain a consistent stream of up and down events, check to see if the key
3331 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3332 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003333 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003334 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003335 auto replacementIt = mReplacedKeys.find(replacement);
3336 if (replacementIt != mReplacedKeys.end()) {
3337 keyCode = replacementIt->second;
3338 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003339 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3340 }
3341 }
3342}
3343
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3345#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3347 "policyFlags=0x%x, action=0x%x, "
3348 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3349 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3350 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3351 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352#endif
3353 if (!validateKeyEvent(args->action)) {
3354 return;
3355 }
3356
3357 uint32_t policyFlags = args->policyFlags;
3358 int32_t flags = args->flags;
3359 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003360 // InputDispatcher tracks and generates key repeats on behalf of
3361 // whatever notifies it, so repeatCount should always be set to 0
3362 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3364 policyFlags |= POLICY_FLAG_VIRTUAL;
3365 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 if (policyFlags & POLICY_FLAG_FUNCTION) {
3368 metaState |= AMETA_FUNCTION_ON;
3369 }
3370
3371 policyFlags |= POLICY_FLAG_TRUSTED;
3372
Michael Wright78f24442014-08-06 15:55:28 -07003373 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003374 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003375
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003377 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003378 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3379 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
Michael Wright2b3c3302018-03-02 17:19:13 +00003381 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003383 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3384 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 bool needWake;
3389 { // acquire lock
3390 mLock.lock();
3391
3392 if (shouldSendKeyToInputFilterLocked(args)) {
3393 mLock.unlock();
3394
3395 policyFlags |= POLICY_FLAG_FILTERED;
3396 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3397 return; // event was consumed by the filter
3398 }
3399
3400 mLock.lock();
3401 }
3402
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003403 std::unique_ptr<KeyEntry> newEntry =
3404 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3405 args->displayId, policyFlags, args->action, flags,
3406 keyCode, args->scanCode, metaState, repeatCount,
3407 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003409 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 mLock.unlock();
3411 } // release lock
3412
3413 if (needWake) {
3414 mLooper->wake();
3415 }
3416}
3417
3418bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3419 return mInputFilterEnabled;
3420}
3421
3422void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3423#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003424 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3425 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003426 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3427 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003428 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003429 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3430 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3431 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3432 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 for (uint32_t i = 0; i < args->pointerCount; i++) {
3434 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 "x=%f, y=%f, pressure=%f, size=%f, "
3436 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3437 "orientation=%f",
3438 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3439 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3440 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3441 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3442 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3443 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3444 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3445 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3446 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3447 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003450 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3451 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 return;
3453 }
3454
3455 uint32_t policyFlags = args->policyFlags;
3456 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003457
3458 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003459 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003460 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3461 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003462 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464
3465 bool needWake;
3466 { // acquire lock
3467 mLock.lock();
3468
3469 if (shouldSendMotionToInputFilterLocked(args)) {
3470 mLock.unlock();
3471
3472 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003473 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003474 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3475 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003476 args->metaState, args->buttonState, args->classification, transform,
3477 args->xPrecision, args->yPrecision, args->xCursorPosition,
3478 args->yCursorPosition, args->downTime, args->eventTime,
3479 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480
3481 policyFlags |= POLICY_FLAG_FILTERED;
3482 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3483 return; // event was consumed by the filter
3484 }
3485
3486 mLock.lock();
3487 }
3488
3489 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003490 std::unique_ptr<MotionEntry> newEntry =
3491 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3492 args->source, args->displayId, policyFlags,
3493 args->action, args->actionButton, args->flags,
3494 args->metaState, args->buttonState,
3495 args->classification, args->edgeFlags,
3496 args->xPrecision, args->yPrecision,
3497 args->xCursorPosition, args->yCursorPosition,
3498 args->downTime, args->pointerCount,
3499 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 mLock.unlock();
3503 } // release lock
3504
3505 if (needWake) {
3506 mLooper->wake();
3507 }
3508}
3509
3510bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003511 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512}
3513
3514void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3515#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003516 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003517 "switchMask=0x%08x",
3518 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519#endif
3520
3521 uint32_t policyFlags = args->policyFlags;
3522 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003523 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524}
3525
3526void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3527#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003528 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3529 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530#endif
3531
3532 bool needWake;
3533 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003534 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003536 std::unique_ptr<DeviceResetEntry> newEntry =
3537 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3538 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 } // release lock
3540
3541 if (needWake) {
3542 mLooper->wake();
3543 }
3544}
3545
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003546InputEventInjectionResult InputDispatcher::injectInputEvent(
3547 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3548 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549#if DEBUG_INBOUND_EVENT_DETAILS
3550 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003551 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3552 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003554 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555
3556 policyFlags |= POLICY_FLAG_INJECTED;
3557 if (hasInjectionPermission(injectorPid, injectorUid)) {
3558 policyFlags |= POLICY_FLAG_TRUSTED;
3559 }
3560
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003561 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003564 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3565 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003566 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003567 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003570 int32_t flags = incomingKey.getFlags();
3571 int32_t keyCode = incomingKey.getKeyCode();
3572 int32_t metaState = incomingKey.getMetaState();
3573 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003575 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003576 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003577 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3578 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3579 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003581 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3582 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003583 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003584
3585 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3586 android::base::Timer t;
3587 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3588 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3589 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3590 std::to_string(t.duration().count()).c_str());
3591 }
3592 }
3593
3594 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003595 std::unique_ptr<KeyEntry> injectedEntry =
3596 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3597 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3598 incomingKey.getDisplayId(), policyFlags, action,
3599 flags, keyCode, incomingKey.getScanCode(), metaState,
3600 incomingKey.getRepeatCount(),
3601 incomingKey.getDownTime());
3602 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003603 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 case AINPUT_EVENT_TYPE_MOTION: {
3607 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3608 int32_t action = motionEvent->getAction();
3609 size_t pointerCount = motionEvent->getPointerCount();
3610 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3611 int32_t actionButton = motionEvent->getActionButton();
3612 int32_t displayId = motionEvent->getDisplayId();
3613 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003614 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615 }
3616
3617 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3618 nsecs_t eventTime = motionEvent->getEventTime();
3619 android::base::Timer t;
3620 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3621 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3622 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3623 std::to_string(t.duration().count()).c_str());
3624 }
3625 }
3626
3627 mLock.lock();
3628 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3629 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 std::unique_ptr<MotionEntry> injectedEntry =
3631 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3632 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3633 motionEvent->getDisplayId(), policyFlags, action,
3634 actionButton, motionEvent->getFlags(),
3635 motionEvent->getMetaState(),
3636 motionEvent->getButtonState(),
3637 motionEvent->getClassification(),
3638 motionEvent->getEdgeFlags(),
3639 motionEvent->getXPrecision(),
3640 motionEvent->getYPrecision(),
3641 motionEvent->getRawXCursorPosition(),
3642 motionEvent->getRawYCursorPosition(),
3643 motionEvent->getDownTime(),
3644 uint32_t(pointerCount), pointerProperties,
3645 samplePointerCoords, motionEvent->getXOffset(),
3646 motionEvent->getYOffset());
3647 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003648 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3649 sampleEventTimes += 1;
3650 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003651 std::unique_ptr<MotionEntry> nextInjectedEntry =
3652 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3653 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3654 motionEvent->getDisplayId(), policyFlags,
3655 action, actionButton, motionEvent->getFlags(),
3656 motionEvent->getMetaState(),
3657 motionEvent->getButtonState(),
3658 motionEvent->getClassification(),
3659 motionEvent->getEdgeFlags(),
3660 motionEvent->getXPrecision(),
3661 motionEvent->getYPrecision(),
3662 motionEvent->getRawXCursorPosition(),
3663 motionEvent->getRawYCursorPosition(),
3664 motionEvent->getDownTime(),
3665 uint32_t(pointerCount), pointerProperties,
3666 samplePointerCoords,
3667 motionEvent->getXOffset(),
3668 motionEvent->getYOffset());
3669 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670 }
3671 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003674 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003675 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003676 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 }
3678
3679 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003680 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 injectionState->injectionIsAsync = true;
3682 }
3683
3684 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003685 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686
3687 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003688 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003689 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003690 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
3692
3693 mLock.unlock();
3694
3695 if (needWake) {
3696 mLooper->wake();
3697 }
3698
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003699 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003701 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003703 if (syncMode == InputEventInjectionSync::NONE) {
3704 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 } else {
3706 for (;;) {
3707 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003708 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 break;
3710 }
3711
3712 nsecs_t remainingTimeout = endTime - now();
3713 if (remainingTimeout <= 0) {
3714#if DEBUG_INJECTION
3715 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003716 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003718 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 break;
3720 }
3721
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003722 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 }
3724
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003725 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3726 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 while (injectionState->pendingForegroundDispatches != 0) {
3728#if DEBUG_INJECTION
3729 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003730 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731#endif
3732 nsecs_t remainingTimeout = endTime - now();
3733 if (remainingTimeout <= 0) {
3734#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3736 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003738 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 break;
3740 }
3741
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003742 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 }
3744 }
3745 }
3746
3747 injectionState->release();
3748 } // release lock
3749
3750#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003751 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003752 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753#endif
3754
3755 return injectionResult;
3756}
3757
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003758std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003759 std::array<uint8_t, 32> calculatedHmac;
3760 std::unique_ptr<VerifiedInputEvent> result;
3761 switch (event.getType()) {
3762 case AINPUT_EVENT_TYPE_KEY: {
3763 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3764 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3765 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003766 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003767 break;
3768 }
3769 case AINPUT_EVENT_TYPE_MOTION: {
3770 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3771 VerifiedMotionEvent verifiedMotionEvent =
3772 verifiedMotionEventFromMotionEvent(motionEvent);
3773 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003774 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003775 break;
3776 }
3777 default: {
3778 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3779 return nullptr;
3780 }
3781 }
3782 if (calculatedHmac == INVALID_HMAC) {
3783 return nullptr;
3784 }
3785 if (calculatedHmac != event.getHmac()) {
3786 return nullptr;
3787 }
3788 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003789}
3790
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 return injectorUid == 0 ||
3793 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794}
3795
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003796void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003798 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 if (injectionState) {
3800#if DEBUG_INJECTION
3801 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 "injectorPid=%d, injectorUid=%d",
3803 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804#endif
3805
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 // Log the outcome since the injector did not wait for the injection result.
3808 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003809 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810 ALOGV("Asynchronous input event injection succeeded.");
3811 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003812 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 ALOGW("Asynchronous input event injection failed.");
3814 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003815 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003816 ALOGW("Asynchronous input event injection permission denied.");
3817 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003818 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 ALOGW("Asynchronous input event injection timed out.");
3820 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003821 case InputEventInjectionResult::PENDING:
3822 ALOGE("Setting result to 'PENDING' for asynchronous injection");
3823 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
3825 }
3826
3827 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003828 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 }
3830}
3831
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003832void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
3833 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 if (injectionState) {
3835 injectionState->pendingForegroundDispatches += 1;
3836 }
3837}
3838
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003839void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
3840 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 if (injectionState) {
3842 injectionState->pendingForegroundDispatches -= 1;
3843
3844 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003845 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 }
3847 }
3848}
3849
Vishnu Nairad321cd2020-08-20 16:40:21 -07003850const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003851 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003852 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3853 auto it = mWindowHandlesByDisplay.find(displayId);
3854 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003855}
3856
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003858 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003859 if (windowHandleToken == nullptr) {
3860 return nullptr;
3861 }
3862
Arthur Hungb92218b2018-08-14 12:00:21 +08003863 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003864 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003865 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003866 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003867 return windowHandle;
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 }
3870 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003871 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872}
3873
Vishnu Nairad321cd2020-08-20 16:40:21 -07003874sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3875 int displayId) const {
3876 if (windowHandleToken == nullptr) {
3877 return nullptr;
3878 }
3879
3880 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3881 if (windowHandle->getToken() == windowHandleToken) {
3882 return windowHandle;
3883 }
3884 }
3885 return nullptr;
3886}
3887
3888sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3889 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3890 return getWindowHandleLocked(focusedToken, displayId);
3891}
3892
Mady Mellor017bcd12020-06-23 19:12:00 +00003893bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3894 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003895 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003896 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003897 if (handle->getId() == windowHandle->getId() &&
3898 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003899 if (windowHandle->getInfo()->displayId != it.first) {
3900 ALOGE("Found window %s in display %" PRId32
3901 ", but it should belong to display %" PRId32,
3902 windowHandle->getName().c_str(), it.first,
3903 windowHandle->getInfo()->displayId);
3904 }
3905 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 }
3908 }
3909 return false;
3910}
3911
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003912bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3913 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3914 const bool noInputChannel =
3915 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3916 if (connection != nullptr && noInputChannel) {
3917 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3918 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3919 return false;
3920 }
3921
3922 if (connection == nullptr) {
3923 if (!noInputChannel) {
3924 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3925 }
3926 return false;
3927 }
3928 if (!connection->responsive) {
3929 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3930 return false;
3931 }
3932 return true;
3933}
3934
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003935std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3936 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003937 size_t count = mInputChannelsByToken.count(token);
3938 if (count == 0) {
3939 return nullptr;
3940 }
3941 return mInputChannelsByToken.at(token);
3942}
3943
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003944void InputDispatcher::updateWindowHandlesForDisplayLocked(
3945 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3946 if (inputWindowHandles.empty()) {
3947 // Remove all handles on a display if there are no windows left.
3948 mWindowHandlesByDisplay.erase(displayId);
3949 return;
3950 }
3951
3952 // Since we compare the pointer of input window handles across window updates, we need
3953 // to make sure the handle object for the same window stays unchanged across updates.
3954 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003955 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003956 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003957 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003958 }
3959
3960 std::vector<sp<InputWindowHandle>> newHandles;
3961 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3962 if (!handle->updateInfo()) {
3963 // handle no longer valid
3964 continue;
3965 }
3966
3967 const InputWindowInfo* info = handle->getInfo();
3968 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3969 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3970 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003971 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3972 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3973 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003974 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003975 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003976 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003977 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003978 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003979 }
3980
3981 if (info->displayId != displayId) {
3982 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3983 handle->getName().c_str(), displayId, info->displayId);
3984 continue;
3985 }
3986
Robert Carredd13602020-04-13 17:24:34 -07003987 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3988 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003989 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003990 oldHandle->updateFrom(handle);
3991 newHandles.push_back(oldHandle);
3992 } else {
3993 newHandles.push_back(handle);
3994 }
3995 }
3996
3997 // Insert or replace
3998 mWindowHandlesByDisplay[displayId] = newHandles;
3999}
4000
Arthur Hung72d8dc32020-03-28 00:48:39 +00004001void InputDispatcher::setInputWindows(
4002 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4003 { // acquire lock
4004 std::scoped_lock _l(mLock);
4005 for (auto const& i : handlesPerDisplay) {
4006 setInputWindowsLocked(i.second, i.first);
4007 }
4008 }
4009 // Wake up poll loop since it may need to make new input dispatching choices.
4010 mLooper->wake();
4011}
4012
Arthur Hungb92218b2018-08-14 12:00:21 +08004013/**
4014 * Called from InputManagerService, update window handle list by displayId that can receive input.
4015 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4016 * If set an empty list, remove all handles from the specific display.
4017 * For focused handle, check if need to change and send a cancel event to previous one.
4018 * For removed handle, check if need to send a cancel event if already in touch.
4019 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004020void InputDispatcher::setInputWindowsLocked(
4021 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004022 if (DEBUG_FOCUS) {
4023 std::string windowList;
4024 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4025 windowList += iwh->getName() + " ";
4026 }
4027 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004030 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4031 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4032 const bool noInputWindow =
4033 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4034 if (noInputWindow && window->getToken() != nullptr) {
4035 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4036 window->getName().c_str());
4037 window->releaseChannel();
4038 }
4039 }
4040
Arthur Hung72d8dc32020-03-28 00:48:39 +00004041 // Copy old handles for release if they are no longer present.
4042 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043
Arthur Hung72d8dc32020-03-28 00:48:39 +00004044 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004045
Vishnu Nair958da932020-08-21 17:12:37 -07004046 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4047 if (mLastHoverWindowHandle &&
4048 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4049 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004050 mLastHoverWindowHandle = nullptr;
4051 }
4052
Vishnu Nair958da932020-08-21 17:12:37 -07004053 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4054 if (focusedToken) {
4055 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4056 if (result != FocusResult::OK) {
4057 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4058 }
4059 }
4060
4061 std::optional<FocusRequest> focusRequest =
4062 getOptionalValueByKey(mPendingFocusRequests, displayId);
4063 if (focusRequest) {
4064 // If the window from the pending request is now visible, provide it focus.
4065 FocusResult result = handleFocusRequestLocked(*focusRequest);
4066 if (result != FocusResult::NOT_VISIBLE) {
4067 // Drop the request if we were able to change the focus or we cannot change
4068 // it for another reason.
4069 mPendingFocusRequests.erase(displayId);
4070 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004073 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4074 mTouchStatesByDisplay.find(displayId);
4075 if (stateIt != mTouchStatesByDisplay.end()) {
4076 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004077 for (size_t i = 0; i < state.windows.size();) {
4078 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004079 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004080 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004081 ALOGD("Touched window was removed: %s in display %" PRId32,
4082 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004083 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004084 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004085 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4086 if (touchedInputChannel != nullptr) {
4087 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4088 "touched window was removed");
4089 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004091 state.windows.erase(state.windows.begin() + i);
4092 } else {
4093 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 }
4095 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004096 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004097
Arthur Hung72d8dc32020-03-28 00:48:39 +00004098 // Release information for windows that are no longer present.
4099 // This ensures that unused input channels are released promptly.
4100 // Otherwise, they might stick around until the window handle is destroyed
4101 // which might not happen until the next GC.
4102 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004103 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004104 if (DEBUG_FOCUS) {
4105 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004106 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004107 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004108 }
chaviw291d88a2019-02-14 10:33:58 -08004109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110}
4111
4112void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004113 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004114 if (DEBUG_FOCUS) {
4115 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4116 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4117 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004118 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004119 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
Chris Yea209fde2020-07-22 13:54:51 -07004121 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004122 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004123
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004124 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4125 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004126 }
4127
Chris Yea209fde2020-07-22 13:54:51 -07004128 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004129 if (inputApplicationHandle != nullptr) {
4130 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4131 } else {
4132 mFocusedApplicationHandlesByDisplay.erase(displayId);
4133 }
4134
4135 // No matter what the old focused application was, stop waiting on it because it is
4136 // no longer focused.
4137 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 } // release lock
4139
4140 // Wake up poll loop since it may need to make new input dispatching choices.
4141 mLooper->wake();
4142}
4143
Tiger Huang721e26f2018-07-24 22:26:19 +08004144/**
4145 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4146 * the display not specified.
4147 *
4148 * We track any unreleased events for each window. If a window loses the ability to receive the
4149 * released event, we will send a cancel event to it. So when the focused display is changed, we
4150 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4151 * display. The display-specified events won't be affected.
4152 */
4153void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004154 if (DEBUG_FOCUS) {
4155 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4156 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004157 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004158 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004159
4160 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004161 sp<IBinder> oldFocusedWindowToken =
4162 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4163 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004164 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004165 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004166 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 CancelationOptions
4168 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4169 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004170 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004171 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4172 }
4173 }
4174 mFocusedDisplayId = displayId;
4175
Chris Ye3c2d6f52020-08-09 10:39:48 -07004176 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004177 sp<IBinder> newFocusedWindowToken =
4178 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4179 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004180
Vishnu Nairad321cd2020-08-20 16:40:21 -07004181 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004182 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004183 if (!mFocusedWindowTokenByDisplay.empty()) {
4184 ALOGE("But another display has a focused window\n%s",
4185 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004186 }
4187 }
4188 }
4189
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004190 if (DEBUG_FOCUS) {
4191 logDispatchStateLocked();
4192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004193 } // release lock
4194
4195 // Wake up poll loop since it may need to make new input dispatching choices.
4196 mLooper->wake();
4197}
4198
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004200 if (DEBUG_FOCUS) {
4201 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
4204 bool changed;
4205 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004206 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207
4208 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4209 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004210 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 }
4212
4213 if (mDispatchEnabled && !enabled) {
4214 resetAndDropEverythingLocked("dispatcher is being disabled");
4215 }
4216
4217 mDispatchEnabled = enabled;
4218 mDispatchFrozen = frozen;
4219 changed = true;
4220 } else {
4221 changed = false;
4222 }
4223
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004224 if (DEBUG_FOCUS) {
4225 logDispatchStateLocked();
4226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 } // release lock
4228
4229 if (changed) {
4230 // Wake up poll loop since it may need to make new input dispatching choices.
4231 mLooper->wake();
4232 }
4233}
4234
4235void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004236 if (DEBUG_FOCUS) {
4237 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239
4240 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004241 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
4243 if (mInputFilterEnabled == enabled) {
4244 return;
4245 }
4246
4247 mInputFilterEnabled = enabled;
4248 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4249 } // release lock
4250
4251 // Wake up poll loop since there might be work to do to drop everything.
4252 mLooper->wake();
4253}
4254
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004255void InputDispatcher::setInTouchMode(bool inTouchMode) {
4256 std::scoped_lock lock(mLock);
4257 mInTouchMode = inTouchMode;
4258}
4259
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004260void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4261 if (opacity < 0 || opacity > 1) {
4262 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4263 return;
4264 }
4265
4266 std::scoped_lock lock(mLock);
4267 mMaximumObscuringOpacityForTouch = opacity;
4268}
4269
4270void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4271 std::scoped_lock lock(mLock);
4272 mBlockUntrustedTouchesMode = mode;
4273}
4274
chaviwfbe5d9c2018-12-26 12:23:37 -08004275bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4276 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004277 if (DEBUG_FOCUS) {
4278 ALOGD("Trivial transfer to same window.");
4279 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004280 return true;
4281 }
4282
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004284 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
chaviwfbe5d9c2018-12-26 12:23:37 -08004286 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4287 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004288 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004289 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 return false;
4291 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004292 if (DEBUG_FOCUS) {
4293 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4294 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004297 if (DEBUG_FOCUS) {
4298 ALOGD("Cannot transfer focus because windows are on different displays.");
4299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 return false;
4301 }
4302
4303 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004304 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4305 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004306 for (size_t i = 0; i < state.windows.size(); i++) {
4307 const TouchedWindow& touchedWindow = state.windows[i];
4308 if (touchedWindow.windowHandle == fromWindowHandle) {
4309 int32_t oldTargetFlags = touchedWindow.targetFlags;
4310 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004312 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 int32_t newTargetFlags = oldTargetFlags &
4315 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4316 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004317 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
Jeff Brownf086ddb2014-02-11 14:28:48 -08004319 found = true;
4320 goto Found;
4321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
4323 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004326 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004327 if (DEBUG_FOCUS) {
4328 ALOGD("Focus transfer failed because from window did not have focus.");
4329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 return false;
4331 }
4332
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004333 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4334 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004335 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004336 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 CancelationOptions
4338 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4339 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004341 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 }
4343
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004344 if (DEBUG_FOCUS) {
4345 logDispatchStateLocked();
4346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 } // release lock
4348
4349 // Wake up poll loop since it may need to make new input dispatching choices.
4350 mLooper->wake();
4351 return true;
4352}
4353
4354void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004355 if (DEBUG_FOCUS) {
4356 ALOGD("Resetting and dropping all events (%s).", reason);
4357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
4359 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4360 synthesizeCancelationEventsForAllConnectionsLocked(options);
4361
4362 resetKeyRepeatLocked();
4363 releasePendingEventLocked();
4364 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004365 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004367 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004368 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004370 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371}
4372
4373void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004374 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 dumpDispatchStateLocked(dump);
4376
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004377 std::istringstream stream(dump);
4378 std::string line;
4379
4380 while (std::getline(stream, line, '\n')) {
4381 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 }
4383}
4384
Vishnu Nairad321cd2020-08-20 16:40:21 -07004385std::string InputDispatcher::dumpFocusedWindowsLocked() {
4386 if (mFocusedWindowTokenByDisplay.empty()) {
4387 return INDENT "FocusedWindows: <none>\n";
4388 }
4389
4390 std::string dump;
4391 dump += INDENT "FocusedWindows:\n";
4392 for (auto& it : mFocusedWindowTokenByDisplay) {
4393 const int32_t displayId = it.first;
4394 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4395 if (windowHandle) {
4396 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4397 windowHandle->getName().c_str());
4398 } else {
4399 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4400 " has focused token without a window'\n",
4401 displayId);
4402 }
4403 }
4404 return dump;
4405}
4406
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004407void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004408 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4409 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4410 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004411 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412
Tiger Huang721e26f2018-07-24 22:26:19 +08004413 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4414 dump += StringPrintf(INDENT "FocusedApplications:\n");
4415 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4416 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004417 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004418 const std::chrono::duration timeout =
4419 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004421 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004422 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004425 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004427
Vishnu Nairad321cd2020-08-20 16:40:21 -07004428 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004430 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004431 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004432 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4433 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004434 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004435 state.displayId, toString(state.down), toString(state.split),
4436 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004437 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004438 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004439 for (size_t i = 0; i < state.windows.size(); i++) {
4440 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 dump += StringPrintf(INDENT4
4442 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4443 i, touchedWindow.windowHandle->getName().c_str(),
4444 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004445 }
4446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004447 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004448 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004449 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004450 dump += INDENT3 "Portal windows:\n";
4451 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004452 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004453 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4454 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004455 }
4456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 }
4458 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004459 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 }
4461
Arthur Hungb92218b2018-08-14 12:00:21 +08004462 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004463 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004464 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004465 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004466 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004467 dump += INDENT2 "Windows:\n";
4468 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004469 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004470 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471
Arthur Hungb92218b2018-08-14 12:00:21 +08004472 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004473 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4474 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004475 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004476 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004477 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004478 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479 i, windowInfo->name.c_str(), windowInfo->displayId,
4480 windowInfo->portalToDisplayId,
4481 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004482 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004483 toString(windowInfo->hasWallpaper),
4484 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004485 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004486 static_cast<int32_t>(windowInfo->type),
4487 windowInfo->frameLeft, windowInfo->frameTop,
4488 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004489 windowInfo->globalScaleFactor,
4490 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004491 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004492 dump += StringPrintf(", inputFeatures=%s",
4493 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004494 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004495 "ms, trustedOverlay=%s, hasToken=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004497 millis(windowInfo->dispatchingTimeout),
4498 toString(windowInfo->trustedOverlay),
4499 toString(windowInfo->token != nullptr));
chaviw85b44202020-07-24 11:46:21 -07004500 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004501 }
4502 } else {
4503 dump += INDENT2 "Windows: <none>\n";
4504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 }
4506 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004507 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 }
4509
Michael Wright3dd60e22019-03-27 22:06:44 +00004510 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004512 const std::vector<Monitor>& monitors = it.second;
4513 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4514 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 }
4516 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004517 const std::vector<Monitor>& monitors = it.second;
4518 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4519 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004522 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524
4525 nsecs_t currentTime = now();
4526
4527 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004528 if (!mRecentQueue.empty()) {
4529 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004530 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004531 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004532 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004533 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 }
4535 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004536 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 }
4538
4539 // Dump event currently being dispatched.
4540 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004541 dump += INDENT "PendingEvent:\n";
4542 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004543 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004544 dump += StringPrintf(", age=%" PRId64 "ms\n",
4545 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004547 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 }
4549
4550 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004551 if (!mInboundQueue.empty()) {
4552 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004553 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004554 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004555 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004556 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004559 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 }
4561
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004562 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004563 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004564 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4565 const KeyReplacement& replacement = pair.first;
4566 int32_t newKeyCode = pair.second;
4567 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004568 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004569 }
4570 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004571 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004572 }
4573
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004574 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004575 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004576 for (const auto& pair : mConnectionsByFd) {
4577 const sp<Connection>& connection = pair.second;
4578 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004580 pair.first, connection->getInputChannelName().c_str(),
4581 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004582 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004584 if (!connection->outboundQueue.empty()) {
4585 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4586 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004587 dump += dumpQueue(connection->outboundQueue, currentTime);
4588
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004590 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 }
4592
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004593 if (!connection->waitQueue.empty()) {
4594 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4595 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004596 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004598 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600 }
4601 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004602 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604
4605 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004606 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4607 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004609 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 }
4611
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004612 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004613 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4614 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4615 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616}
4617
Michael Wright3dd60e22019-03-27 22:06:44 +00004618void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4619 const size_t numMonitors = monitors.size();
4620 for (size_t i = 0; i < numMonitors; i++) {
4621 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004622 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004623 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4624 dump += "\n";
4625 }
4626}
4627
Garfield Tan15601662020-09-22 15:32:38 -07004628base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4629 const std::string& name) {
4630#if DEBUG_CHANNEL_CREATION
4631 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632#endif
4633
Garfield Tan15601662020-09-22 15:32:38 -07004634 std::shared_ptr<InputChannel> serverChannel;
4635 std::unique_ptr<InputChannel> clientChannel;
4636 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4637
4638 if (result) {
4639 return base::Error(result) << "Failed to open input channel pair with name " << name;
4640 }
4641
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004643 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004644 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
Garfield Tan15601662020-09-22 15:32:38 -07004646 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004647 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004648 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4651 } // release lock
4652
4653 // Wake the looper because some connections have changed.
4654 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004655 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656}
4657
Garfield Tan15601662020-09-22 15:32:38 -07004658base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4659 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4660 std::shared_ptr<InputChannel> serverChannel;
4661 std::unique_ptr<InputChannel> clientChannel;
4662 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4663 if (result) {
4664 return base::Error(result) << "Failed to open input channel pair with name " << name;
4665 }
4666
Michael Wright3dd60e22019-03-27 22:06:44 +00004667 { // acquire lock
4668 std::scoped_lock _l(mLock);
4669
4670 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004671 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4672 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004673 }
4674
Garfield Tan15601662020-09-22 15:32:38 -07004675 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004676
Garfield Tan15601662020-09-22 15:32:38 -07004677 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004678 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004679 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004680
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004681 auto& monitorsByDisplay =
4682 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004683 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004684
4685 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004686 }
Garfield Tan15601662020-09-22 15:32:38 -07004687
Michael Wright3dd60e22019-03-27 22:06:44 +00004688 // Wake the looper because some connections have changed.
4689 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004690 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004691}
4692
Garfield Tan15601662020-09-22 15:32:38 -07004693status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004695 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
Garfield Tan15601662020-09-22 15:32:38 -07004697 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 if (status) {
4699 return status;
4700 }
4701 } // release lock
4702
4703 // Wake the poll loop because removing the connection may have changed the current
4704 // synchronization state.
4705 mLooper->wake();
4706 return OK;
4707}
4708
Garfield Tan15601662020-09-22 15:32:38 -07004709status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4710 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004711 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004712 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004713 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 return BAD_VALUE;
4715 }
4716
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004717 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004718 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004719
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004721 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 }
4723
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004724 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
4726 nsecs_t currentTime = now();
4727 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4728
4729 connection->status = Connection::STATUS_ZOMBIE;
4730 return OK;
4731}
4732
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004733void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4734 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4735 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004736}
4737
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004738void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004739 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004740 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004742 std::vector<Monitor>& monitors = it->second;
4743 const size_t numMonitors = monitors.size();
4744 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004745 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746 monitors.erase(monitors.begin() + i);
4747 break;
4748 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004749 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004750 if (monitors.empty()) {
4751 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004752 } else {
4753 ++it;
4754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
4756}
4757
Michael Wright3dd60e22019-03-27 22:06:44 +00004758status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4759 { // acquire lock
4760 std::scoped_lock _l(mLock);
4761 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4762
4763 if (!foundDisplayId) {
4764 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4765 return BAD_VALUE;
4766 }
4767 int32_t displayId = foundDisplayId.value();
4768
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004769 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4770 mTouchStatesByDisplay.find(displayId);
4771 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004772 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4773 return BAD_VALUE;
4774 }
4775
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004776 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004777 std::optional<int32_t> foundDeviceId;
4778 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004779 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004780 foundDeviceId = state.deviceId;
4781 }
4782 }
4783 if (!foundDeviceId || !state.down) {
4784 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004786 return BAD_VALUE;
4787 }
4788 int32_t deviceId = foundDeviceId.value();
4789
4790 // Send cancel events to all the input channels we're stealing from.
4791 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004793 options.deviceId = deviceId;
4794 options.displayId = displayId;
4795 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004796 std::shared_ptr<InputChannel> channel =
4797 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004798 if (channel != nullptr) {
4799 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4800 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004801 }
4802 // Then clear the current touch state so we stop dispatching to them as well.
4803 state.filterNonMonitors();
4804 }
4805 return OK;
4806}
4807
Michael Wright3dd60e22019-03-27 22:06:44 +00004808std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4809 const sp<IBinder>& token) {
4810 for (const auto& it : mGestureMonitorsByDisplay) {
4811 const std::vector<Monitor>& monitors = it.second;
4812 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004813 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004814 return it.first;
4815 }
4816 }
4817 }
4818 return std::nullopt;
4819}
4820
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004821sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004822 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004823 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004824 }
4825
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004826 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004827 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004828 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004829 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831 }
Robert Carr4e670e52018-08-15 13:26:12 -07004832
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004833 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834}
4835
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004836void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004838 removeByValue(mConnectionsByFd, connection);
4839}
4840
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004841void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4842 const sp<Connection>& connection, uint32_t seq,
4843 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004844 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4845 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 commandEntry->connection = connection;
4847 commandEntry->eventTime = currentTime;
4848 commandEntry->seq = seq;
4849 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004850 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851}
4852
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004853void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4854 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004856 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004858 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4859 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004861 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862}
4863
Vishnu Nairad321cd2020-08-20 16:40:21 -07004864void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4865 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004866 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4867 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004868 commandEntry->oldToken = oldToken;
4869 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004870 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004871}
4872
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004873void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4875 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004876 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004878 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879 return;
4880 }
4881 /**
4882 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4883 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4884 * has changed. This could cause newer entries to time out before the already dispatched
4885 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4886 * processes the events linearly. So providing information about the oldest entry seems to be
4887 * most useful.
4888 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004889 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4891 std::string reason =
4892 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004893 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894 ns2ms(currentWait),
4895 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004897 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898 reason);
4899
4900 std::unique_ptr<CommandEntry> commandEntry =
4901 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4902 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05004903 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 commandEntry->reason = std::move(reason);
4905 postCommandLocked(std::move(commandEntry));
4906}
4907
Chris Yea209fde2020-07-22 13:54:51 -07004908void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004909 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4910 application->getName().c_str());
4911
4912 updateLastAnrStateLocked(application, reason);
4913
4914 std::unique_ptr<CommandEntry> commandEntry =
4915 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4916 commandEntry->inputApplicationHandle = application;
4917 commandEntry->inputChannel = nullptr;
4918 commandEntry->reason = std::move(reason);
4919 postCommandLocked(std::move(commandEntry));
4920}
4921
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00004922void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
4923 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4924 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
4925 commandEntry->obscuringPackage = obscuringPackage;
4926 postCommandLocked(std::move(commandEntry));
4927}
4928
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4930 const std::string& reason) {
4931 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4932 updateLastAnrStateLocked(windowLabel, reason);
4933}
4934
Chris Yea209fde2020-07-22 13:54:51 -07004935void InputDispatcher::updateLastAnrStateLocked(
4936 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004937 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4938 updateLastAnrStateLocked(windowLabel, reason);
4939}
4940
4941void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4942 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004944 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 struct tm tm;
4946 localtime_r(&t, &tm);
4947 char timestr[64];
4948 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004949 mLastAnrState.clear();
4950 mLastAnrState += INDENT "ANR:\n";
4951 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004952 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4953 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004954 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955}
4956
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 mLock.unlock();
4959
4960 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4961
4962 mLock.lock();
4963}
4964
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004965void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 sp<Connection> connection = commandEntry->connection;
4967
4968 if (connection->status != Connection::STATUS_ZOMBIE) {
4969 mLock.unlock();
4970
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004971 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
4973 mLock.lock();
4974 }
4975}
4976
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004977void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004978 sp<IBinder> oldToken = commandEntry->oldToken;
4979 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004980 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004981 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004982 mLock.lock();
4983}
4984
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004985void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004986 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004987 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 mLock.unlock();
4989
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004990 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004991 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992
4993 mLock.lock();
4994
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004995 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4997 } else {
4998 // stop waking up for events in this connection, it is already not responding
4999 sp<Connection> connection = getConnectionLocked(token);
5000 if (connection == nullptr) {
5001 return;
5002 }
5003 cancelEventsForAnrLocked(connection);
5004 }
5005}
5006
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005007void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5008 mLock.unlock();
5009
5010 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5011
5012 mLock.lock();
5013}
5014
Chris Yea209fde2020-07-22 13:54:51 -07005015void InputDispatcher::extendAnrTimeoutsLocked(
5016 const std::shared_ptr<InputApplicationHandle>& application,
5017 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005018 if (connectionToken == nullptr && application != nullptr) {
5019 // The ANR happened because there's no focused window
5020 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
5021 mAwaitedFocusedApplication = application;
5022 }
5023
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024 sp<Connection> connection = getConnectionLocked(connectionToken);
5025 if (connection == nullptr) {
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005026 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005027 return;
5028 }
5029
5030 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005031 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005032
5033 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05005034 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005035 for (DispatchEntry* entry : connection->waitQueue) {
5036 if (newTimeout >= entry->timeoutTime) {
5037 // Already removed old entries when connection was marked unresponsive
5038 entry->timeoutTime = newTimeout;
5039 mAnrTracker.insert(entry->timeoutTime, connectionToken);
5040 }
5041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005042}
5043
5044void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5045 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005046 KeyEntry& entry = *(commandEntry->keyEntry);
5047 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048
5049 mLock.unlock();
5050
Michael Wright2b3c3302018-03-02 17:19:13 +00005051 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005052 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005053 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005054 : nullptr;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005055 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005056 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5057 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060
5061 mLock.lock();
5062
5063 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005064 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005066 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005068 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5069 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071}
5072
chaviwfd6d3512019-03-25 13:23:49 -07005073void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5074 mLock.unlock();
5075 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5076 mLock.lock();
5077}
5078
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005079/**
5080 * Connection is responsive if it has no events in the waitQueue that are older than the
5081 * current time.
5082 */
5083static bool isConnectionResponsive(const Connection& connection) {
5084 const nsecs_t currentTime = now();
5085 for (const DispatchEntry* entry : connection.waitQueue) {
5086 if (entry->timeoutTime < currentTime) {
5087 return false;
5088 }
5089 }
5090 return true;
5091}
5092
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005093void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005095 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005097 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098
5099 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005100 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005101 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005102 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005104 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005105 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005106 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005107 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5108 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005109 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005110 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005111
5112 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005113 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005114 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005115 restartEvent =
5116 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005117 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005118 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005119 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5120 handled);
5121 } else {
5122 restartEvent = false;
5123 }
5124
5125 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005126 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005127 // contents of the wait queue to have been drained, so we need to double-check
5128 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005129 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5130 if (dispatchEntryIt != connection->waitQueue.end()) {
5131 dispatchEntry = *dispatchEntryIt;
5132 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005133 mAnrTracker.erase(dispatchEntry->timeoutTime,
5134 connection->inputChannel->getConnectionToken());
5135 if (!connection->responsive) {
5136 connection->responsive = isConnectionResponsive(*connection);
5137 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005138 traceWaitQueueLength(connection);
5139 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005140 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005141 traceOutboundQueueLength(connection);
5142 } else {
5143 releaseDispatchEntry(dispatchEntry);
5144 }
5145 }
5146
5147 // Start the next dispatch cycle for this connection.
5148 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149}
5150
5151bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005152 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005153 KeyEntry& keyEntry, bool handled) {
5154 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005155 if (!handled) {
5156 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005157 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005158 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005159 return false;
5160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005162 // Get the fallback key state.
5163 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005164 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005165 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005166 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005167 connection->inputState.removeFallbackKey(originalKeyCode);
5168 }
5169
5170 if (handled || !dispatchEntry->hasForegroundTarget()) {
5171 // If the application handles the original key for which we previously
5172 // generated a fallback or if the window is not a foreground window,
5173 // then cancel the associated fallback key, if any.
5174 if (fallbackKeyCode != -1) {
5175 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005177 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005178 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005179 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005181 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005182 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183
5184 mLock.unlock();
5185
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005186 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005187 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188
5189 mLock.lock();
5190
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005191 // Cancel the fallback key.
5192 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005194 "application handled the original non-fallback key "
5195 "or is no longer a foreground target, "
5196 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 options.keyCode = fallbackKeyCode;
5198 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005200 connection->inputState.removeFallbackKey(originalKeyCode);
5201 }
5202 } else {
5203 // If the application did not handle a non-fallback key, first check
5204 // that we are in a good state to perform unhandled key event processing
5205 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005206 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005207 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005209 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005210 "since this is not an initial down. "
5211 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005212 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005214 return false;
5215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005217 // Dispatch the unhandled key to the policy.
5218#if DEBUG_OUTBOUND_EVENT_DETAILS
5219 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005220 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005221 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005222#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005223 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005224
5225 mLock.unlock();
5226
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005227 bool fallback =
5228 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005229 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005230
5231 mLock.lock();
5232
5233 if (connection->status != Connection::STATUS_NORMAL) {
5234 connection->inputState.removeFallbackKey(originalKeyCode);
5235 return false;
5236 }
5237
5238 // Latch the fallback keycode for this key on an initial down.
5239 // The fallback keycode cannot change at any other point in the lifecycle.
5240 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005242 fallbackKeyCode = event.getKeyCode();
5243 } else {
5244 fallbackKeyCode = AKEYCODE_UNKNOWN;
5245 }
5246 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5247 }
5248
5249 ALOG_ASSERT(fallbackKeyCode != -1);
5250
5251 // Cancel the fallback key if the policy decides not to send it anymore.
5252 // We will continue to dispatch the key to the policy but we will no
5253 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005254 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5255 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005256#if DEBUG_OUTBOUND_EVENT_DETAILS
5257 if (fallback) {
5258 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005259 "as a fallback for %d, but on the DOWN it had requested "
5260 "to send %d instead. Fallback canceled.",
5261 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005262 } else {
5263 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005264 "but on the DOWN it had requested to send %d. "
5265 "Fallback canceled.",
5266 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005267 }
5268#endif
5269
5270 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5271 "canceling fallback, policy no longer desires it");
5272 options.keyCode = fallbackKeyCode;
5273 synthesizeCancelationEventsForConnectionLocked(connection, options);
5274
5275 fallback = false;
5276 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005277 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005278 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005279 }
5280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281
5282#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005283 {
5284 std::string msg;
5285 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5286 connection->inputState.getFallbackKeys();
5287 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005288 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005290 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005291 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005292 }
5293#endif
5294
5295 if (fallback) {
5296 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005297 keyEntry.eventTime = event.getEventTime();
5298 keyEntry.deviceId = event.getDeviceId();
5299 keyEntry.source = event.getSource();
5300 keyEntry.displayId = event.getDisplayId();
5301 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5302 keyEntry.keyCode = fallbackKeyCode;
5303 keyEntry.scanCode = event.getScanCode();
5304 keyEntry.metaState = event.getMetaState();
5305 keyEntry.repeatCount = event.getRepeatCount();
5306 keyEntry.downTime = event.getDownTime();
5307 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005308
5309#if DEBUG_OUTBOUND_EVENT_DETAILS
5310 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005311 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005312 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005313#endif
5314 return true; // restart the event
5315 } else {
5316#if DEBUG_OUTBOUND_EVENT_DETAILS
5317 ALOGD("Unhandled key event: No fallback key.");
5318#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005319
5320 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005321 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322 }
5323 }
5324 return false;
5325}
5326
5327bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005328 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005329 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 return false;
5331}
5332
5333void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5334 mLock.unlock();
5335
5336 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5337
5338 mLock.lock();
5339}
5340
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005341KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5342 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005343 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005344 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5345 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005346 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347}
5348
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005349void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5350 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 // TODO Write some statistics about how long we spend waiting.
5352}
5353
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005354/**
5355 * Report the touch event latency to the statsd server.
5356 * Input events are reported for statistics if:
5357 * - This is a touchscreen event
5358 * - InputFilter is not enabled
5359 * - Event is not injected or synthesized
5360 *
5361 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5362 * from getting aggregated with the "old" data.
5363 */
5364void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5365 REQUIRES(mLock) {
5366 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5367 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5368 if (!reportForStatistics) {
5369 return;
5370 }
5371
5372 if (mTouchStatistics.shouldReport()) {
5373 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5374 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5375 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5376 mTouchStatistics.reset();
5377 }
5378 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5379 mTouchStatistics.addValue(latencyMicros);
5380}
5381
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382void InputDispatcher::traceInboundQueueLengthLocked() {
5383 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005384 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 }
5386}
5387
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005388void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 if (ATRACE_ENABLED()) {
5390 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005391 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005392 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394}
5395
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005396void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 if (ATRACE_ENABLED()) {
5398 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005399 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005400 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 }
5402}
5403
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005404void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005405 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005407 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 dumpDispatchStateLocked(dump);
5409
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005410 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005411 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005412 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414}
5415
5416void InputDispatcher::monitor() {
5417 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005418 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005420 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421}
5422
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005423/**
5424 * Wake up the dispatcher and wait until it processes all events and commands.
5425 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5426 * this method can be safely called from any thread, as long as you've ensured that
5427 * the work you are interested in completing has already been queued.
5428 */
5429bool InputDispatcher::waitForIdle() {
5430 /**
5431 * Timeout should represent the longest possible time that a device might spend processing
5432 * events and commands.
5433 */
5434 constexpr std::chrono::duration TIMEOUT = 100ms;
5435 std::unique_lock lock(mLock);
5436 mLooper->wake();
5437 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5438 return result == std::cv_status::no_timeout;
5439}
5440
Vishnu Naire798b472020-07-23 13:52:21 -07005441/**
5442 * Sets focus to the window identified by the token. This must be called
5443 * after updating any input window handles.
5444 *
5445 * Params:
5446 * request.token - input channel token used to identify the window that should gain focus.
5447 * request.focusedToken - the token that the caller expects currently to be focused. If the
5448 * specified token does not match the currently focused window, this request will be dropped.
5449 * If the specified focused token matches the currently focused window, the call will succeed.
5450 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5451 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5452 * when requesting the focus change. This determines which request gets
5453 * precedence if there is a focus change request from another source such as pointer down.
5454 */
Vishnu Nair958da932020-08-21 17:12:37 -07005455void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5456 { // acquire lock
5457 std::scoped_lock _l(mLock);
5458
5459 const int32_t displayId = request.displayId;
5460 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5461 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5462 ALOGD_IF(DEBUG_FOCUS,
5463 "setFocusedWindow on display %" PRId32
5464 " ignored, reason: focusedToken is not focused",
5465 displayId);
5466 return;
5467 }
5468
5469 mPendingFocusRequests.erase(displayId);
5470 FocusResult result = handleFocusRequestLocked(request);
5471 if (result == FocusResult::NOT_VISIBLE) {
5472 // The requested window is not currently visible. Wait for the window to become visible
5473 // and then provide it focus. This is to handle situations where a user action triggers
5474 // a new window to appear. We want to be able to queue any key events after the user
5475 // action and deliver it to the newly focused window. In order for this to happen, we
5476 // take focus from the currently focused window so key events can be queued.
5477 ALOGD_IF(DEBUG_FOCUS,
5478 "setFocusedWindow on display %" PRId32
5479 " pending, reason: window is not visible",
5480 displayId);
5481 mPendingFocusRequests[displayId] = request;
5482 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5483 "setFocusedWindow_AwaitingWindowVisibility");
5484 } else if (result != FocusResult::OK) {
5485 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5486 typeToString(result));
5487 }
5488 } // release lock
5489 // Wake up poll loop since it may need to make new input dispatching choices.
5490 mLooper->wake();
5491}
5492
5493InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5494 const FocusRequest& request) {
5495 const int32_t displayId = request.displayId;
5496 const sp<IBinder> newFocusedToken = request.token;
5497 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5498
5499 if (oldFocusedToken == request.token) {
5500 ALOGD_IF(DEBUG_FOCUS,
5501 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5502 displayId);
5503 return FocusResult::OK;
5504 }
5505
5506 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5507 if (result != FocusResult::OK) {
5508 return result;
5509 }
5510
5511 std::string_view reason =
5512 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5513 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5514 return FocusResult::OK;
5515}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005516
Vishnu Nairad321cd2020-08-20 16:40:21 -07005517void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5518 const sp<IBinder>& newFocusedToken, int32_t displayId,
5519 std::string_view reason) {
5520 if (oldFocusedToken) {
5521 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005522 if (focusedInputChannel) {
5523 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5524 "focus left window");
5525 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005526 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005527 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005528 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005529 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005530 if (newFocusedToken) {
5531 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5532 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005533 }
5534
5535 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005536 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005537 }
5538}
Vishnu Nair958da932020-08-21 17:12:37 -07005539
5540/**
5541 * Checks if the window token can be focused on a display. The token can be focused if there is
5542 * at least one window handle that is visible with the same token and all window handles with the
5543 * same token are focusable.
5544 *
5545 * In the case of mirroring, two windows may share the same window token and their visibility
5546 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5547 * we expect the focusability of the windows to match since its hard to reason why one window can
5548 * receive focus events and the other cannot when both are backed by the same input channel.
5549 */
5550InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5551 int32_t displayId) const {
5552 bool allWindowsAreFocusable = true;
5553 bool visibleWindowFound = false;
5554 bool windowFound = false;
5555 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5556 if (window->getToken() != token) {
5557 continue;
5558 }
5559 windowFound = true;
5560 if (window->getInfo()->visible) {
5561 // Check if at least a single window is visible.
5562 visibleWindowFound = true;
5563 }
5564 if (!window->getInfo()->focusable) {
5565 // Check if all windows with the window token are focusable.
5566 allWindowsAreFocusable = false;
5567 break;
5568 }
5569 }
5570
5571 if (!windowFound) {
5572 return FocusResult::NO_WINDOW;
5573 }
5574 if (!allWindowsAreFocusable) {
5575 return FocusResult::NOT_FOCUSABLE;
5576 }
5577 if (!visibleWindowFound) {
5578 return FocusResult::NOT_VISIBLE;
5579 }
5580
5581 return FocusResult::OK;
5582}
Garfield Tane84e6f92019-08-29 17:28:41 -07005583} // namespace android::inputdispatcher